Mark D
Mark D

Reputation: 3

Jquery Ajax not sending data to php server

This will be an easy one for you, but after ages of looking online I can't find a solution, or at least one I'm understanding.

result and users variables both alert correctly. The data contents shows empty - why?

How should I be inserting these two variables into data ?

(also if it is right - how do I view the data content without going into server side)

Thank you in advance.

        var result = result.text;
        var users = localStorage.getItem('user');
         alert("1");
               $.ajax({
   url:'********',
   method: 'POST',
   data: {user: users, serial: result},
   dataType: "text",
   contentType: "application/json",
   success: function(data){


       alert (data);
       alert(users);
       alert(result);

Upvotes: 0

Views: 52

Answers (1)

adiga
adiga

Reputation: 35259

In your code alert(data) will refer to the data returned by the server. Not the data of your ajax request.

$.ajax() takes a settings object as its parameter. It's a set of key/value pairs that configure the Ajax request. data is just one of the keys of the object you are passing to the $.ajax() method.

To simplify your code, this is what is happening:

// this is what you're sending to the server
var dataSentToTheServer = {
    user: users,
    serial: result 
}

// creating an object where data, url, success etc are keys.
var settings = {
    url:'api/method',
    method: 'POST',
    data: dataSentToTheServer,
    dataType: "text",
    success: function (dataSentFromTheServer) {
        alert(dataSentFromTheServer); // this argument will have the data returned by your server
        alert(dataSentToTheServer); // data which was sent *to* the server
        alert(data); // doesn't exist
    }
    ....
}

$.ajax(settings);

Upvotes: 1

Related Questions