{"id":207,"date":"2012-04-28T17:27:53","date_gmt":"2012-04-28T09:27:53","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=207"},"modified":"2018-09-03T22:05:09","modified_gmt":"2018-09-03T14:05:09","slug":"how-to-send-http-post-requests-and-http-get-requests-using-jquery","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-send-http-post-requests-and-http-get-requests-using-jquery\/","title":{"rendered":"How to send HTTP post requests and HTTP get requests using jQuery"},"content":{"rendered":"<p>This was a proof of concept to try out jQuery's ajax features. <strong>A<\/strong>synchronus <strong>J<\/strong>avascript <strong>A<\/strong>nd <strong>X<\/strong>ML is a way for avoiding unnecessary refresh of the entire web page. When used properly, it can enhance user experience for your website, especially when you have lots of images on your page which does not change often across different pages.<\/p>\n<p><strong>This proof of concept was based on <a href=\"http:\/\/blog.jquery.com\/2011\/11\/21\/jquery-1-7-1-released\/\" title=\"Link to download jQuery 1.7.1\" target=\"_blank\">jQuery version 1.7.1<\/a><\/strong>.<\/p>\n<h3>A sample scenario<\/h3>\n<p>Let's create a scenario to demonstrate the use of jQuery AJAX facilities. Suppose we have two php scripts. One process variables sent by the client via HTTP post while the other process variables sent by the client via HTTP get.<\/p>\n<p>Let's name the first script as <code>postDataHandler.php<\/code>; the second as <code>getDataHandler.php<\/code>.<\/p>\n<h4>The server script - postDataHandler.php: <\/h4>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\nResults from postDataHandler.php:\r\n&lt;br\/&gt;\r\n&lt;?php\r\n$number = isset($_POST&#x5B;'number']) ? $_POST&#x5B;'number'] : '';\r\nif (is_numeric($number)) {\r\n    if ($number % 2 == 0) {\r\n        echo 'The number is even.';\r\n    }\r\n    else {\r\n        echo 'The number is odd.';\r\n    } \/\/ end if\r\n}\r\nelse {\r\n    echo 'You did not enter a number. Please enter a number.';\r\n} \/\/ end if\r\n?&gt;\r\n<\/pre>\n<p>In <code>postDataHandler.php<\/code>, we output a string that indicates the identity of the processing script. We then look for a post variable - <strong>number<\/strong> in the predefined variable, <code>$_POST<\/code>, that stores post data. <\/p>\n<p>We then check whether a number is provided. If provided, we check whether the number is odd or even and prints the result. <\/p>\n<p>If a number is not provided, we ask for a number.<\/p>\n<h4>The server script - getDataHandler.php: <\/h4>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\nResults from getDataHandler.php:\r\n&lt;br\/&gt;\r\n&lt;?php\r\n$number = isset($_GET&#x5B;'number']) ? $_GET&#x5B;'number'] : '';\r\nif (is_numeric($number)) {\r\n    if ($number &lt; 0) {\r\n        echo 'The number is negative.';\r\n    }\r\n    else if ($number &gt; 0){\r\n        echo 'The number is positive.';\r\n    }\r\n    else {\r\n        echo 'The number is neither positive nor negative. It is zero.';\r\n    } \/\/ end if\r\n}\r\nelse {\r\n    echo 'You did not enter a number. Please enter a number.';\r\n} \/\/ end if\r\n?&gt;\r\n<\/pre>\n<p>In <code>getDataHandler.php<\/code>, we output a string that indicates the identity of the processing script. We then look for a query string variable - <strong>number<\/strong> in the predefined variable, <code>$_GET<\/code>, that stores query string data.<\/p>\n<p>We first check whether a number is provided. If a number is provided, we check whether it is negative, positive or is zero and outputs the result.<\/p>\n<p>If a number is not provided, we ask for a number.<\/p>\n<h3>The HTML code for the sample scenario<\/h3>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;div id=&quot;contentLink&quot;&gt;\r\n    &lt;a id=&quot;checkWhetherNumberIsOdd&quot; href=&quot;#&quot;&gt;\r\n        Check if number is odd or even.\r\n    &lt;\/a&gt;\r\n    &lt;br\/&gt;\r\n    &lt;a id=&quot;checkWhetherNumberIsNegative&quot; href=&quot;#&quot;&gt;\r\n        Check if number is positive or negative.\r\n    &lt;\/a&gt;\r\n&lt;\/div&gt;\r\n&lt;label for=&quot;numberTextField&quot;&gt;Number: &lt;\/label&gt;\r\n&lt;input id = &quot;numberTextField&quot; type=&quot;text&quot;\/&gt;\r\n&lt;hr\/&gt;\r\n&lt;div id=&quot;contentBlock&quot;&gt;\r\n&lt;\/div&gt;\r\n<\/pre>\n<p>The HTML code renders four main elements on screen that will be involved in the demonstration:<\/p>\n<ol>\n<li>A link that will initiate a HTTP post.<\/li>\n<li>A link that will initiate a HTTP get.<\/li>\n<li>A text field for user input.<\/li>\n<li>A section that will display the result from the server scripts.<\/li>\n<\/ol>\n<p>All four are given a unique id each to facilitate DOM selection by the jQuery counterpart.<\/p>\n<h3>The jQuery code to perform HTTP get and HTTP post<\/h3>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n$(document).ready(\r\n    \r\n    function () {\r\n    $('#checkWhetherNumberIsOdd').click(\r\n        function(event) {\r\n            event.preventDefault();\r\n            $.post('postDataHandler.php'\r\n                 , {number: $('#numberTextField').val()}\r\n                 , dataReady);\r\n        }\r\n    );\r\n    \r\n    $('#checkWhetherNumberIsNegative').click(\r\n        function(event) {\r\n            event.preventDefault();\r\n            $.get('getDataHandler.php'\r\n                   , {number: $('#numberTextField').val()}\r\n                   , dataReady); \r\n        } \/\/ end function(event)\r\n    ); \/\/ end $(document).ready\r\n    \r\n    function dataReady(data) {\r\n        $('#contentBlock').html(data);\r\n    } \/\/ end function dataReady(data)\r\n    \r\n});\r\n<\/pre>\n<p>When the document is ready, a click handler is added to each of the two links.<\/p>\n<h4>Inside the click handler for checkWhetherNumberIsOdd<\/h4>\n<p>A call to <code>event.preventDefault<\/code> prevents clicks on the \"Check whether number is odd or even\" link from initiating a full refresh of the web page. <\/p>\n<p>We then call <a href=\"http:\/\/api.jquery.com\/jQuery.post\/\" title=\"Link to jQuery.post documentation\" target=\"_blank\"><code>$.post<\/code><\/a> to send a HTTP post request to <code>postDataHandler.php<\/code>. There are three arguments supplied to the <code>$.post<\/code> function:<\/p>\n<ol>\n<li>The url to the server endpoint which will handle the HTTP post request, which in this case is <code>postDataHandler.php<\/code>.<\/li>\n<li>A javascript object which contains a <code>number<\/code> property with the user input from <code>numberTextField<\/code> as its value.<\/li>\n<li>The dataReady function which will look for <code>contentBlock<\/code> and set its content to the content of the HTTP response from the <code>postDataHandler.php<\/code>.<\/li>\n<\/ol>\n<h4>Inside the click handler for checkWhetherNumberIsNegative<\/h4>\n<p>The logic in the click handler for <code>checkWhetherNumberIsNegative<\/code> is similar to the logic <code>checkWhetherNumberIsOdd<\/code>.<\/p>\n<p>We call event.preventDefault to prevent clicks on \"Check if number is positive or negative.\" from initiating a full refresh of the web page.<\/p>\n<p>However, we call <a href=\"http:\/\/api.jquery.com\/jQuery.get\/\" title=\"Link to jQuery.get documentation\" target=\"_blank\"><code>$.get<\/code><\/a> instead of <code>$.post<\/code> to send a HTTP get request to <code>getDataHandler.php<\/code>. <\/p>\n<p>The three arguments supplied to the $.get function is similar to $.post:<\/p>\n<ol>\n<li>The url to the server endpoint which will handle the HTTP post request, which in this case is <code>getDataHandler.php<\/code>.<\/li>\n<li>A javascript object which contains a <code>number<\/code> property with the user input from <code>numberTextField<\/code> as its value.<\/li>\n<li>The dataReady function which will look for <code>contentBlock<\/code> and set its content to the content of the HTTP response from the <code>getDataHandler.php<\/code>.<\/li>\n<\/ol>\n<h3>Wait! How about cases when the server scripts are not contactable?<\/h3>\n<p>There may probably be situations when the scripts does not execute correctly, or in HTTP taxomony, does not send back a HTTP response with status of success 2xx. In such situations, nothing will be populated by the jQuery codes in <code>contentBlock<\/code>.<\/p>\n<p>But what if we want to notify our users of such situations from our scripts? Yes we can do that. Since this proof of concept is based on jQuery 1.7.1, we can attach an event handler to output a notification to our users when failures occurred. The event handler can be attached to the $.post or $.get functions by chaining <a href=\"http:\/\/api.jquery.com\/error\/\" title=\"jQuery api reference for .error\" target=\"_blank\">.error<\/a> at the back:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n$.post('postDataHandler.php'\r\n     , {number: $('#numberTextField').val()}\r\n     , dataReady).error(function () {\r\n        alert('An error had occurred while checking if number is odd or even.');\r\n     });\r\n<\/pre>\n<h3>Related posts<\/h3>\n<ul>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/code-segments-for-rendering-html-4-0-pages\/\" title=\"Code segments for rendering html 4.0 pages\" target=\"_blank\">Code segments for rendering html 4.0 pages<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-validate-input-fields-as-the-user-is-filling-up-a-form-with-jquery\/\" title=\"How to validate input fields as the user is filling up a form with jQuery\" target=\"_blank\">How to validate input fields as the user is filling up a form with jQuery<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/a-mechanism-for-serving-http-requests-in-c\/\" title=\"A mechanism for serving HTTP requests in C#\" target=\"_blank\">A mechanism for serving HTTP requests in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/how-to-ensure-that-your-javascript-is-able-to-write-unicode-characters-from-external-javascript-files-to-your-html-contents\/\" title=\"How to ensure that your Javascript is able to write unicode characters from external Javascript files to your HTML contents\" target=\"_blank\">How to ensure that your Javascript is able to write unicode characters from external Javascript files to your HTML contents<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/deciding-which-http-status-code-to-use-in-a-http-response\/\" title=\"Deciding which HTTP status code to use in a HTTP response\" target=\"_blank\">Deciding which HTTP status code to use in a HTTP response<\/a><\/li>\n<\/ul>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-3l\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-3l&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-3l&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F207&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>This was a proof of concept to try out jQuery&#8217;s ajax features. <strong>A<\/strong>synchronus <strong>J<\/strong>avascript <strong>A<\/strong>nd <strong>X<\/strong>ML is a way for avoiding unnecessary refresh of the entire web page. When used properly, it can enhance user experience for your website, especially when you have lots of images on your page which does not change often across different pages.<\/p>\n<p><strong>This proof of concept was based on <a href=\"http:\/\/blog.jquery.com\/2011\/11\/21\/jquery-1-7-1-released\/\" title=\"Link to download jQuery 1.7.1\" target=\"_blank\">jQuery version 1.7.1<\/a><\/strong>.<\/p>\n","protected":false},"author":1,"featured_media":1208,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[119,118,120,121,122,89,123],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/jquery-logo-mark-dark.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-3l","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/207"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=207"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/207\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1208"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=207"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=207"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=207"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}