{"id":1327,"date":"2022-07-18T10:35:00","date_gmt":"2022-07-18T10:35:00","guid":{"rendered":"https:\/\/samyakonline.biz\/blog\/?p=1327"},"modified":"2023-07-27T09:13:21","modified_gmt":"2023-07-27T09:13:21","slug":"ajax-xhr-request-example-to-php","status":"publish","type":"post","link":"https:\/\/samyakonline.biz\/blog\/ajax-xhr-request-example-to-php.html","title":{"rendered":"AJAX XHR Request Example to PHP at Server Side"},"content":{"rendered":"<p class=\"post-modified-info\">Last Updated on July 27, 2023 by <a href=\"https:\/\/samyakonline.biz\/blog\/author\/samyakonline\" class=\"last-modified-author\">Subhash Jain<\/a><\/p>\n\n\n<p>AJAX stand for&nbsp;Asynchronous JavaScript and XML. AJAX uses&nbsp;<strong>XHR object<\/strong>&nbsp;to send data to the server and uses JS and HTML DOM to display data. AJAX is the example of synergy between JS and HTML DOM.<\/p>\n\n\n\n<p>XHR is the short form for XMLHttpRequest. All modern browsers have in-built XMLHttpRequest object to communicate between the client side and server side without page load. XHR object can be used in these useful scenarios:-<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Submit the form without page re-load<\/li>\n\n\n\n<li>After page-load, request data from server<\/li>\n\n\n\n<li>After page-load, receive data from server<\/li>\n\n\n\n<li>Sending data to server in the background<\/li>\n<\/ul>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #000000;color:#000000\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #000000;color:#000000\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/samyakonline.biz\/blog\/ajax-xhr-request-example-to-php.html\/#Live_Username_Availability_Check_with_XHR_Client_Side_and_PHP_Server_Side_By_POST\" >Live Username Availability Check with XHR (Client Side ) and PHP (Server Side) By POST<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/samyakonline.biz\/blog\/ajax-xhr-request-example-to-php.html\/#Part_I_HTML_Form_XHR_Object_Request_by_POST\" >Part I: HTML Form &amp; XHR Object Request by POST<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/samyakonline.biz\/blog\/ajax-xhr-request-example-to-php.html\/#Part_II_Server_Response_via_PHP_Script\" >Part II: Server Response via PHP Script<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/samyakonline.biz\/blog\/ajax-xhr-request-example-to-php.html\/#Live_Username_Availability_Check_with_XHR_Client_Side_and_PHP_Server_Side_By_GET\" >Live Username Availability Check with XHR (Client Side ) and PHP (Server Side) By GET<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Live_Username_Availability_Check_with_XHR_Client_Side_and_PHP_Server_Side_By_POST\"><\/span>Live Username Availability Check with XHR (Client Side ) and PHP (Server Side) By POST<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>I am going to explain an example when we need to check at server side if the username already exists in DB or not. I will be displaying it with the code and live demo example. We are using AJAX method by using XMLHttpRequest XHR object to send request at server end by POST method. The server will return the data in JSON format. We will fetch the data from server without page reload and display the result on the screen if the &#8220;username exists&#8221; or &#8220;username does not exist&#8221;.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Part_I_HTML_Form_XHR_Object_Request_by_POST\"><\/span>Part I: HTML Form &amp; XHR Object Request by POST<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong>Step 1:<\/strong>&nbsp;<code>change<\/code>&nbsp;event is fired\/triggered in JS when the value of&nbsp;<code>&lt;input&gt;, &lt;select&gt;, and &lt;textarea&gt;<\/code>&nbsp;gets changed. On&nbsp;<code>change<\/code>&nbsp;event, we call&nbsp;<code>function checkUsername()<\/code>. We assume that these username already exists in DB:&nbsp;<code>'ram', 'manohar', 'tom', 'rakesh', 'ajay'<\/code>. If username exists. We add bootstrap class text-danger to show alert and set value of username input field to blank.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;input type=\"text\" name=\"username\" id=\"username\" value=\"\" class=\"form-control\"\n         onchange=\"checkUsername()\" \/&gt;\n        &lt;span id=\"myuname\"&gt; &lt;\/span&gt;<\/code><\/pre>\n\n\n\n<p><strong>Step 2<\/strong>: We use&nbsp;<code>POST<\/code>&nbsp;method to send XHR object request to server. Please note&nbsp;<code>GET &amp; POST<\/code>&nbsp;&#8211; both can be used to send the request but both behaves differently. I would like to mention that we have used JS function serialize to serialize form data when we send via POST.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ JS script to serialize form data when we send via POST\n    &lt;script src = 'serialize-0.2.js'&gt; &lt;\/script&gt;\n\n    &lt;script&gt;\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/  BOF JS  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\tfunction checkUsername(){\n\n\t\t\/\/ Let us create a new XMLHttpRequest object\n\t\t xhr = new XMLHttpRequest();\n\n\t\t\/\/  Let us specify the type of request that we send tp server\n\t\txhr.open('POST', 'username-post-method-response.php', true);\n\t\t\n        \/\/ Send the proper header information along with the request\n        xhr.setRequestHeader('Content-type', 'application\/x-www-form-urlencoded');\n\n\t\t\/\/ Send request with serialized form data\n\t  \t \tparams = serialize(myform);\n\t\t\tconsole.log(params);\n\t\t\txhr.send(params);\n\n        \/\/ Callback function is executed after the response from server is over\n\t\t    xhr.onload = function() {\n\t\t\/\/ Check if HTTP response tatus is 200 and browser has got response from server\n\t\t\tif (xhr.status != 200 &amp;&amp; xhr.readyState == 4 ) {\n\t\t\t\t\n\t\t\t\t\/\/ If POST URL is not found then 404: Not Found error\n\t\t\t\tconsole.log(`Error ${xhr.status}: ${xhr.statusText}`); \n\n\t\t\t\/\/ Display server response \n\t\t\t} else { \n\t\t\t\trdata = JSON.parse(this.responseText);\n\t\t\t\tconsole.log(`Done, got ${xhr.response.length} bytes`); \n\t\t\t\tdocument.getElementById(\"myuname\").innerHTML = rdata.msg;\n\t\t\t\tif(rdata.success == false){\n\t\t\t\t\t\/\/ username does not exist\n\t\t\t\t\tdocument.getElementById(\"myuname\").className = 'text-success';\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n                    \/\/ username exists. We add bootstrap class text-danger to show alert and set value of username input field to blank.\n\t\t\t\t\tdocument.getElementById(\"myuname\").className = 'text-danger';\n\t\t\t\t\tdocument.getElementById(\"username\").value = '';\n\t\t\t\t}\n\t\t\t\t\/\/alert(rdata.success);\n\t\t\t}\n\t\t};\n\n\t\t\/\/ event e\n\t\txhr.onprogress = function(event) {\n\t\t\tif (event.lengthComputable) {\n\t\t\t\tconsole.log(`Got ${event.loaded} of ${event.total} bytes`);\n\t\t\t} else {\n\t\t\t\t\/\/ If no Content-Length \n\t\t\t\tconsole.log(`Got ${event.loaded} bytes`); \n\t\t\t}\n\n\t\t};\n\n\t\txhr.onerror = function() \n\t\t{\n\t\t\talert(\"Request failed\");\n\t\t};\n\t}\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/  EOF JS  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \n\n    &lt;\/script&gt;<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Part_II_Server_Response_via_PHP_Script\"><\/span>Part II: Server Response via PHP Script<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>We assume that you get your result form MySQL Query in array format. Let us pre-define array to explain here with the example code as given below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/  BOF PHP  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    &lt;?php\n    $data = array();\n    $usernames = array('ram', 'manohar', 'tom', 'rakesh', 'ajay');\n    $uname = $_POST&#91;'username'];\n    \/\/$uname = 'ram';\n    if(in_array($uname, $usernames))\n    {\n        $data&#91;'success'] = true;\n        $data&#91;'msg'] = 'username exists';\n\n    }\n    else\n    {\n\n        $data&#91;'success'] = false;\n        $data&#91;'msg'] = 'username does not exist';\n    }\n    $response_data = json_encode($data);\n    echo $response_data;\n    ?&gt;\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/  EOF PHP  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \n\n    &lt;\/script&gt;<\/code><\/pre>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link has-background wp-element-button\" href=\"https:\/\/samyakonline.biz\/scripts\/demo\/ajax-xhr-request-example-to-php\/ajax-xhr-request-example-to-php-post-method.zip\" style=\"background:linear-gradient(135deg,rgb(6,147,227) 100%,rgb(155,81,224) 100%)\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Download &#8211; Live Username Availability Check With XHR (POST Method)<\/strong><\/a><\/div>\n<\/div>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link has-background wp-element-button\" href=\"https:\/\/samyakonline.biz\/scripts\/demo\/ajax-xhr-request-example-to-php\/form-post-method.php\" style=\"background:linear-gradient(135deg,rgb(6,147,227) 52%,rgb(155,81,224) 88%)\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Demo &#8211; Live Username Availability Check with XHR (POST Method)<\/strong><\/a><\/div>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Live_Username_Availability_Check_with_XHR_Client_Side_and_PHP_Server_Side_By_GET\"><\/span>Live Username Availability Check with XHR (Client Side ) and PHP (Server Side) By GET<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button aligncenter\"><a class=\"wp-block-button__link has-vivid-cyan-blue-background-color has-background wp-element-button\" href=\"https:\/\/samyakonline.biz\/scripts\/demo\/ajax-xhr-request-example-to-php\/ajax-xhr-request-example-to-php-get-method.zip\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Download &#8211; Live Username Availability Check With XHR (GET Method)<\/strong><\/a><\/div>\n<\/div>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button aligncenter\"><a class=\"wp-block-button__link has-vivid-cyan-blue-background-color has-background wp-element-button\" href=\"https:\/\/samyakonline.biz\/scripts\/demo\/ajax-xhr-request-example-to-php\/form.php\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Demo &#8211; Live Username Availability Check with XHR (GET Method)<\/strong><\/a><\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>AJAX stand for&nbsp;Asynchronous JavaScript and XML. AJAX uses&nbsp;XHR object&nbsp;to send data to the server and uses JS and HTML DOM to display data. AJAX is the example of synergy between JS and HTML DOM. XHR is the short form for XMLHttpRequest. All modern browsers have in-built XMLHttpRequest object to communicate between the client side and [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":1328,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","footnotes":""},"categories":[1],"tags":[],"class_list":["post-1327","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-scripts"],"modified_by":"Anil","_links":{"self":[{"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/posts\/1327","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/comments?post=1327"}],"version-history":[{"count":0,"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/posts\/1327\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/media\/1328"}],"wp:attachment":[{"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/media?parent=1327"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/categories?post=1327"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/samyakonline.biz\/blog\/wp-json\/wp\/v2\/tags?post=1327"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}