Reputation: 585
I need to use the $.ajax()
call within jQuery to post a little bit of JSON to my PHP script.
I have tried everything but nothing works as I would like it to. I simply try to echo a var_dump of the $_POST/$_GET arrays but it comes back empty.
var myJSONObject = {"bindings": [{"conversation": _conid} ]};
var obj = $.toJSON(myJSONObject);
$.ajax({
type: "POST",
url: "./code/ajax/fetch_messages.php",
data: obj,
async:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
},
beforeSend: function (XMLHttpRequest)
{
},
complete: function (XMLHttpRequest, textStatus)
{
}});
I can see that the post is made by looking in the headers:
{"bindings":[{"conversation":"38x001c61450ad4d5abd47c37408e8236eb5427f54e2930000306882646e4016c5f8ecf8e00a18a26ab3b6d07f6727bd187625daaedf951f93072d54d59e300e100"}]}
PHP:
echo var_dump($_POST);
Everything works great when using the $.post()
call but I always run in to problems when I try to switch to $.ajax
. I need to use it to be able to retreive the response UTF-8 encoded.
The code pasted in this post is just one of many snippets I've tried, even examples from tutorials on the web does not work.
Could someone please give me a snippet that you know do work so I can try that? Sending JSON through POST.
Upvotes: 0
Views: 157
Reputation: 1955
below is a slice of my routine and it works fine :
var data = 'post_type=' + post_type.val() + '&page_id=' +
page_id.val() + '&home_page='
+ home_page.attr('checked') + '&archive_page=' +
archive_page.attr('checked') + '&search_page=' +
search_page.attr('checked');
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "?service=set_data",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: true,
//success
success: function (html) {
$(".no-items").hide("slow");
$("#list_table").append(html).hide().slideDown('slow');
}
});
Upvotes: 1
Reputation: 71908
I think you must give your json string a key, so you can get it on the other side (PHP):
data: {"myjson": obj},
Then on PHP it will be in $_POST['myjson']
Upvotes: 1