6

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.

intA
  • 2,513
  • 12
  • 41
  • 66
  • 7
    well then you should become familiar with AJAX. It's the only way to do this... – Wouter J Mar 25 '13 at 22:03
  • Pretty sure the only way to do this is with some sort of ajax solution. jQuery makes it really easy, if you have any experience with that. – dmikester1 Mar 25 '13 at 22:04

4 Answers4

10

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']);
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • 2
    +1 for pointing out that AJAX is not the only solution – Justin Bicknell Mar 25 '13 at 22:13
  • +1 That is a good point. It is probably actually easier to do with jQuery though. It isn't perfect for everything, but it is good for this. – pseudosavant Mar 25 '13 at 22:34
  • This seems to make sense, thanks! Do I need to specify the php file I'm looking to send it to somewhere? Also, if the markers array already exists is it just as simple as removing that line where you create markers? – intA Mar 26 '13 at 15:59
  • 1
    @Skytbest Doesn't your form already have an `action` attribute? It tells the form which PHP to submit to. If it's missing (like in my example), it submits to the current file. About the variable markers, yes, my code was just an example. You can use any variable, provided it's in scope. – bfavaretto Mar 26 '13 at 16:20
  • Yup, ok just wanted to be sure. Should the page automatically reload when I submit or do I have to tell it to explicitly? – intA Mar 26 '13 at 18:25
  • @Skytbest It submits/reloads to the url specified in the action attribute, no js code needed. That's how html forms work. It's actually a limitation, which ajax tries to solve. That's why you got so many ajax-related answers. – bfavaretto Mar 26 '13 at 18:38
  • Ok, cool. I edited my original question and put the code that I'm using. It is still not working for some reason, do you think you could look at it quick and see if there are any glaring mistakes? – intA Mar 26 '13 at 18:45
  • In the code you posted, the `markers` array is not defined. You have to define it somewhere on your JavaScript, and add values to it. – bfavaretto Mar 26 '13 at 18:50
  • Oh, well yea, it is defined earlier in the code and elements are added to it as the user clicks on a google maps panel on the page. I'll throw it in there too – intA Mar 26 '13 at 18:52
  • 2
    This is getting too complex to solve in comments. I suggest you post a new, follow up question explaining the new issues you're having. This is now way beyond the scope of your original question, which by the way is closed, so you can't get any new answers here. Also, don't forget to check your browser console, it will show you JavaScript errors when they occur, and that's essential information to help you debug your code. – bfavaretto Mar 26 '13 at 18:56
5

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);
pseudosavant
  • 7,056
  • 2
  • 36
  • 41
3

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.

greg
  • 6,853
  • 15
  • 58
  • 71
1

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

Wouter J
  • 41,455
  • 15
  • 107
  • 112
Youn Elan
  • 2,379
  • 3
  • 23
  • 32
  • Do this use delimiters? I can't really have delimiters since the array include user inputted text and I don't want to limit what the user can input. – intA Mar 26 '13 at 16:07