AJAX request callback using jQuery

Solution 1:

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.

Solution 2:

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

Solution 3:

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.

Solution 4:

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