Accessing $_POST data sent by Jquery/AJAX
13,835
Solution 1
Try sending the data as an object:
function end_incident() {
$.ajax({
type: "POST",
url: "http://www.example.co.uk/erc/end_incident.php",
data: { name: "Daniel", phone: "01234123456" },
success: function(msg){
alert('Success!');
}
});
};
Solution 2
Make sure the url your requesting for is within the same origin of your site, if it isn't, you've got a cross-site scripting issue. Only way around that:
- Getting "higher" access/priveledges within the browser, i.e. create an add-on/extension, or use Greasemonkey
Use a proxy through your own site to get the request for the file:
var getURL = "http://www.example.co.uk/erc/end_incident.php"; $.ajax({ type: "POST", url: "/get_url.php?url=" + encodeURIComponent(getURL), data: { name: "Daniel", phone: "01234123456" }, success: function(msg){ alert('Success!'); } });
I recommend you add a error
function to your ajax. It's suprising how many people just focus on success
and never process an error!
error: function()
{
console.log(arguments);
}
Author by
Daniel H
Updated on September 05, 2022Comments
-
Daniel H over 1 year
I am using this function:
function end_incident() { var dataString = 'name=Daniel&phone=01234123456'; $.ajax({ type: "POST", url: "http://www.example.co.uk/erc/end_incident.php", data: dataString, success: function(msg){ alert('Success!'+dataString); } }); };
to send information to
end_incident.php
, but I'm not able to access the$_POST
variables. I've tried doing it like this:$name = $_POST['name']; $phone = $_POST['phone'];
Am I doing something wrong?
Thanks for any help
-
Fidi almost 13 yearsDamn, wanted to post the same thing! You were faster :) +1
-
kapa almost 13 yearsNo, this won't make any difference. The
data
attribute can be set either as an object (in this case it will be converted to a query string) or as a string in the query string format. See here. -
Daniel H almost 13 yearsHi Richard D thanks for your reply. I think the problem was that I missed a couple of apostrophies in my SQL query and its now working but I like the layout you've used better anyway so I'll use that :)
-
Brian McCutchon almost 11 years+1 for error comment. But wouldn't it be a good idea to actually tell the user that an error occurred? You never know when your server or the user's WIFI might be down.
alert("Could not connect to the server. Please check your network connection or try again later.");
...or something cleaner.