I'm running into a problem with JQuery Mobile (new to me) and the AJAX-call. I'm using the following code:
$.ajax({
type: "POST",
url: "http://**correct url**/post/todoitem",
beforeSend: addHeaders,
dataType: "json",
contentType: "application/json",
data: { "todoitem":"test" }, // this is just as a test
success: function(result) {
alert("Success: " + JSON.stringify(result));
},
error: function() {
alert("Error: " + JSON.stringify(arguments));
}
});
While executing this, it calls a PHP script where I need the data from the todoitem, so in this case the string "text" (in the end, multiple variables are to be send, but for now I'm just using one parameter for simplicity).
My PHP code looks like this (also just for testing purposes):
echo json_encode($_POST));
The result is: nothing, null. The $_POST seems to be empty. I've searched and tried many things, but most answers (even here on stackoverflow) are about forms and people say I need to serialize the contents of the form. However, I'm not using a form at all.
I also tried
data: JSON.stringify({ "todoitem" : "test" })
as some suggested but this did not work either.
I do know that the data is being transfered because of this little PHP hack I tried:
echo file_get_contents('php://input');
That exactly shows the data: todoitem = test. So where does this all go wrong? I'm working on this for days now! Thnx in advance
The problem is with this part of your code:
contentType: "application/json",`
Removing that line should make the sent Content-Type header default to application/x-www-form-urlencoded and PHP will decode the request into $_POST.
Related
When I send serialised data to a PHP file using ajax, it is sometimes URL Encoded depending on how i do it.
Originally i had the following code which worked fine:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: $("#sitestructure-form").serialize(),
success: function(d){$("#structureupdate").html(d);}
});
The data was sent to my PHP file and i could echo it and it looked like this.
[{"id":20,"children":[{"id":21}]},{"id":19},{"id":18,"children":[{"id":14}]},{"id":16},{"id":13,"children":[{"id":11}]},{"id":17},{"id":15},{"id":12}]
I wanted to send more than one piece of data, I called the serialized data 'order' and added 'process' to it so i updated my code to the following:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: {
order: $("#sitestructure-form").serialize(),
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
However when I retrieve the serialised data sent in 'order' the output looks like this:
data=%5B%7B%22id%22%3A20%2C%22children%22%3A%5B%7B%22id%22%3A21%7D%5D%7D%2C%7B%22id%22%3A19%7D%2C%7B%22id%22%3A18%2C%22children%22%3A%5B%7B%22id%22%3A14%7D%5D%7D%2C%7B%22id%22%3A16%7D%2C%7B%22id%22%3A13%2C%22children%22%3A%5B%7B%22id%22%3A11%7D%5D%7D%2C%7B%22id%22%3A17%7D%2C%7B%22id%22%3A15%7D%2C%7B%22id%22%3A12%7D%5D
The only way i can think of to fix this problem is to use php to urldecode it and then use str_replace to remove the 'data=' bit at the front, like so.
$data = str_replace("data=","",urldecode($_POST['order']));
How can I get this to work with AJAX though so i dont have to urldecode it?
Ive tried using a variable and setting the processData to false however that didn't seem to work.
var order = $("#sitestructure-form").serialize();
$.ajax({
type: 'POST',
url: 'ajax-process.php',
processData: false,
data: {
order: order,
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
My knowledge of AJAX/Jquery is rather limited so any help would be greatly appreciated.
That's because you are feeding a serialized text string to the data attribute the first time around and jQuery does not convert it to a serialized string. The second you are assigning an object to the data attribute with the "order" attribute having the serialized text string, so jQuery basically double encodes it. For it to act as you'd like you would have to convert the form to an object and assign your "order" attribute to that object. See this post: Convert form data to JavaScript object with jQuery
// taking the example from the above link, you do this instead
order = $("#sitestructure-form"). serializeObject();
Fixed by doing the following:
$.ajax({
type: 'POST',
url: 'ajax-process.php?',
data: $("#sitestructure-form").serialize() + "&action=sitemap-reordernavigation",
success: function(d){$("#structureupdate").html(d);}
});
Hmm I have a little problem with that :
$.ajax({
type: 'POST',
data: {
name : 'aatrox'
},
dataType: "json",
async:false,
url: 'appliserv/testsendajax.php',
success: function(data){
console.log(data);
alert('good');
},
error: function(data){
console.log(data);
alert(fail);
}
});
the text in the alert is always fail ....
in my serv :
$text = $_POST['name'];
echo $text;
and I don't understand that. Thanks (sry if my english isn't good)
Your server-side script output plain text. So you have to change value of dataType option.
Change this:
dataType: "json"
to this:
dataType: "text"
Quite likely you're getting a parse error. This is because your ajax request is expecting JSON but you're are returning a plain string. Either return JSON from your PHP script or change the dataType to text:
dataType: "text",
Also be sure to change alert(fail); to:
alert('fail');
String literals must be delimited or variables have to be initialized before they are used.
You already got your answer, I just want to add that using
async: false
is a bad practice when dealing with ajax calls, it freezes your browser while waiting for the response.
If it's possible you should try to avoid this behavior and use
instead the ajax callbacks properly; however if you really want to block the UI you can try to use something like http://malsup.com/jquery/block/
Okay I think I am going mad because I have done this a million times before and now I can't make it work. I am doing an ajax post to a PHP script with some simple JSON and then returning the JSON from my PHP, however it is currently showing $_POST as an empty array.
Here is my js:
$.ajax({
type: "POST",
url: "/account/book-promo.php",
data: '{"firstName":"Peter" , "lastName":"Jones"}',
success: function(response) {
console.log(response);
}
});
And my PHP:
<?php
var_dump($_POST);
exit;
Firebug shows that my request is using POST as it is supposed to and my data is being sent as JSON yet I am getting a response of:
array(0) {
}
The only thing I can think is that there is some kind of server settings that are preventing this from working, however I cant think why there would be. Maybe I have missed a bracket or something, it is driving me mad!
Any and all suggestions welcome!
send it like if you want to send it as json.
data: { data : '{"firstName":"Peter" , "lastName":"Jones"}' },
and if you want to send it as POST just remove quotes '
data: {"firstName":"Peter" , "lastName":"Jones"},
You have to do this:
$.ajax({
type: "POST",
dataType: "json", // <---------------its required if response is json
url: "/account/book-promo.php",
data: {"firstName":"Peter" , "lastName":"Jones"}, //<---instead of string send the object this way
success: function(response) {
console.log(response);
}
});
You said in your post retuning the JSON from my PHP:
so you need to use dataType:"json" and the data you are sending to your php should be sent as object (which is usually to be pair of key and values separated by : like {key:value}) as of your code you are sending a string.
I need to know the exact difference between:
<form method="POST" action="https://mywebsite/signon.php">
<input name="harv_acc" value="940322903" type="hidden" />
<input name="harv_eml" value="a#b.com" type="hidden" />
<input type="submit" value="SignOn" />
and
var url = "https://mywebsite/signon.php";
$.ajax({
url: url,
type: 'POST',
//dataType: 'html', -- this was something I tried later
//data: "harv_acc=" + accountnumber + "&harv_eml=" + email , this is also what I tried last but below is what I tried first
data: { harv_acc: account, harv_eml: email },
success: function (data) {
closePopup("div_PleaseWait");
alert(data);
//window.location = encodeURI('<%= Url.Action("DownloadDocument", "Documents") %>?DocumentID=' + documentID + '&DownloadType=' + downloadType + '&DownloadPath=' + data);
}
});
When I post the latter I get a 200 but no response. If I submit the first one I get the correct response.
From the comments:
I'm posting to another site
Aha! There's your issue. Browsers block AJAX to external websites for security reasons. Sorry, but you're not going to issue that request via an XHR request.
If the other website wants you to communicate with them, they could expose this part of the site via JSON-P, which works something like this:
My site adds <script src="http://othersite.com/signon.js?username=foo&password=bar&callback=myCallback"> to the source code (yeah, it's messy to use GET for this, but JSON-P can't work any other way), and creates a function named myCallback to handle the response data.
The other site signs in, then returns something like myCallback({success: false, errorMessage: "Incorrect password, try again!"})
That script is run on my site, calls myCallback, and everything is happy.
JSON-P is a powerful protocol, but only works if the remote site agrees to it. Still, if they do, jQuery has a nice shortcut for it: just set dataType: "jsonp" and it will handle the whole callback thing for you.
But if you're not closely involved with this website, that's unlikely to happen, and you'll probably just be stuck with having to give up on this kind of cross-site interaction. Sorry, but this kind of cross-domain policy is critical to online security. (I don't want other sites issuing requests to bankofamerica.com on my behalf, kthx.)
The first parameter passed to your complete function will be a jqXHR object, which is a wrapper around the browser's XMLHttpRequest object. A more convenient way to handle the response is to use the done method:
var url = "https://mywebsite/signon.php";
$.ajax({
url: url,
type: 'POST',
dataType: 'html',
data: "harv_acc=" + accountnumber + "&harv_eml=" + email
}).done(function(data) {
closePopup("div_PleaseWait");
alert(data);
});
Cross domain ajax requests are not supported by browser. But there is another way to get around this.
You can use JSONP for cross-domain requests. It is easy to use and allows you to request anything (as long as it is in JSON format) from any server/script that supports the callback. The good thing about JSONP is that it works in older browsers too.
The only serious limitation seems to be that it always uses the HTTP GET method
Can you please check with this too.
Try sending ther data as a key:value object. This is an example from the jQuery docs
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Update: as user Matchu pointed out, this is not the problem, as the data will be converted into a query string anyway, as stated in the jQuery docs:
"The data option can contain either a query string of the form key1=value1&key2=value2, or a map of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. "
So yeah, some rash answering on my part there. At least I learned something! ;)
when using POST method you should ,in your case, Post your data as JSON
var url = "https://mywebsite/signon.php";
$.ajax({
url: url,
type: 'POST',
dataType: 'html',
data: {
harv_acc : accountnumber,
harv_eml : email
},
success: function (data) {
closePopup("div_PleaseWait");
alert(data);
//window.location = encodeURI('<%= Url.Action("DownloadDocument", "Documents") %>?DocumentID=' + documentID + '&DownloadType=' + downloadType + '&DownloadPath=' + data);
}
});
NOTE : i used dataType : JSON
I got the error:
request failed: URI too long (longer than 8190)
I've seen other posts on StackOverflow for this one. Those posts recommend:
Not changing Apache settings (agree)
Using post, not get
Not using jsonp with post
I'm using jQuery's AJAX to POST:
$.ajax({
url: "test.php",
dataType: "json",
data: paras,
type: "POST",
success: function(ret){callback(ret);}
});
It's my impression you can use json just not jsonp. Correct? If so, why might I still be getting the error?
You should try setting proccessData to false.
From the docs:
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
so to prevent the data being added to the url:
$.ajax({
url: "test.php",
dataType: "application/json",
data: paras,
type: "POST",
proccessData: false, // this is true by default
success: function(ret){callback(ret);}
});
Honestly, I thought this was automatic, but since your url is too long it's worth a shot.
I ran into this issue when using jQuery to submit large forms, and was able to solve it by adding this plugin.
For example, using the following code to submit the form after adding the plugin resolved the issue for me:
$(formSelectorHere).ajaxSubmit({
url: myURL,
type: 'post',
contentType: "multipart/form-data",
data: $(this).serialize(),
success: function(data) {
function(data) {
//success code here//
}
});
If you're not using this to submit a form, this may not be relevant to you and won't solve your problem, but that's the most common situation where this issue appears, so I figured it was worth mentioning. (The plugin should also be able to submit a form using JSON, but haven't personally tested it).