Pass JSON string to PHP and push to array - javascript

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" : "MrMeow#Couch.com",
"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?

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.

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.

Related

get only specific element of a JSON database stored in server by url request

my website relies on a database which is a big JSON file like this:
var myjsonData =
[ {
"ID": 0,
"name": "Henry",
"surname": "McLarry",
"...": "...",
}]
I do generate this data every month at high cost to me, therefore I would like to avoid calling it straight in my html <head>, because this will allow any user to download the full database in no time.
I would like to build a "something" that can only call specific items from the json file (just the only one I want to show) without "exposing" the full .json onto client side.
today I use the call
var myvar= myjsonData.ID.Name
to get "Henry" into myvar, I would like to build something like
var myvar = mycallfunction(ID,Name)
I did try with PHP as intermediary but the ajax calls from javacript doesn't allow me to fetch the data.
Can I use JQuery with the JSON Url to get only the item I need?
What you can do is parse your json for an object. So you can get any value you want from json.
Example:
var myjsonData = '{"ID": 0,"name": "Henry","surname": "McLarry"}';
obj = JSON.parse(myjsonData);
console.log(myjsonData.ID); //print the id
console.log(myjsonData.name); //print the name
console.log(myjsonData.surname); //print the surname
So you have a NoSQL Database which has only one kind of Document that is the full JSON element you use in your website. In that scenario you have three options:
Depending on the NoSQL Database you're using you can limit the fields which will be returned(I.e: For MongoDB you can look here: https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/)
Change the way you store you data into more modular documents and make the logic to connect them in you application. So instead of one big document you'll have modular ones as Users, Products, Transactions and etc and you can use your application to query them individually.
Build a Server Side logic as an API to deal with your data and provide only what you need, so the API(Which can be node.js, php, or any you may like) will get the full JSON it`s endpoints will only the data you want. For example: myapi.com/getUser, myapi.com/getProducts and so on.
If you're able to provide more info on the technologies you're using that would help us. Hope that helped :).

How to properly unpack data from PHP array encoded as JSON from a JavaScript file

I have been doing searches for hours upon hours and have tried different snippets of codes and techniques and I simply cannot get any of them to work. I have done research, I am simply a very inexperienced developer trying to learn as I go.
My ultimate goal: Have a live-updating graph of test results data pulled from a MySQL database and rendered using Chart.JS library.
What I have done so far:
I have an HTML file with embedded JavaScript and calls to AJAX function to auto-refresh page every 5 minutes (this has been tested and works).
I have a PHP file which opens a PDO connection to a local MySQL database, runs 3 selection queries, and stores the results into 3 PHP arrays. (I have iterated through the arrays and echoed the results and the data is good).
I have then stored the data inside these PHP arrays into a JSON object using json_encode()
e.g.
$totalTestsPassedArray = array();
$sql = "SELECT totalTestsPassed FROM execution ORDER BY lastDate";
$query = $conn->prepare($sql);
$query->execute(array(':totalTestsPassed' => $totalTestsPassed));
while($row = $query->fetch()){
array_push($totalTestsPassedArray, $row['totalTestsPassed']);
}
$json_totalTestsPassedArray = json_encode($totalTestsPassedArray); //pack data into JSON object
echo $json_totalTestsPassedArray; // for accessibility by AJAX
foreach ($totalTestsPassedArray as $item){ //print out contents of array
echo $item . '<br>';
}
I read that one method to consume this JSON data is to use jQuery's $.getJSON method, and in order to use it, I must 'echo' out the results of my json_encoded object. I realize I am printing the results twice. The echo $json_totalTestsPassedArray is for the aforementioned purpose.
I have included the path of this PHP file in my HTML file from #1 using <?php require '../file_name.php';?>
I have tried several ways of unpacking this JSON encoded object packed with my database data: using AJAX requests, making a new array in the HTML and then flooding it with the JSON object using $.getJSON, and some other things people have suggested to do on various documents online, all met with failure.
Could someone please tell me the proper way to do what I am trying to do? I have a PHP file with an array of data, and I would like to pass that array of data into a dataset for use by Chart.JS to populate a graph and then draw it to the canvas and display my results.
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data : [DATA FROM MY PHP ARRAY IN ANOTHER FILE WOULD GO HERE...]
}
Again, please forgive my ignorance. I have tried my best to figure out the solution on my own and would really appreciate some guidance. It's my first time using these tools. I thought it would be as simple as:
Query DB using PHP script
Store results into array
Pack into JSON object (the goal being to transfer data from PHP to JS file)
Unpack JSON object in JavaScript
Load unpacked data into my JavaScript array
In php print only json and set header content type to application/json then your XHR response will contain javascript object with your data. There is no need for any json parsing.

Getting all of the .json files from a directory

I'm creating an android app which takes in some json data, is there a way to set up a directory such as;
http://......./jsons/*.json
Alternatively, a way to add into a json file called a.json, and extend its number of containing array data, pretty much add more data into the .json file this increase its size.
It could be by PHP or Javascript.
Look into Parsing JSON, you can use the JSON.parse() function, in addition, I'm not sure about getting all your JSON files from a directory call, maybe someone else will explain that.
var data ='{"name":"Ray Wlison",
"position":"Staff Author",
"courses":[
"JavaScript & Ajax",
"Buildinf Facebook Apps"]}';
var info = JSON.parse(data);
//var infostoring = JSON.stringify(info);
One way to add to a json file is to parse it, add to it, then save it again. This might not be optimal if you have large amounts of data but in that case you'll probably want a proper database anyway (like mongo).
Using PHP:
$json_data = json_decode(file_get_contents('a.json'));
array_push($json_data, 'some value');
file_put_contents('a.json', json_encode($json_data));

Codeigniter - sending json to script file

I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.

JQuery and JSON

Here's something I want to learn and do. I have a JSON file that contains my product and details (size, color, description). In the website I can't use PHP and MySQL, I can only use Javascript and HTML. Now what I want to happen is using JQuery I can read and write a JSON file (JSON file will serve as my database). I am not sure if it can be done using only JQuery and JSON.
First thing, How to query a JSON file? (Example: I would search for the name and color of the product.)
How to parse the JSON datas that were searched into an HTML?
How to add details, product to the JSON file?
It will also be great if you can point me to a good tutorial about my questions.
I'm new to both JQuery and JSON.
Thanks!
Since Javascript is client side, you won't be able to write to the JSON file on the server using only Javascript. You would need some server side code in order to do that.
Reading and parsing the JSON file is not a problem though. You would use the jQuery.getJSON function. You would supply both a url and a callback parameter (data isn't needed, because you're reading a file, so no need to send data). The url would be the path to your JSON file, and the callback would be a function that uses the data.
Here's an example of what your code might look like. I don't know exactly what your JSON is, but if you have a set called "products" containing a set of objects with the details "name" and "price", this code would print those out:
$.getJSON("getProductJSON.htm",
function(data) {
$.each(data.products, function(i, item) {
var name = item.name;
var price = item.price;
// now display the name and price on the page here!
});
},
);
Basically, the data variable in $.getJSON makes the entire contents of the JSON available to you, very easily. And the $.each is used to loop over a set of JSON objects.

Categories