简体   繁体   中英

Undefined Index error when sending array to PHP via AJAX

I've tried the fixes for similar questions but nothing has worked for me.

Trying to send an array to PHP via AJAX when my submit button is pressed.

In the PHP file I get the error - Notice: Undefined index: data

HTML

 <form id="email-form" action="add-user.php" method="post">
       ...
 </form>

Javascript

var frm = $('#email-form');
frm.submit(function (ev) {
var cars = ["Saab", "Volvo", "BMW"]; //this is the array i want to send for purposes of this question
var jsonString = JSON.stringify(cars);
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: {'data': jsonString},
        success: function () {
            alert('ok');
        }
    });
});

PHP (add-user.php)

$data = json_decode(stripslashes($_POST['data']));

foreach($data as $d){
echo $d;
}

Get same error when trying- data: {data: jsonString}

console.log(jsonString) shows me the array so I know it exists.

Any ideas as to what is causing undefined index error? Thanks in advance.

When you submit the form, the submit event fires. This triggers the normal Ajax request. The submit function then finishes running and the form submits.

The browser leaves the current page, and discards the execution environment containing the event handler waiting for the response to the Ajax request.

The server side script receives the normal form data, but the form doesn't have a data field, so you are getting the undefined index error.

You need to prevent the normal form submission:

ev.preventDefault();

You should also make sure that the fields that are actually in the form can be handled by the server side code for when the JS fails.

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