mikeyy
mikeyy

Reputation: 933

jQuery json ajax function

I am having a kind of a weird problem, or maybe I do not understand how js and jQuery is working.

I have a small js that is sending an id and a value using AJAX. After a lot of experimentation I finally found a working solution which is:

$.post('dashboard/xhrDeleteListing', "id=" + id, function() {
    alert(1);
}); 

However, I would like to use json format for the data part of the call. So what I did (to make sure that my JSON is correct) was the following:

var myJSON = {
    id: id
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
    alert(1);
}, 'json'); 

But this didn't work. First, php server didn't get anything (nothing in $_POST), second, the callback function didn't run (alert(1) was never executed). To my surprise, the following call did create a $_POST['id'] value:

$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
    alert(1);
}, 'json');         

but again the callback function didn't run. It only run after removal of 'json' datatype argument).

The version of jQuery is v1.11.0.

Can anyone help me to figure out what am I doing wrong?

Regards,

Upvotes: 0

Views: 101

Answers (3)

Makrand
Makrand

Reputation: 587

Try this :

 $.ajax({
    url: 'dashboard/xhrDeleteListing',
    type : 'POST',
    dataType : 'json',
    data: {
      'id':id,
    },
     success : function(callback_record) {
       alert(callback_record);
    }
  });

Upvotes: 0

Mehran Hatami
Mehran Hatami

Reputation: 12961

The important point here is when you do this like:

$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
    alert(1);
}, 'json'); 

the 'json' paramter is the dataType of data expected from the server, not from you to send.

It means in your backend after doing your server side task you have to return a valid json string but it seems you want to do a server action without any return value, that's why you have to remove 'json' from your arguments.

Upvotes: 1

Prashobh
Prashobh

Reputation: 9542

var myJSON = {
    "id": "id"
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
    alert(1);
}, 'json'); 

Upvotes: 0

Related Questions