I am new to the use of jQuery for handling AJAX, and have written a basic script to get the basics down. Currently I am POSTing an AJAX request to the same file, and I wish
The elegant way would be to have a separate(!) PHP file that will only output the number times 2
part of your current PHP. Then you generate an AJAX request from your current PHP to the new separate PHP.
I believe this post answers one aspect of what you are seeing - the echoing of the entire page in your alert box.
Next, here are some good posts for getting the basics of AJAX:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
NOTE *The better approach is to keep things like this in a separate file, makes it easier to read and easier to understand, especially if you use a good naming conversion.
It is a bad procedural approach but here I go :) :
<?php
$num = $_POST['json'];
if (isset($num))
echo ($num['number'] * 2);
die();
?>
or better yet:
<?php
$num = $_POST['json'];
if (isset($num))
die($num['number'] * 2); //In case of error you could put them in brackets
?>
PS
As alternative to die();
you could use exit();
, they both do pretty much the same: terminating further execution
You could add die();
after you echo the number if you really want to keep it on the same page. This will terminate the execution of the script. Don't forget to add brackets around the if statement:
if (isset($num)) {
echo $num['number'] * 2;
die();
}
It is, however, not the most elegant solution.
I don't know how efficient this is but you can do something like:
<?php
/*convertNum.php*/
$num = isset($_POST['json']) ? $_POST['json'] : NULL; //you have errors in this line
if (!is_null($num)){
echo $num['number'] * 2;
exit(); //exit from script
}
?>