Passing Javascript array to PHP file [duplicate]

空扰寡人 提交于 2019-12-03 14:25:43

I'm assuming your page is already being reloaded when you submit the form, and that you don't have a problem with that. If so, you can add a hidden field for that data, and add it to the field just before the form submits:

<form method="post" id="theform">
    <!-- your existing form fields -->

    <input type="hidden" id="markers" name="markers">

    <button>Submit</button>
</form>

Then use this JavaScript

window.onload = function() {
    var form = document.getElementById('myform');
    form.addEventListener('submit', function(){
        var markersField = document.getElementById('markers');
        var markers = [1,2,3];
        markersField.value = JSON.stringify(markers);
    });
}

And add this to your PHP, where you handle the submitted form data:

$markers = json_decode($_POST['markers']);

This is probably the most straight forward way of doing it. It uses jQuery which is good for this kind of stuff. The first part just sends the array as the markers parameter in an AJAX POST.

// Javascript / jQuery
$.ajax({
    type: 'POST',
    data: markers,
    dataType: 'json',
    url: 'yourPHPFile.php'
});

This part is the PHP that receives the post and decodes the JSON to a PHP array.

// PHP in 'yourPHPFile.php'
// Santizing the string this way is a little safer than using $_POST['markers']
$markersFromPost = filter_input(INPUT_POST, 'markers', FILTER_SANITIZE_STRING);

// Turn the sanitized JSON string into a PHP object
$markers = json_decode($markersFromPost);

You will need to learn the basics of AJAX and JSON. jQuery can help you with this and I'd recommend it as a good starting point.

Submit JSON using AJAX, then use $phpArray = json_decode($submittedJson); and viola, you will have a nice PHP array of the submitted javascript object.

Youn Elan

send a json object and convert it to an array with json_decode($obj)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!