AJAX PHP Post Request

jQuery.post()

jQuery.post( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR

Description: Send data to the server using a HTTP POST request.

version added: 1.0 jQuery.post( url [, data ] [, success ] [, dataType ] )

A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case.

The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).

version added: 1.12-and-2.2 jQuery.post( [settings ] )

A set of key/value pairs that configure the Ajax request. All properties except for url are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a complete list of all settings. Type will automatically be set to POST .

This is a shorthand Ajax function, which is equivalent to:

$.ajax(
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
>);

The success callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object).

Most implementations will specify a success handler:

$.post( "ajax/test.html", function( data )
$( ".result" ).html( data );
>);

This example fetches the requested HTML snippet and inserts it on the page.

Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

The jqXHR Object

As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.post() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

The Promise interface also allows jQuery's Ajax methods, including $.get() , to chain multiple .done() , .fail() , and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

Источник

AJAX PHP Post Request With Example

AJAX PHP Post request with an example

In this article, we will see how to send an AJAX PHP post request with an example. Generally, a POST request is used to send the data to a PHP file then we can use that data, process it like validation checking, data saving, mail sending, etc, and then PHP will send the response with the message, data, response code, etc.

Why We Use AJAX?

AJAX is used to perform various HTTP requests like POST, GET, PUT, etc. AJAX is used to update the part of the webpage without reloading a page. Overall, it will improve the user experience.

For example, Let’s say we are using jQuery AJAX Post request for login form so in this, we will send username and password to the PHP file. In that file, we will check the username and password into the database and allow login users or show them an error message in the login form.

Where We Can Use AJAX?

We can use AJAX everywhere on the website. Let’s see very useful places where AJAX is used.

  1. Login form to validate the user and redirect the user if successful or show messages on the form
  2. Registration form to insert data into the database, email and show server-side validations, etc
  3. Sending contact us form’s email and show success or error message on the form
  4. AJAX is used in data-tables to fetch only required data to overcome load on servers
  5. For the pagination of posts, tables, load more button effect, etc.
  6. Autocomplete search like you type Au and it brings the lists with Au words
  7. To create filters like pricing filters, colors filters, category filters, etc

Use jQuery $.ajax() Method To Send HTTP Request

Different users follow different ways to send data using AJAX. Let’s see how to do that.

1. AJAX: Send Data Using Object Parameters

To send in parameters, you need to create a JavaScript object. So to do that you need to get values using .val() function and create an object using it something like below.

But what if you have a large number of fields in your form in that case you need to submit the whole form data one by one but that isn’t a good idea right? In that case, use the second option after this point.

let firstName = $('#firstname').val(), lastName = $('#lastname').val(), message = $('#message').val(); $.ajax(< method: "POST", url: 'file.php', data: < firstname: firstName, lastname: lastName, message: message >, success: function(response)< console.log(response); >, error: function(xhr, status, error) < console.error(xhr); >>);

2. AJAX: Send Whole Form Data Using serialize() & serializeArray() Methods

serialize() method creates data in query string format so due to that submitting a file with this function won’t work.

serializeArray() method creates data in JavaScript array objects.

Suppose, you have a form and you want to submit the whole form data using AJAX then you can do something like the below:

let formData = $('#myForm').serialize(); /* Or use serializeArray() function same as serialize() let formData = $('#myForm').serializeArray(); */ $.ajax(< method: "POST", url: 'file.php', data: formData, success: function(response)< console.log(response); >, error: function(xhr, status, error) < console.error(xhr); >>);

3. AJAX: Send Whole Form Data Using FormData() methods

The FormData() is a constructor that creates a new FormData object as below:

let myForm = document.getElementById('myForm'); let formData = new FormData(myForm); $.ajax(< method: "POST", url: 'file.php', data: formData, success: function(response)< console.log(response); >, error: function(xhr, status, error) < console.error(xhr); >>);

If you want to append extra key-value pair in FormData() object then you can use obj.append(‘key’, ‘value’) function as below:

formData.append('action', 'insert');

4. User Registration Using AJAX PHP Post Request

In this example, we will submit a simple registration form using AJAX PHP Post request.

index.php

         body < color: #fff; background: #3598dc; font-family: "Roboto", sans-serif; >.form-control < height: 41px; background: #f2f2f2; box-shadow: none !important; border: none; >.form-control:focus < background: #e2e2e2; >.form-control, .btn < border-radius: 3px; >.signup-form < width: 400px; margin: 30px auto; >.signup-form form < color: #999; border-radius: 3px; margin-bottom: 15px; background: #fff; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); padding: 30px; >.signup-form h2 < color: #333; font-weight: bold; margin-top: 0; >.signup-form hr < margin: 0 -30px 20px; >.signup-form .form-group < margin-bottom: 20px; >.signup-form input[type="checkbox"] < margin-top: 3px; >.signup-form .row div:first-child < padding-right: 10px; >.signup-form .row div:last-child < padding-left: 10px; >.signup-form .btn < font-size: 16px; font-weight: bold; background: #3598dc; border: none; min-width: 140px; >.signup-form .btn:hover, .signup-form .btn:focus < background: #2389cd !important; outline: none; >.signup-form a < color: #fff; text-decoration: underline; >.signup-form a:hover < text-decoration: none; >.signup-form form a < color: #3598dc; text-decoration: none; >.signup-form form a:hover < text-decoration: underline; >.signup-form .hint-text < padding-bottom: 15px; text-align: center; >#responseContainer  

Sign Up

Please fill in this form to create an account!


I accept the Terms of Use & Privacy Policy
Sign Up

processRegistration.php

That’s it for now. We hope this article helped you to learn how to send AJAX PHP Post requests.

Additionally, read our guide:

  1. Best Way to Remove Public from URL in Laravel
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. Active Directory Using LDAP in PHP or Laravel
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How to Convert Base64 to Image in PHP
  12. Check If A String Contains A Specific Word In PHP
  13. How To Find Duplicate Records in Database
  14. How To Get Latest Records In Laravel
  15. Laravel Twilio Send SMS Tutorial With Example
  16. How To Pass Laravel URL Parameter
  17. Laravel 9 Resource Controller And Route With Example
  18. Laravel 9 File Upload Tutorial With Example
  19. How To Schedule Tasks In Laravel With Example
  20. Laravel Collection Push() And Put() With Example

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂. Keep Smiling! Happy Coding!

Источник

PHP Ajax Form Submit Example

Asynchronous JavaScript programming is really gaining popularity day by day, so in php application development everyone wants to use Asynchronous call wherever possible.

Here you learn How to submit php ajax from using jQuery, php ajax post using jquery step by step, in order to make ajax call from php script, we have to use jquery, so you must learn jquery first ( if you are not familiar).

PHP Ajax post using jQuery

In this tutorial you will learn how to make Ajax call in Php application, Ajax is very common term for web application developer, but if you are completely new to web development world then you may have a question what exactly Ajax is ?

AJAX stands for Asynchronous JavaScript, which allows developer to make a server side call from web page without reloading then entire page again, that means using Ajax in php application you can send data to server side and pull data from backend without even rending the entire page again, using Ajax you can create a good user experience for your web application user, Ajax call is very smooth and faster for getting data from server

Ajax call can fetch data from server in either form of XML or JSON

how to make ajax call in php

You don’t need any previous knowledge to understand Ajax call, but if you are familiar with following scripting, it will be easy to understand

Here is the standard structure of JavaScript Ajax post in Php.

  

Now let’s look at another example of submitting form using Ajax and jquery in php code.

Name:
Email:

Note: in above code, e.preventDefault() method will block default click handling (it has nothing to do with Ajax form submit, you can take off that line of code), learn more about how preventDefault works

Источник

Читайте также:  Таблицы
Оцените статью