Posted on: 07.08.2020 Posted by: Alex D Comments: 0

JQuery AJAX Send Examples

Using ajax you can run a php file on the server. And the result of his work is displayed in the DIV block. In this case, the browser page does not need to be loaded. This process is hidden from the user.

In order to form an ajax request, you must have a php file on the server. And you have to decide what parameters will be passed to this file. And the transmission method is GET or POST.

The php file should contain this line.

echo (isset($_GET['callback']) ? $_GET['callback'] : '').'(' . json_encode($data) . ')';

A json string is returned back to the browser. Which is taken from the $date variable. $date is an array.

$data = array($par1,$par2,$par3);

In the browser, we can refer to the date as an array. For example data[0], data[1], data[2].

In our browser, we will have the result of the php file and now we can display it in the div, in the console or in the alert.

$('#div1').html(data[0]);
console.log(data[1]);
alert(data[2]);

Sample code. Let’s calculate a + b in php and display the result c, run with an alert.

Client-side jQwery code in browser.

$.ajax({
 type: "get",
 url: "https://spage.me/info/example/calculate.php",
 dataType: "jsonp",
 data: { a:"200", b:"300" },
 error: function ()
 {
  console.log("Error Ajax - calculate.php");
 },
  success: function(data)
 {
  console.log(data);
  alert(data[0]);
 },
  complete: function()
 {
  console.log("Complet Ajax - calculate.php");
 }
});

The php file calculate.php code on the server.

<?php
 $a = $_GET['a'];
 $b = $_GET['b'];
 $c = $a + $b;

 $data = array($c);
 header('Content-Type: application/javascript');
 echo (isset($_GET['callback']) ? $_GET['callback'] : '').'(' . json_encode($data) . ')';
?>

Now you can create 2 input fields. And take a and b from these fields.

This is the html code in the client browser.

<script>
function total() {
 $.ajax({
   type: "get",
   url: "https://spage.me/info/example/calculate.php",
   dataType: "jsonp",
   data: { a : $("#a").val(), b : $("#b").val() },
   success:  function(data) 
     {
       alert(data[0]);
     },
 });
}
</script>

<P><input type="text" id="a"></P>
<P><input type="text" id="b"></P>
<P><button onClick="total();">OK</button></P>

DEMO

The last script does not have complete: function (). What is it for? In Complete: function (), you can insert js code that will be executed in the last queue. This is the callback function.

Documentation for this css property is here

Categories:

Leave a Comment