简体   繁体   中英

cannot receive js array posted with ajax

I am trying to send form data and js array to mysql database. I am having problem with receiving js array into my php. I receive data from form but not the array. I can't find the problem.

index.php

<!doctype html>
<html lang="en">
<head>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><!--bootstrap-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script><!--jquery-->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><!--angular js-->
<script type="text/javascript" src="assets/js/main.js"></script>

</head>
<body>
<form method="post" action="upload.php">
<!--dynamic form created from javascript-->
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
</body>
</html>

javascript -- main.js

var objArray = []; //Array of questions

function upload(){
            var jsonArray = JSON.stringify(objArray);

            $.ajax({
                type:'post',
                url: 'upload.php',
                data: { jsonData : jsonArray},
                success: function(data){
                   console.log("success!");
               }
            });

    } else {
        console.log("no data javascript!");
    }
}

upload.php

<?php

if(($_SERVER['REQUEST_METHOD'] == "POST") && (isset($_POST['submit']))){

    $servername = "......";
    $username = "......";
    $password = "......";
    $dbname = ".....";

    // Create connection
    $conn = new mysqli($servername, $username, $password,$dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    if(!empty($_POST['jsonData'])){
        $json = $_POST['jsonData'];
        var_dump(json_decode($json, true));
        echo "<script type=\"text/javascript\">
              console.log('received data');
        </script>";
     } else {
        echo "data not received";
     }

    $conn->close();

}else {echo "unsecure connection";}
?>

objArray looks like this:

[{"questionId":1,"questionTypeObj":"single","options":3},{"questionId":2,"questionTypeObj":"single","options":3}]

upload.php outputs "data not received"

when you click the button your code are going to send 2 requests to the server

First request-the ajax

this ajax request has the parameter you need jsonData : jsonArray and right after that you are going to send another request

Second request-submitting the form

and the form has no jsonData : jsonArray paramter sent with it

you don't need this ajax at all!

all you need to do to receive the jsonData : jsonArray paramter is to send it along with the form

for example:

change your form to be like this

<form method="post" action="upload.php">
<input id="jsonData" type="hidden" name="jsonData" value="">
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>

and change your button function to be like this

function upload(){
     var jsonArray = JSON.stringify(objArray);
     $('input#jsonData')[0].value=jsonArray ;
}


EDIT :

Or if you want upload.php to process the ajax request, and not to response with a whole document then you don't need the form, remove the form from your HTML , and just add submit:Upload to the ajax request

  data: { jsonData : jsonArray, submit:"Upload" } 

Your output indicates what the problem is: You get to the part where you echo data not received but you are not sending a submit key: $_POST['submit'] is not set when called through ajax.

So you are submitting your form the "normal" way and not through ajax.

This is caused by the fact that you are not cancelling the default submit action of your button.

The best way to solve that (in my opinion...), is to remove the inline javascript - the click handler - and replace your function with:

$("form").on('submit', function(e) {
    // Cancel the default form submit
    e.preventDefault();

    // The rest of your function
    var jsonArray = JSON.stringify(objArray);
    ...
});

Note that I am catching the form submit event. You could also replace that with the button click event but that might not work correctly when a visitor uses the enter key in a form field.

You shouldn't be doing it this way. There's no way to guarantee that the javascript will execute before you redirect. In fact, it won't run fast enough, and will just redirect to the next page. Try

<form method="post" action="upload();">

This will get the data to the page, but it won't display it. If you want it displayed you should have forms submitting it. If you post with ajax you can also try to catch the response with jquery.

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