0

rookie here. I've searched and searched and still remain ignorant.

I am making an array of markers/info windows for a Google Maps API. Currently, I have succeeded in loading my markers from an external JSON file. JSON data looks like this: https://codedump.io/share/5XUwRzOFvREi/1/json-array pathway ./json/Markers

{"Markers": [
{
  "title" : "Meow Monestary",
  "position" : {
    "lat" : 40.5178,
    "lng" : -122.6438
  },
  "posterContact" : {
    "name" : "Mr Meowser",
    "email" : "[email protected]",
    "phone" : "(555)-202-3040",
    "private" : true
  },
  "type" : "myResidence",
  "ownerContact" : {
    "name" : false,
    "email" : false,
    "phone" : false,
    "private" : true
  },
  "description" : "Meow meow purrrrr.  Dogs are not my favorite but they are my second favorite.",
  "private" : true
},

I want users to be able to fill out a form containing all of this data and then push the new marker object into the JSON array. So far I have collected the form, created a Javascript object, and converted it to a JSON string like this...

function submitForm(){
        //place form data into array
        var formData = $("#shelterForm").serializeArray();

        //build the javascript object using the values in the array
        var shelter = {
          title:formData[0].value,
          position:{
            lat:formData[1].value,
            lng:formData[2].value
          },
          posterContact:{
            name:formData[3].value,
            email:formData[4].value,
            phone:formData[5].value,
            private:formData[6].value
          },
          type:formData[7].value,
          ownerContact:{
            name:formData[8].value,
            email:formData[9].value,
            phone:formData[10].value,
            private:formData[11].value
          },
          description:formData[12].value,
          private:formData[13].value
        };
  shelterString = JSON.stringify(shelter);
}

I'm sure there was an easier way to do this. If you feel inclined to go into this... GREAT!! My main issue though is that now I have my JSON string, but can't figure out how to push it into my array. I'm thinking maybe pass the string to PHP and write to file, or possibly ajax allows this?

2 Answers 2

2

Whether or not you use AJAX, you will still need a script on the server to save the data server side. Doing an AJAX request is more advanced than just a regular form POST, so I would recommend against it for a beginner.

Once the data is sent to PHP, you will need to store it. The most common way this would be done is with a database, typically MySQL. When the form is posted, you would get the data from the $_POST variable and store it as a new row in the database. Then, for the JSON file, rather than using a static file, you would point the maps to a PHP script for the external JSON file. That script would then query the database, assemble the data into an associative array with code very much like your javascript submitForm() function, and then call json_encode() to convert that array into a JSON string that it would then print. On the client side, you would not need your submitForm() function anymore.

If you don't want to mess around with a database, you can use a regular file on your server and have the PHP script modify that file. It is a little messier, though, and if you have an error in your script or the server loses power while writing the file, you could lose all your data, so I would recommend also setting up a daily backup if you have important data in the file. Also, you will have to take special precaution to not allow two different people to submit their updates at the same time, since having two processes writing to the same file concurrently will cause garbage data. Databases are built to be more resilient to these problems out of the box.

If you want to go the file route, you would probably still want to move the creation of the JSON into PHP. Your javascript relies on the exact indicies of the form elements, and is hard to read and maintain. In PHP, you would have something like:

$shelter = [
      'title' => $_POST['shelter_title'],
      'position' => [
        'lat' => $_POST['shelter_latitude'],
        'lng' => $_POST['shelter_latitude']
      ],

The $_POST keys are the name attributes from your form elements, which makes it much easier to maintain than using index numbers, which would have to be renumbered if you added or removed a form field.

Then, you would need to lock the json file to make sure that two processes don't try to update it at the same time

if (!flock($json_filename,LOCK_EX)) {
  die('We are having trouble updating our records. Please try again later.');
}
//Now nobody else can write to the file until the script finishes or calls flock($json_filename, LOCK_UN) to release the lock

Then, we load the old JSON file, and update it with our new record:

$old_json = file_get_contents($json_filename); //get JSON data as string
$old_data = json_decode($old_json); //convert JSON data into PHP array
$new_data = array_push($old_data['Markers'], $shelter); //add the new shelter to PHP array
$new_json = json_encode($new_data); //convert the PHP array back to a JSON string
file_put_contents($json_filename, $new_json); //write the string to the file
//json file is updated, so now you can display a message, or redirect the user to a new page with header('Location: foo')

I haven't tested this code, so back up your JSON before trying this.

Sign up to request clarification or add additional context in comments.

1 Comment

Alright thanks, that is some good advice to have. I am looking into mySQL now to better understand how to use a database. I think it sounds worth it.
1

What you should be doing here, is to have a local json file to which the google map api would be pointed to and to add to that file using the html form with a php action where you would ingest the form data and add it to the json file.

<form action="addJson.php" method="post">

addJson.php (to get the general idea)

<?php
$localFile = 'json/Markers.json';
$data = [$_POST]; // reformat if required
$existing = json_decode(file_get_contents($localFile));
$all = array_merge($existing,$data);
file_put_contents($localFile,json_encode($all));

echo 'thanks for addition';
?>

And you can totally omit the javascript submitForm function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.