I am sorry if this is a duplicate question. I have searched for an answer but nothing seems to work.
I am trying to send quite a large JSON object to a PHP file via POST.
This is my JavaScript code :
var grid =
{
"user": 1,
"grid": JSON.stringify(hz),
"week": WEEK,
"AP": AP,
"X_VAL": X_VAL,
"Y_VAL": Y_VAL
};
grid = JSON.stringify(grid);
$.ajax({
url:"php/saveGrid.php",
type: "POST",
data : "g="+grid,
success: function (data, textStatus, jqXHR)
{
console.log(data);
}
});
This is my PHP code :
$g = stripslashes($_REQUEST["g"]);
echo $AP = $g->AP;
But this returns an error which says :
Trying to get property of non-object
What am I doing wrong?
Your primary problem is that you are trying to treat a string of JSON as if it were a PHP object.
You need to parse it first.
$g = stripslashes($_REQUEST["g"]);
$g = json_decode($g);
echo $AP = $g->AP;
You also have some secondary issues.
You failed to URL encode the JSON, so if it contains characters with special meaning in URLS, it will break.
data : "g="+grid,
should be:
data : { g: grid },
You should not need to run stripslashes over input from $_REQUEST/POST/GET.
If you don't have magic quotes turned on, then it could break the incoming data if it contains slashes.
If you do have magic quotes turned on, then you should turn them off or upgrade to a modern version of PHP (which wouldn't support them).
Nesting JSON inside JSON is silly. It bloats the data and makes it more work to read.
"grid": JSON.stringify(hz),
should be:
grid: hz,
$_REQUEST could get data from the query string, or the request body, or a cookie. You know it is coming in the request body so just use $_POST to remove the ambiguity.
You need to decode the json object then can use it as an array. Try, json_decode. Like,
$g = stripslashes($_REQUEST["g"]);
$json_de=json_decode($g);
echo $AP = $json_de['AP'];
Or if you want to see the full array then use,
print_r($json_de);
Hope this will help you.
Related
I'm having this collection of objects which are inside a html text area:
{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...
...
Is there a way to send the whole collection to node js and iterate through it to get values of objects?
My AJAX code:
$.ajax({
type: "POST",
url: "https://example.com/nodeapp",
data: '['+document.getElementById("list").value+']',
success: function(data) {
console.log(data);
}
});
I tried to do a foreach on req.body, but it doesn't seem to work:
var arr = req.body;
arr.foreach(element=>{
console.log(element.email);
})
Gives the error:
TypeError: arr.foreach is not a function
At first , you have to parse the body by using JSON.parse() function .
Like this :
var arr = JSON.parse(req.body);
arr.forEach(element=>{
console.log(element.email);
});
The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .
I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:
'[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},
{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...]'
Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:
{
"<<the array in string format>>" : ""
}
How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)
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.
I am not really sure how to phrase this question, so I will just ask the best I can.
I would like to know how to grab the contents of a webpage and place it in a string or array so I can parse the data.
This is the webpage: https://campusdata.uark.edu/api/buses?callback=?&routeIds=8
The webpage returns something like this:
?([{"id":25,"fleet":15,"name":"Fleet 15","description":"","zonarId":9,"gpsId":"8061088","latitude":"36.0680039","longitude":"-94.1758039","speed":0.000,"heading":89.700,"power":true,"date":"\/Date(1456339080000)\/","color":"#0090ff","routeName":"Blue","routeId":8,"distance":9999999999,"nextStop":"Garland Center","nextArrival":"8 mins"},{"id":33,"fleet":6,"name":"Fleet 6 ","description":"","zonarId":13,"gpsId":"8061090","latitude":"36.0818423","longitude":"-94.1707598","speed":0.000,"heading":181.700,"power":true,"date":"\/Date(1456339200000)\/","color":"#0090ff","routeName":"Blue","routeId":8,"distance":2.31887983012931,"nextStop":"South Creekside","nextArrival":"1 mins"}]);
I am not sure the best way to go about this... AJAX through JQuery? Maybe a php call? I don't know.
I have searched for this, but like I said, I don't know exactly how to phrase the question, so my search results have been sporadic at best.
Can someone help me please?
Seems like a JSONP call. You can use jQuery to easily fetch the data from the API end point. Please see the example below:
$.ajax({
url: "https://campusdata.uark.edu/api/buses?callback=?&routeIds=8",
// The name of the callback parameter
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
data: {},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
Here is a jsfiddle with working example.
Please make sure to include jquery in the page before trying this.
Your can use this in PHP
$site = file_get_contents("http://campusdata.uark.edu/api/buses?callback=&routeIds=8");
print_r(json_decode($site));
Reference
json_encode
file_get_contents
Get the page content with file_get_contents function. Remove illegal character. Convert the json format to PHP array:
<?php
$page = file_get_contents('https://campusdata.uark.edu/api/buses?callback=?&routeIds=8');
$page = substr($page, 0, -2);
$page = substr($page, 2);
var_dump (json_decode($page));
I'm storing different values in the sessionStorage during a longer process. At the end i want to read all the data and send it to my php backend using ajax. The problem is that php seems to take every value including quotes. Here is what i got:
// Reading data from storage
var imgb = sessionStorage.getItem("img_b_id");
....
// perpare data
var oData = {
imgb: imgb,
...
};
// Sending data
$.post( "../php/direct/create.php", oData).done(function(data) {
if(data==true) {
window.open("step5.php", "_self");
} else {
alert("Error: " + data.toString());
}
});
This is working perfectly fine. However, php will read the value of imbg with quotes. Example:
echo $_POST['imgb'];
/* Returns "asd" instead of asd
The image below shows that my data is stored without the quotes (chrome sessionstorage screenshot)
Do you have any suggestions on how to solve this. I currently replace the quotes, but I'd love to fix this problem at it's root...
I have tried your code ( with Firefox and Chrome ) and
echo $_POST['imgb'];
Print the string without quotes.
Consider that even if you set a number in the session storage, for example
sessionStorage.setItem("img_b_id", 100);
The value is received at server by PHP as a string so you can convert it with PHP functions intval(), floatval() etc.
http://php.net/manual/en/function.intval.php
I'm collecting some data from my page, storing the data in an array for multiple uses on the page, and sending a copy of the array via AJAX, storing the data in the database on a PHP page.
One piece of data I'm storing in the array is the output of a TinyMCE WYSIWYG editor, so it contains HTML, but have just found this to be a problem - I'll explain:
After entering one line of text in my WYSIWYG editor and I trigger my AJAX event, this is the JSON string displayed in my console and everything worked okay, the database was sent and stored:
{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdg.</p>","keywords":""}
If I write two lines of text, this is the JSON string and was successful:
{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdg.</p>\n<p>fgfgfdg</p>","keywords":""}
Now, if I write one line of text and press return and not type anything on the second line, I get the following which fails.
{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdgdfgdfgdfgdfg.</p>\n<p> </p>","keywords":""}
It seems broke my JSON output somehow. My PHP can't access the decoded array values, as there is no array. print_r(json_decode($json)) returns nothing. Can anybody help?
This is my HTML page with jQuery:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
var post_data = {};
post_data.id = post_id;
post_data.topic = topic;
post_data.title = title;
post_data.description = description;
post_data.content = tinyMCE.activeEditor.getContent();
post_data.keywords = keywords;
post_data = JSON.stringify(post_data);
save_post_request = $.ajax({
url: 'ajax/save-post.php',
type: 'POST',
data: "save_mode="+save_mode+"&post_data="+post_data,
dataType: 'text',
cache: false
});
</script>
This is my PHP page:
header('Content-type: application/json; charset=UTF-8');
$post_data = isset($_POST['post_data']) ? $_POST['post_data'] : null;
$post_data_arr = json_decode($post_data, true);
$post_id = $post_data_arr['id'];
$topic = $post_data_arr['topic'];
// others
$content = $post_data_arr['content'];
if (!$post_data_arr['id']) {
// fails here
// id is not accessible when the JSON contains <p> </p> in the 'content' item
}
This is what Firebug says:
You are placing the JSON into some URL Encoded data, but you are not URL Encoding it.
The & character has special meaning in URL Encoded data (it separates key/value pairs), so this means you are breaking the data.
Use the encodeURIComponent function to properly encode your data before adding it to the string:
data: "save_mode="+encodeURIComponent(save_mode)+"&post_data="+encodeURIComponent(post_data),
However, since you are using jQuery, you shouldn't be constructing your URL Encoded data by hand in the first place. jQuery can do it for you. Pass data an object instead of a string:
data: {
save_mode: save_mode,
post_data: post_data
},