php - AJAX request callback using jQuery -


i new use of jquery handling ajax, , have written basic script basics down. posting ajax request same file, , wish additional processing based on results of ajax call.

here 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 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 response if submit 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 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 interested in receiving , using number '4', hence question: what best way specify data want returned?

some thoughts i've had:

  • wrapping html inside if statement (i.e., if $num isset, not output html; else output html) i'm echoing html, , i'd rather not that.
  • setting separate php script receive ajax call: did originally, , works fine. however, interested in keeping inside 1 file, , wanted explore possible ways of doing so.

i'm sure there elegant way this. suggestions!

the elegant way have separate(!) php file output number times 2 part of current php. generate ajax request current php new separate php.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -