简体   繁体   中英

jQuery Ajax post data to same page PHP not working

Note: this is a jQuery coding exercise and I am not allowed to use plugins or other modules.

Problem: I have a simple form on which I want to process the POST form data - same page processing.

HTML + PHP on same page:

<?php
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>
<head>
  <title>jQuery Forms</title>
  <link rel="stylesheet" href="css/global.css">
</head>
<body>
    <form id="myForm" action="">
          <input type="text" placeholder="Email" id="email" name="email">
          <span class="error">Email not entered</span><br />
          <input type="password" placeholder="Password" id="pword" name="pword">
          <span class="error">Password not entered</span><br />
          <input type="text" placeholder="First Name" id="fname" name="fname">
          <span class="error">First Name not entered</span><br />
          <input type="text" placeholder="Last Name" id="lname" name="lname">
          <span class="error">Last Name not entered</span><br />
          <input type="submit" value="Submit">
    </form>
  <script src="jquery.js"></script>
  <script src="form.js"></script>
</body>
</html>

Note: from other answers on here about same page processing using ajax I read that the url property should be left out for this.

jQuery form.js:

// jQuery form validation
$(document).ready(function(){

    // field mapping
    var form_fields = {
        'email' : 'email',
        'pword' : 'password',
        'fname' : 'first name',
        'lname' : 'last name'
    };

    // ajax data
    var ajaxData = {};

    // make sure form fields were entered
    $('#myForm').on('submit', function(e){

        for (var field in form_fields) {
            if (!$('#' + field).val()) {
                $('#' + field).next().addClass('error_show');
            } else if ($('#' + field).val()) {
                $('#' + field).next().removeClass('error_show');
                ajaxData[field] = $('#' + field).val();
            }
        }
        console.log(ajaxData)
        $.ajax({
            type    : 'POST',
            data    : ajaxData,
            success : function() {
                console.log('success');
            },

            error   : function(xhr, status, errorThrown) {
                console.log('error');
            }
        });
        return false;

    });

});

When I type in data into the form fields as so I get the following from jQuery:

ajaxData: Object {email: "robert@stackoverflow.com", pword: "123", fname: "Robert", lname: "Rocha"}

and a success message indicating that it was successful. Yet when I print the GLOBAL variables to see what data was passed to the page they come up as empty:

Array
(
    [_GET] => Array
        (
        )

    [_POST] => Array
        (
        )

    [_COOKIE] => Array
        (
        )

    [_FILES] => Array
        (
        )

    [GLOBALS] => Array
 *RECURSION*
)

Your code is working fine - I've pulled it down and run it locally and it does in fact POST that sample data to your server.

If you are using Firefox or Chrome (or really any browser should be fine), you will need to open up the inspector/Firebug and look at your network requests.

You are sending the form data over an http request , so the actual page you have open in your browser will not change or reload. Instead you will see the request being made from the current page via the Network panel, or in the JavaScript console if you enable Show XMLHttpRequests or Log XMLHttpRequests .

Here is a screenshot to show you what I mean: 在此处输入图片说明


If you want to have it submit back to the same page with a reload, you could update your form submit handler to do something like this:

// make sure form fields were entered
    $('#myForm').on('submit', function (e) {

        for (var field in form_fields) {
            if (!$('#' + field).val()) {
                $('#' + field).next().addClass('error_show');
            } else if ($('#' + field).val()) {
                $('#' + field).next().removeClass('error_show');
                ajaxData[field] = $('#' + field).val();
            }
        }
        if ($('#myForm').find('.error_show').length) {
            e.preventDefault();
        }
    });

Note I removed the AJAX code and just prevent the form from submitting if it doesn't have all of the values set properly.

In your current html, this will add it to your page URL as post data. If you want to actually have it send over the POST method (recommended), you will need to update your form with that setting:

<form id="myForm" action="" method="post">
...

Also checkout the jQuery validate plugin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM