6

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 to do some additional processing based on the results of that AJAX call.

Here is my code:

**/*convertNum.php*/**

$num = $_POST['json'];
if (isset($num))
 echo $num['number'] * 2;
?>

<!DOCTYPE html>
<html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <style type="text/css">
 td {border:none;}

 </style>
 </head>
 <body>

 <table width="800" border="1">
 <tr>
 <td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>
 <td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>
 </tr>

 <tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>
 </table>



 <script>
 $(document).ready(function () {
 $('#getNum').click(function () {
 var $numSent = $('#numSend').val();
 var json = {"number":$numSent};

 $.post("convertNum.php", {"json": json}).done(function (data) 
 {
 alert(data);
 }
 );

 });
 });
 </script>
 </body>
</html>

Here is the response I get if I submit the number '2':

4

<!DOCTYPE html>

<html>

<head>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

 <style type="text/css">

td {border:none;}

</style>

</head>

<body>



<table width="800" border="1">

 <tr>

 <td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>

 <td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>

 </tr>

 <tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>

</table>

<script>

$(document).ready(function () {

 $('#getNum').click(function () {

 var $numSent = $('#numSend').val();

 var json = {"number":$numSent};

 $.post("convertNum.php", {"json": json}).done(function (data) 

 {

 alert(data);

 }

 );



 });

});

</script>
</body>
</html>

Obviously I'm only interested in receiving and using the number '4', hence my question: What is the best way to specify exactly what data I want returned?

Some thoughts I've had:

  • wrapping all my HTML inside a if statement (i.e., if $num isset, do NOT output html; else output HTML) but then I'm echoing HTML, and I'd rather not do that.
  • Setting up a separate PHP script to receive my AJAX call: That was what I did originally, and it works just fine. However, I am interested in keeping everything inside one file, and wanted to explore possible ways of doing so.

I'm sure there is an elegant way to do this. Thanks for any suggestions!

JRizz
  • 206
  • 3
  • 12
  • why would you like to keep everything in one file. You should structurize your code. Otherwise you will get very lage files with confusing code. And what about css and javascript? Do you want to have it all in one file, too? You can do it but i think this wouldn't be elegant. – steven Jul 31 '13 at 14:53
  • Steven - fair enough. The reaon I want to explore keeping all the calls in one file is because I am working on a project where we will have multiple php pages making AJAX calls, and I am attempting to determine best practices for handling this case. Now, I will say that each script that utilizes an AJAX call like this will have a corresponding .inc include file - perhaps it would be best to make the POST call to that include file, rather than using the same page or a different script. I'm in the exploratory phase of development right now, and the answers I'm getting are enormously helpful. – JRizz Jul 31 '13 at 15:07

5 Answers5

7

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.

devnull69
  • 15,158
  • 3
  • 44
  • 55
  • Hi devnull, That was my original approach. I need to edit my answer to include that - thank you. I did have the AJAX call pointing to a seperate PHP script, but I wanted to explore the idea of keeping it all on one page. – JRizz Jul 31 '13 at 14:44
  • 1
    Then you should go for the `if` ... you don't need to echo HTML, you can still have the HTML part outside of the sections. This will also work inside PHP if statements! – devnull69 Jul 31 '13 at 14:46
  • Interesting - I hadn't considered that. Let me play with my script some more and explore that. Thank you - I want to leave this open to get other ideas to consider, but if this is the best solution I'll mark this the answer. I appreciate your input. – JRizz Jul 31 '13 at 14:53
  • After further testing, I've decided that using either an include file to handle the call, or utilizing an if statement is the best way to go, with a strong leaning towards the include file. Thanks everyone. – JRizz Jul 31 '13 at 15:39
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

Community
  • 1
  • 1
cssyphus
  • 31,599
  • 16
  • 79
  • 97
  • Thank you kindly. Always good to have additional reading material and examples. I appreciate your time. – JRizz Jul 31 '13 at 18:06
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

DaGhostman Dimitrov
  • 1,538
  • 17
  • 42
  • 1
    brackets in first approach? +1 for second one – steven Jul 31 '13 at 14:56
  • Thanks for the typo :) didn't saw that – DaGhostman Dimitrov Jul 31 '13 at 14:57
  • Thanks Ghostman. That was my original approach - I've made edits to my question to specify that. It works great, but I wanted to explore the idea of using the same page to receive the AJAX call. It's looking like that still may be the most efficient way to go. Thanks! – JRizz Jul 31 '13 at 15:09
1

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.

Valk6
  • 96
  • 1
  • 5
0

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
 }
?>
Konsole
  • 3,389
  • 3
  • 24
  • 38