Reputation: 353
I am new to both javascript and php. I am trying to write a javascript function that will post a string back to the server so that I can capture it and save it in the database. It will eventually post data obtained from the google.maps geocoding api,but for now, I'm just trying to get ANY post to work. I have been able to post to the server with html forms, but not successfully yet using a javascript function, and I have a hunch that I am missing something basic.
I have included the jquery library in my Script.js file with:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
I have then added this function, which I pretty much just copied from the examples in my Script.js file:
<script>
function namepost(){
document.write("Tired of trying to debug this bloody thing");
$.post("test.php",{firstname:"John"});
}
</script>
For testing purposes, I have created the file test.php, and here is the code:
<?php
require_once 'Script.js';
echo "<script>namepost()</script>";
$name = $_POST['firstname'];
print_r($_POST);
echo "Firstname is {$name}";
Here is the output I get when I run the code:
Tired of trying to debug this bloody thingArray ( ) Firstname is
My function is getting called, but it doesn't appear that I am posting firstname because the $_POST gives me an empty array. I can't tell why, and I have been at this for hours and hours. Is there another file I need to include to use the jquery $.post function? Please, help me save the rest of my hair and sanity!
Upvotes: 0
Views: 81
Reputation: 98861
The html:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.post(
"/jquery/result.php",
{ name: "Zara" },
function(data) {
$('#stage').html(data);
}
);
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id="stage" style="background-color:blue;">
STAGE
</div>
<input type="button" id="driver" value="Load Data" />
</body>
</html>
The php:
<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>
Change the values to match yours.
http://www.tutorialspoint.com/jquery/ajax-jquery-post.htm
Upvotes: 0
Reputation: 246
The jQuery $.post will do an asynchronous POST, so your page won't be updated unless you process the results in javascript:
$.post("test.php", {firstname:"John"}, function(result){ alert(result) });
(The third parameter of $.post is a function that will execute after the server responds).
If you want to do synchronous POST, you will need to use the jQuery $.ajax function, like this:
$.ajax({
type: 'POST',
url: "test.php",
data: {firstname:"John"},
success: function(result){ alert(result) },
async:false
});
Upvotes: 1