javascript

How to send form data in $.post jQuery

When using the jQuery $.post() method, one can send form data to a server without reloading the current page. This is done by serializing the form data and sending it as an argument to the $.post() method.

//create form data
var form_data = {
    "first_name": "John",
    "last_name": "Deo"
};

// send form data in post request 
$.post("api_url.php", form_data, function(response) {
    console.log(response);
});

The code above is making a POST request to the api_url.php file.

The form_data variable is being passed as data in the request.

The function(response) is a callback function that is executed when the POST request is complete. The response variable contains the data that is returned from the api_url.php file.

Serialize form and send its data in $.post

This title refers to a process in which data from a form is converted into a format that can be transmitted to a server, using the $.post() method. This is often done in order to save the form data in a database or to send it to another server for processing

$.post("api_url.php", $("#my_form").serialize(), function(response){
    console.log(response);
});

1) The code above uses jQuery's post method to send a post request to the api_url.php file.

2) The data being sent in the post request is serialized form data from the my_form element.

3) The response from the api_url.php file is logged to the console.

Was this helpful?