Passing Javascript array to PHP file [duplicate]

2019-03-28 00:30发布

So I know that Javascript is client-side and PHP is server-side and that complicates thing but I'm wondering how to go about doing this.

I have an array in my javascript code (in a HTML file) and when the user hits my submit button I want the page to send over that array to my PHP page which will then take that date and put it into a SQL database.

Is there a simple way to doing this? My array is declared like this var markers = []; it is just a variable in the javascript portion of the code.

I've looked at a bunch of other posts concerning this but all the solutions will not fit what I need to do, or require WAY too much of a change for what I can do right now. I'm not really familiar with AJAX or JSON (not sure exactly what that is).

My Javascript is:

var markers = [];

function placeMarker(location) {
        var clickedLocation = new google.maps.LatLng(location);
        var name = document.getElementById("checkname").value;
        var description = document.getElementById("description").value;


        var marker = new google.maps.Marker({
            position: location,
            map: map,
            title: name,
            // This may cause a problem when reloading and editing an existing tour
            // url was found at: http://biostall.com/adding-number-or-letters-to-google-maps-api-markers
            icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + markerId + '|FE6256|000000'
        });

        marker.setMap(map);
        markers.push([markerId, name, marker.getPosition().lat(), marker.getPosition().lng(), description]);
        //alert("" + markers);
        markerId = markerId + 1;
    }

    google.maps.event.addListener(map, 'click', function(event) {
        placeMarker(event.latLng);
    });

    google.maps.event.addListener(marker, "click", function() {
        map.removeOverlay(marker);
        marker.setMap(map);
    });
} 

window.onload = function() {
    var form = document.getElementById('theform');
    form.addEventListener('submit', function(){
        var markersField = document.getElementById('markers');
        markersField.value = JSON.stringify(markers);
    });
}

My HTML is:

<form action="portal.php" method="post" id="theform">
    <input type="hidden" id="markers" name="markers">
    <button>Submit</button>
</form>

In my portal.php file I have:

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

Nothing prints out in the php page even though I know there are elements in the array, this leads me to believe the array is not being passed over.

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-28 00:48

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

查看更多
我命由我不由天
3楼-- · 2019-03-28 00:55

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.

查看更多
该账号已被封号
4楼-- · 2019-03-28 00:56

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']);
查看更多
做个烂人
5楼-- · 2019-03-28 01:09

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);
查看更多
登录 后发表回答