0
$.ajax({
        url: 'test.php',
        type: 'GET',
        dataType: 'json',
        data: "last_name=SMITH&first_name=JOHN&middle_name=J",
        contentType: "application/json; charset=utf-8",
        success: function(response) {
            var len = response.length;
            for (var i = 0; i < len; i++) {
             var name = response[i].LASTNAME + ", " + response[i].FIRSTNAME + " " + response[i].MIDDLE
             var sysid = response[i].ORDERID
             $("<li></li>")
             .html("<a href='result.php?orderid=" + orderid + "'>" + name + "</a>")
             .insertAfter($("#questions-divider"));
             $("#questions").listview("refresh"); 
            }

        }
   });
});

This works with GET. I tried it with post and it failed. I have _POST in my php page. I changed the data parameter to be:

data: '{ "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" }',

But this fails also (with get and post). My php page returns that it can't find last_name in my payload. $_POST['last_name'] never gets the data in my php page. Send it with GET and it works (I changed my php to use $_GET for testing then back to $_POST).

edit: I tried this but it did not help: Cant get jQuery ajax POST to work

edit: also: jquery $.post empty array

edit: I was able to get like this. Don't know why the formatted data fails:

//data: '{ "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" }',
    data: "last_name=SMITH&first_name=JOHN&middle_name=J",
    //contentType: "application/json; charset=utf-8",
    contentType: "application/x-www-form-urlencoded",
Community
  • 1
  • 1
johnny
  • 19,272
  • 52
  • 157
  • 259

2 Answers2

3

Remove the quotes to make data's value an object. Should read:

data: { "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" },

Kenaniah
  • 5,171
  • 24
  • 27
3

Here is the simple $.ajax template I use all the time. It works for everything. You data value should be an object.

$.ajax({
    type: "POST",
    url: "ajax.php",                             // Your URL
    //data: "action=whatever&user=" + username,  // You can do it like this.
    data: {name: data, action: "whatever"},      // Or like this, Notice the Quotes
    dataType: "html",                            // The Return Type of the data
    success: function(xhr){                      // Success! :)
        alert("success, ajax post was success");
    },
    error: function (xhr, ajaxOptions, thrownError){ // Your a failure :(
        alert(xhr.status);
        alert(thrownError);
    }
});

Your currently passing a string to the data, it needs to be an object:

Yours:

data: '{ "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" }',

Should be

data: { "last_name": "SMITH", "first_name": "JOHN", "middle_name": "J" },
Anil
  • 21,730
  • 9
  • 73
  • 100