I have a variable we will call test_string which I am assigning the string "hello" too.
var test_string = "hello";
And I want it to post to a php page just oneway I have tried:
$.post('php_page.php', test_string);
On the php_page.php I use:
$new_var = $_POST['test_string'];
echo $new_var;
And get no result. What am I missing in the $.post()?
Try this ---
$.post('php_page.php', {test_string:test_string});
and let me know
EDIT MY WORKING CODE ---
test.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function handle(){
var test_string = "hello";
$.post('myphp.php', {'test_string':test_string},
function (result){
$("span").html(result);
});
}
</script>
</head>
<body>
<input type="button" onclick="handle();" value="Click" />
<span></span>
</body>
</html>
myphp.php
<?php
$new_var = $_POST['test_string'];
echo $new_var;
As swapnesh implies, you're missing that $.post
expects an object as the second parameter:
$.post('php_page.php', { objkey : objval });
Then in PHP you retrieve it with this:
$val = $_POST['objkey'];
In http requests both post and get,the values are sent as a Name/value pair. In your code you are missing two things. the first thing is you are trying to send just the data without assiging it in to a Name/vale pair. And the second thing is you have not writtien the function to catch the server response.
Please try as follows.
$.post('php_page.php', test_string: "hello", function(response) {
alert(response);
});