jquery send form data to php

Solutions on MaxInterview for jquery send form data to php by the best coders in the world

showing results for - "jquery send form data to php"
Johanna
27 Aug 2018
1<form id="foo">
2    <label for="bar">A bar</label>
3    <input id="bar" name="bar" type="text" value="" />
4
5    <input type="submit" value="Send" />
6</form>
7
8// Variable to hold request
9var request;
10
11// Bind to the submit event of our form
12$("#foo").submit(function(event){
13
14    // Prevent default posting of form - put here to work in case of errors
15    event.preventDefault();
16
17    // Abort any pending request
18    if (request) {
19        request.abort();
20    }
21    // setup some local variables
22    var $form = $(this);
23
24    // Let's select and cache all the fields
25    var $inputs = $form.find("input, select, button, textarea");
26
27    // Serialize the data in the form
28    var serializedData = $form.serialize();
29
30    // Let's disable the inputs for the duration of the Ajax request.
31    // Note: we disable elements AFTER the form data has been serialized.
32    // Disabled form elements will not be serialized.
33    $inputs.prop("disabled", true);
34
35    // Fire off the request to /form.php
36    request = $.ajax({
37        url: "/form.php",
38        type: "post",
39        data: serializedData
40    });
41
42    // Callback handler that will be called on success
43    request.done(function (response, textStatus, jqXHR){
44        // Log a message to the console
45        console.log("Hooray, it worked!");
46    });
47
48    // Callback handler that will be called on failure
49    request.fail(function (jqXHR, textStatus, errorThrown){
50        // Log the error to the console
51        console.error(
52            "The following error occurred: "+
53            textStatus, errorThrown
54        );
55    });
56
57    // Callback handler that will be called regardless
58    // if the request failed or succeeded
59    request.always(function () {
60        // Reenable the inputs
61        $inputs.prop("disabled", false);
62    });
63
64});
65