简体   繁体   中英

Pass JS array to PHP via Ajax

I have an array in javascript and I need to convert it into PHP array. So I have this code and I have tried other codes too but no one has worked. Here is the code:

 <!DOCTYPE html> <html> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <div id="res" style="border: 1px solid black; width: 400px; height: 200px;"></div> <br> <input type="file" name="img[]" id="img" multiple> <input type="submit" name="submit" id="submit"> <script> var array = new Array(); $('#img').change(function() { var img = $('#img').val().split('\\\\').pop(); array.push(img); document.getElementById('res').innerHTML = array; }); $('#submit').click(function() { var send_data = JSON.stringify(array); $.ajax({ type: "POST", enctype: "multipart/form-data", url: "test.php", data: {send_data:send_data}, datatype: "JSON", success: function(data) { } }); }); </script> </body> </html>

And my test.php

 <?php $data = $_POST['send_data']; $decoded = json_decode($data, true); var_dump($decoded); ?>

HTML && Javascript sample code:

 function validateForm() { let formData = { 'name': $('input[name=name]').val(), 'email': $('input[name=email]').val(), 'message': $('textarea[name=message]').val() }; //Prevent page from refresh after sending message (ajax) $.ajax({ url: "./assets/php/contact_me.php", type: "POST", data: formData, success: function (data, textStatus, jqXHR) { if (data.code) $('#status').text(data.message); }, error: function (jqXHR, textStatus, errorThrown) { $('#status').text("Error"); } }); }
 <a class="btn" onclick="validateForm()">Send Message</a> <!-- Status text --> <div id="status" class="text-danger pb-2"></div>

PHP Code:

<?php

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

header('Content-Type: application/json');
if (strlen($name) < 3){
    print json_encode(array('message' => 'Name is too short', 'code' => 0));
    exit();
}
if ($email === ''){
    print json_encode(array('message' => 'Email cannot be empty', 'code' => 0));
    exit();
} else {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        print json_encode(array('message' => 'Email format invalid.', 'code' => 0));
        exit();
    }
}
if (strlen($message) < 5){
    print json_encode(array('message' => 'Message is too short', 'code' => 0));
    exit();
}
print json_encode(array('message' => 'successfull!', 'code' => 1));
exit();

I have an array in javascript and I need to convert it into PHP array.

You can transform a javascript array (call it myDataAsJSArray ) into a JSON string, before POST -ing:

let myDataAsJSON = JSON.stringify('myDataAsJSArray');

After POST -ing, you can transform the JSON string into a PHP array :

$My_Data_As_PHP_Array = json_decode($_POST['myDataAsJSON'], TRUE);

Note that if you omit the optional TRUE parameter immediately above, PHP will transform your JSON into a PHP Object, rather than a PHP Array.


Further Reading:

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