Php and ajax call

AJAX PHP Example

The following example demonstrates how a web page can communicate with a web server while a user types characters in an input field:

Example

Example Explained

In the example above, when a user types a character in the input field, a function called showHint() is executed. The function is triggered by the onkeyup event. Here is the code:

Example

  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a PHP file (gethint.php) on the server
  • Notice that q parameter is added gethint.php?q=»+str
  • The str variable holds the content of the input field

The PHP File — «gethint.php»

The PHP file checks an array of names, and returns the corresponding name(s) to the browser:

// Array with names
$a[] = «Anna»;
$a[] = «Brittany»;
$a[] = «Cinderella»;
$a[] = «Diana»;
$a[] = «Eva»;
$a[] = «Fiona»;
$a[] = «Gunda»;
$a[] = «Hege»;
$a[] = «Inga»;
$a[] = «Johanna»;
$a[] = «Kitty»;
$a[] = «Linda»;
$a[] = «Nina»;
$a[] = «Ophelia»;
$a[] = «Petunia»;
$a[] = «Amanda»;
$a[] = «Raquel»;
$a[] = «Cindy»;
$a[] = «Doris»;
$a[] = «Eve»;
$a[] = «Evita»;
$a[] = «Sunniva»;
$a[] = «Tove»;
$a[] = «Unni»;
$a[] = «Violet»;
$a[] = «Liza»;
$a[] = «Elizabeth»;
$a[] = «Ellen»;
$a[] = «Wenche»;
$a[] = «Vicky»;

// get the q parameter from URL
$q = $_REQUEST[«q»];

// lookup all hints from array if $q is different from «»
if ($q !== «») $q = strtolower($q);
$len=strlen($q);
foreach($a as $name) if (stristr($q, substr($name, 0, $len))) if ($hint === «») $hint = $name;
> else $hint .= «, $name»;
>
>
>
>

Читайте также:  Python on windows mobile

// Output «no suggestion» if no hint was found or output correct values
echo $hint === «» ? «no suggestion» : $hint;
?>

Источник

PHP — AJAX and PHP

The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field:

Example

Example Explained

In the example above, when a user types a character in the input field, a function called «showHint()» is executed. The function is triggered by the onkeyup event. Here is the HTML code:

Example

  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a PHP file (gethint.php) on the server
  • Notice that q parameter is added to the url (gethint.php?q=»+str)
  • And the str variable holds the content of the input field

The PHP File — «gethint.php»

The PHP file checks an array of names, and returns the corresponding name(s) to the browser:

// Array with names
$a[] = «Anna»;
$a[] = «Brittany»;
$a[] = «Cinderella»;
$a[] = «Diana»;
$a[] = «Eva»;
$a[] = «Fiona»;
$a[] = «Gunda»;
$a[] = «Hege»;
$a[] = «Inga»;
$a[] = «Johanna»;
$a[] = «Kitty»;
$a[] = «Linda»;
$a[] = «Nina»;
$a[] = «Ophelia»;
$a[] = «Petunia»;
$a[] = «Amanda»;
$a[] = «Raquel»;
$a[] = «Cindy»;
$a[] = «Doris»;
$a[] = «Eve»;
$a[] = «Evita»;
$a[] = «Sunniva»;
$a[] = «Tove»;
$a[] = «Unni»;
$a[] = «Violet»;
$a[] = «Liza»;
$a[] = «Elizabeth»;
$a[] = «Ellen»;
$a[] = «Wenche»;
$a[] = «Vicky»;

// get the q parameter from URL
$q = $_REQUEST[«q»];

// lookup all hints from array if $q is different from «»
if ($q !== «») $q = strtolower($q);
$len=strlen($q);
foreach($a as $name) if (stristr($q, substr($name, 0, $len))) if ($hint === «») $hint = $name;
> else $hint .= «, $name»;
>
>
>
>

// Output «no suggestion» if no hint was found or output correct values
echo $hint === «» ? «no suggestion» : $hint;
?>

Источник

How to Use AJAX in PHP and jQuery

Sajal Soni

Sajal Soni Last updated Nov 27, 2021

Today, we’re going to explore the concept of AJAX with PHP and JavaScript. The AJAX technique helps you to improve your application’s user interface and enhance the overall end user experience.

AJAX stands for Asynchronous JavaScript and XML, and it allows you to fetch content from the back-end server asynchronously, without a page refresh. Thus, it lets you update the content of a web page without reloading it.

Let’s look at an example to understand how you could use AJAX in your day-to-day application development. Say you want to build a page that displays a user’s profile information, with different sections like personal information, social information, notifications, messages, and so on.

The usual approach would be to build different web pages for each section. So for example, users would click the social information link to reload the browser and display a page with the social information. This makes it slower to navigate between sections, though, since the user has to wait for the browser to reload and the page to render again each time.

On the other hand, you could also use AJAX to build an interface that loads all the information without refreshing the page. In this case, you can display different tabs for all sections, and by clicking on the tab it fetches the corresponding content from the back-end server and updates the page without refreshing the browser. This helps you to improve the overall end-user experience.

The overall AJAX call works something like this:

Ajax Call

Let’s quickly go through the usual AJAX flow:

  1. First, the user opens a web page as usual with a synchronous request.
  2. Next, the user clicks on a DOM element—usually a button or link—that initiates an asynchronous request to the back-end server. The end user won’t notice this since the call is made asynchronously and doesn’t refresh the browser. However, you can spot these AJAX calls using a tool like Firebug.
  3. In response to the AJAX request, the server may return XML, JSON, or HTML string data.
  4. The response data is parsed using JavaScript.
  5. Finally, the parsed data is updated in the web page’s DOM.

So as you can see, the web page is updated with real-time data from the server without the browser reloading.

In the next section, we’ll how to implement AJAX using vanilla JavaScript.

How AJAX Works Using Vanilla JavaScript

In this section, we’ll see how AJAX works in vanilla JavaScript. Of course, there are JavaScript libraries available that make it easier to do AJAX calls, but it’s always interesting to know what’s happening under the hood.

Let’s have a look at the following vanilla JavaScript code, which performs the AJAX call and fetches a response from the server asynchronously.

var objXMLHttpRequest = new XMLHttpRequest(); 
objXMLHttpRequest.onreadystatechange = function()  
if(objXMLHttpRequest.readyState === 4)  
if(objXMLHttpRequest.status === 200)  
alert(objXMLHttpRequest.responseText); 
alert('Error Code: ' + objXMLHttpRequest.status); 
alert('Error Message: ' + objXMLHttpRequest.statusText); 
objXMLHttpRequest.open('GET', 'request_ajax_data.php'); 

Let’s go through the above code to understand what’s happening behind the scenes.

  1. First, we initialize the XMLHttpRequest object, which is responsible for making AJAX calls.
  2. The XMLHttpRequest object has a readyState property, and the value of that property changes during the request lifecycle. It can hold one of four values: OPENED , HEADERS_RECEIVED , LOADING , and DONE .
  3. We can set up a listener function for state changes using the onreadystatechange property. And that’s what we’ve done in the above example: we’ve used a function which will be called every time the state property is changed.
  4. In that function, we’ve checked if the readyState value equals 4 , which means the request is completed and we’ve got a response from the server. Next, we’ve checked if the status code equals 200 , which means the request was successful. Finally, we fetch the response which is stored in the responseText property of the XMLHttpRequest object.
  5. After setting up the listener, we initiate the request by calling the open method of the XMLHttpRequest object. The readyState property value will be set to 1 after this call.
  6. Finally, we’ve called the send method of the XMLHttpRequest object, which actually sends the request to the server. The readyState property value will be set to 2 after this call.
  7. When the server responds, it will eventually set the readyState value to 4, and you should see an alert box displaying the response from the server.

So that’s how AJAX works with vanilla JavaScript. The method here, using «callback functions» is the traditional way to code AJAX, but a cleaner and more modern way is with Promises.

In the next section, we’ll see how to use the Promise object for AJAX.

How to Use JavaScript Promises for AJAX

Promises in JavaScript provide a better way to manage asynchronous operations and callbacks that are dependent on other callbacks. In JavaScript, Promise is an object which may have one of the three states: pending, resolved, or rejected. Initially, the Promise object is in the pending state, but as the asynchronous operation is completed, it may evaluate to the resolved or rejected state.

Let’s quickly revise the previous example with the Promise object.

function AjaxCallWithPromise()  
return new Promise(function (resolve, reject)  
const objXMLHttpRequest = new XMLHttpRequest(); 
objXMLHttpRequest.onreadystatechange = function ()  
if (objXMLHttpRequest.readyState === 4)  
if (objXMLHttpRequest.status == 200)  
resolve(objXMLHttpRequest.responseText); 
reject('Error Code: ' + objXMLHttpRequest.status + ' Error Message: ' + objXMLHttpRequest.statusText); 

Источник

Оцените статью