0

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,

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

The id is a value. With your declaration "id" : "id" I am getting {"id":"id"}. But I did try "id": id, which generated {"id":"25"} which in turn didn't work either...
0

Try this :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.