Reputation: 75
I am having trouble getting a basic ajax POST to work. I switched to an onclick after I was having trouble getting using a jquery .click, among other things. Just wondering if I am making some blatant mistake or what. If no obvious mistake, it may be something with apache? Not too much experienced here so any help would be appreciated.
Here is a link to a function:
<a href="markerpages.php" onclick="postData()">click this for php page</a>
Here is the function:
function postData() {
console.log("outside ajax is working");
$.ajax({
type: "POST",
url: "/markerpages.php",
data: {
source1: "some text",
source2: "some text 2"},
success: function (data) {
console.log("inside ajax is working");
},
error: function () {
console.log("ajax post failed")
}
});
here is what I have on my php webpage:
<?php
if (isset($_POST['source1']))
$src1 = $_POST['source1'];
else $src1 = "post data not obtained";
echo $src1;
echo "<pre>" . print_r($_REQUEST, 1) . "</pre>";
print_r($_POST);
var_dump($_POST);
var_dump($_POST);die;
?>
I am not returning errors in firebug, and I am getting the log statements I placed inside ajax and outside, just not getting empty arrays on the PHP page. Sincere thanks for any help.
Upvotes: 0
Views: 114
Reputation: 592
When clicking the link, postData()
is being called, but then the browser is loading the URL specified in your <a href>
. You can do one of three possible things:
Add the following line at the top of your postData() function: event.preventDefault()
. That will stop the original event clicking action, and is the preferred method.
Change your onclick
attribute and add return false
to prevent the URL clicking behavior. Ex: onclick="postData(); return false;
Change the <a href="/markerpages.php">
to <a href="#">
. But this is not a good approach since the page's URL will change to mypage.htm#
.
Another helpful debugging tip: you can output the data
variable (the returned value from your PHP script) like so: console.log(data);
.
And since you seem to be hand building a form which will eventually pass values from the server back to the front-end, I suggest looking at this article: Pass a PHP Array to Javascript as JSON using AJAX and json_encode()
Upvotes: 0
Reputation: 934
First of all you should put a return false;
in the js function, doing so there will not be any redirects,
Check in Developer Network your request, if the url is correct and if you are retrieving any errors during the ajax post.
Upvotes: 1
Reputation: 33186
You are sending the user to the page using the anchor tag. If you do this, all post data is lost. You need to replace the url in the anchor tag with #
to make sure the user stays on the page:
<a href="#" onclick="postData()">click this for php page</a>
Upvotes: 2