Back-End Development PHP and database

Passing data to php script using Ajax

Passing data to php script using Ajax – here we will use j query to get data from inputs and then create an Ajax method to pass data to php script (asynchronous request).

Ajax is sued to asynchronously send data to a script. By asynchronous we mean that the user can continue doing some other tasks at the front end till the script is being executed. User need not wait for response.

Passing data to php script using Ajax -steps

  1. Creating a form

    The type attribute is set to button, because we are going to send data using a function in an asynchronous way.Setting type=”submit” will cause synchronous transfer of data and also page reloading or re-direction.

  2. Getting input values using jQuery

    val() function is jQuery’s built in function to get the input values.

  3. Building $.ajax() method to send data to php script

    This method is used to perform asynchronous requests. All jQuery Ajax methods use ajax() function.

    where the name:value pairs can hold many values. The most commonly used are:

    Name Value
    type Specifies the type of request (GET or POST)
    url Specifies the URL to send the request to. Default is the current page
    data Specifies the data that is to be sent
    async A Boolean value that indicates whether the request should be handled asynchronously or not. Default is true
    success(result,status,xhr) A function to be run when the request succeeds

    function will be:

    add-user.php is the php script to handle the request.
    var dataTosend='user='+data1+'&pwd='+data2; is the variable holding the form in which data is actually sent to the server. Suppose user=scanfcode&pwd=123456 would be the sent data according to the values.
    Names “user” and “pwd” in the query above will be used to fetch these data in php script.

  4. Creating the php handler script

    Let the data received be user=scanfcode&pwd=123456.
    We will be using the post method to get data, since the data request type is post.