json from js to php - failed to open stream: http request failed - javascript

I am trying to send some json data from js to php, and pass it to mongo by REST.
The following outputs json string (that works fine later if I just put it as string in PHP file, please see snippet below).
JS to send json:
var s = JSON.stringify(send); //s contains previous data in arrays, etc
ic(s);
function ic(s){
var ajaxUrl = './iM.php';
$.getJSON(ajaxUrl,
{da: s},
function(data) {
console.log (data);
});
}
in iM.php:
$s = $_GET["da"]; // <-- doesn't work
//$s = '{"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]}'; //<-- works fine
$opts = array(
"http" => array(
"method" => "POST",
"header" => "Content-type: application/json",
"content" => $s,
),
);
$context = stream_context_create($opts);
$result = file_get_contents("https://api.mongolab.com/api/1/databases/$db/collections/$collection?apiKey=$key", false, $context);
var_dump($result); // Dumps the response document
At the firefox debugger, I can see the file is actually being called, however No data is added.
error_log file is created:
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
I also tried urlencode($s) in php, still not working.
$db, $collection and $key are defiend in php, no problem there.
What am I missing?

Basically JSON.stringify(send) function is designed in such way that it will make your json into what you are getting.
JSON.stringify(value[, replacer[, space]])
You should use this function properly. read the docs to know more.
Its basically useful if you have input value as JS array or JS object
which can be converted to single string.
You are getting '{/"r/":/"pax/",/"c/":1 in only case if you are trying to stringify a json which already in string format.
these:
var s = ['1','2','3'];
and
var s = "['1','2','3']";
are totally different things.
If you are sending an array or json object you can even send it directly
using the code above.
for example :
send = {"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]};
ic(send);
function ic(s){
var ajaxUrl = 'im.php';
$.getJSON(ajaxUrl,
{da: s},
function(data) {
console.log (data);
});
}
make sure to handle array at php side properly.
Like if you want return json, do:
$s = $_GET["da"]; //this will be array.
var jsonObject = json_encode($s);
or you can stringify it there and then provide.
or else just send string and then use json_decode to make it json in php

Related

Laravel Error returns when it does json_decode

I get the data in json format with the help of javascript. The javascript code I wrote actually sends the data in the format I want as follows:
var log_lists = JSON.stringify(Object.assign({}, $scope.log_list));
when I checked it on the internet, I checked that the incoming data is in json format and it was verified by all
When I send the requests, it is received correctly by the controller and when I return, I see the data returned in the console as follows.
My controller code
$log_example = $request->all();
return $log_example;
return data
{
"0":["1","SALES","5,00","REMOVED"],
"1":["2","SALES","10,00","REMOVED"],
"2":["1","BUYER","2","DROPPED"]
}
I use the json_decode function to run it in the foreach loop and when I return the data again I get the error "server error"
return json_decode($log_example, true);
// returns with errors
I couldn't find where I made a mistake.
Thank you for your help and suggestions.
$request->all() return an array by default.
First encode and then decode as below
$log_example = $request->all();
$logs = json_encode($log_example);
$data = json_decode((string) $logs, true);
return $data;

JSON response at ajax request to JS variables

I am trying to upload files with dynamic names and get those dynamic names back.
In detail, I have 2 page form.php and upload.php. When upload button is pressed on form.php then request sent to upload.php, where 2 files (DLpath and PhotoIDPath) are uploaded to server with dynamically names e.g :
DLpath=documents/20161130232311i8hGn0HzJT276415832.png
And
PhotoIDPath=documents/20161130232311SSRqCyIbKKalock.png.
It is working fine. Then on upload.php, I am encoding those file names as JSON array i.e.
$response = array ('DLpath'=>$Dlpath ,'PhotoIDPath'=>$PhotoIDPath);
echo json_encode($response);
And firebug snapshot is :
I want to get DLpath in var jsDlpath and PhotoIDPath in var jsPhotoIDPath
And my code ( Not working) to get response is :
complete: function(response)
{
var jsDlpath=response.DLpath;
var jsPhotoIDPath=response.PhotoIDPath;
alert(jsDlpath+" - "+jsPhotoIDPath)
}
And alert show :
undefined - undefine
If you can help me to gwt those values in js variables, I will be very thankful to you.
Since you're encoding you response in server side you should parse it in the js side, you could use $.parsejson() :
success: function(response)
{
var response = $.parseJson(response);
//if $.parseJson dont work, use JSON.parse
var jsDlpath=response.DLpath;
var jsPhotoIDPath=response.PhotoIDPath;
alert(jsDlpath+" - "+jsPhotoIDPath)
}
NOTE : Use success/done callback instead of complete.
Hope this helps.
If running in pure javascript you will find that there are two response attributes: responseText and responseXML. You probably want:
var data = JSON.parse(response.responseText);
A complete example, using curl from https://gist.github.com/bitdivine/7ddd943387a4350336dd (but jquery will do fine as well) to get open issues on Github:
curl('https://api.github.com/repos/gchq/CyberChef/issues?state=open')
.then((res) => JSON.parse(res.responseText))
.then((data) => console.log(data))

Accessing and decoding JSON sent from JavaScript to PHP

So I have a form, I took the contents of its inputs, threw them into an array, had it made into a JSON and then sent it to PHP so it can in turn decode and enter it into a database. I know it'd be easier to just use a <form method="POST" action="phpfile.php"> but I can't have this redirecting to another page, especially since my PHP is not embedded into HTML, instead it handles things offsite. Otherwise it'd be simpler to just use $_POST["name"] to get what I need. Nonetheless, this page in particular is supposed to create the user, receive a server response, that the user has been entered into the database and then is given an alert with a button to be redirected to the main page.
So anyway here are the relevant sections of this whole process.
JavaScript:
window.onload = function findSubmitButton() {
var button = document.querySelector(".send_info").addEventListener("click", serverInteraction);
}
function serverInteraction() {
var xmlhttp;
var inputArray;
var finalArray = [];
var JSONArray;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Your browser is not compatible with XMLHTTP");
return false;
}
inputArray = document.querySelectorAll("input[type=text]");
for(var i = 0; i < inputArray.length; i++){
finalArray[i] = inputArray[i].value;
}
console.log(finalArray);
JSONArray = JSON.stringify({finalArray: finalArray});
console.log(JSONArray);
xmlhttp.open("POST","phpFiles/sendUserInfo.php", true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(JSONArray);
}
PHP:
<?php
$finalArray = json_decode($_POST['finalArray']);
var_dump($finalArray);
?>
That var_dump simply returns a null and using echo gives me nothing, except a warning that my array variable isn't initialized through XDebug. I'm not quite sure what I'm doing wrong here, I've been following this just like the tutorials tell you to do it, and isn't generating the array. I've also tried $_POST['JSONArray']without any luck in case that was how it was supposed to go. Also tried file_get_contents('php://input') which sends an empty string as well.
You can't get your data from $_POST if you put JSON in your post body.
see this question Receive JSON POST with PHP. php can't handle application/json properly.
For your var_dump is empty, try this
var_dump(file_get_contents('php://input'));
var_dump(json_decode(file_get_contents('php://input'), true));
you will see your data.
And if you send your data without change it to JSON, you will get wrong data.
eg: your finalArray is ['a','b','c'] and you send it directly.
var_dump(file_get_contents('php://input'));
you will see php got string a,b,c instead of ['a','b','c']
So if you want to use $_POST to receive data, you need to use application/x-www-form-urlencoded. you can use jquery to do it. see http://api.jquery.com/jquery.ajax/
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
it will serialize your js object into x-www-form-urlencoded and php will handle it properly.
use chrome's dev tools, switch to network and see the request payload and response would be helpful for you.
You are bypassing $_POST by sending the the data as "Content-type","application/json" .
The data will instead be set in the body of request and can be retrieved using file_get_contents("php://input")
For further discussion see file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?
Generally there is no need to send your data as json to php

Why does jsonp return "Unexpected Token :" when using $.ajax() when my json is properly formated?

I'm using the below code to grab json from a remote address and use it's information in my project as a javascript object.
$.ajax({
type: "POST",
dataType: "JSONP",
url: "http://www.edupal.co/deals/?email=wed#umbc.edu",
jsonCallback: 'parseResponse',
success: function( data ){
console.log($.parseJSON(data));
},
error: function( xhr, str, e ){
console.log( "There was an error with the request", str, e );
},
complete: function(){
console.log("The request has completed.... finally.");
}
});
The problem is that although the request is being made just fine (I can see it in my networks tab in dev tools), it is telling me in my javascript console that there is an "Unexpected Token : "
Here is the JSON that is returning:
{"0":"1","id":"1","1":"20% Off UMBC Hoodies","title":"20% Off UMBC Hoodies","2":"umbc","school":"umbc","3":"UMBC Bookstore","location":"UMBC Bookstore","4":"http:\/\/bookstore.umbc.edu\/StoreImages\/9-862269-1.jpg","picture":"http:\/\/bookstore.umbc.edu\/StoreImages\/9-862269-1.jpg","5":"Limit 1 per person. Must present EduPal app with deal to cashier to be awarded discount.","description":"Limit 1 per person. Must present EduPal app with deal to cashier to be awarded discount.","6":"http:\/\/www.globatum.com","link":"http:\/\/www.globatum.com","7":"7\/30\/2014,08:45","start":"7\/30\/2014,08:45","8":"7\/30\/2014,09:45","end":"7\/30\/2014,09:45","9":"active","status":"active","10":"0","clicks":"0","11":"2014-07-30 20:18:30","posted":"2014-07-30 20:18:30"}
So i'm confused at what the problem could be. Can anyone help? I put it all in jsfiddle if anyone wants to test it. http://jsfiddle.net/#&togetherjs=T0ztQQbitP
Here is the PHP that generates the JSON
<?php
include('../dbconnect.php');
header('Content-Type: application/json');
$email = $_GET['email'];
$email = substr($email, 0, strpos($email, ".edu"));
$email = strstr($email, '#');
$school = str_replace('#', '', $email);
$sql = "SELECT * FROM `ads` WHERE `school` = '$school' ORDER BY `posted` DESC";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count > 0){
$deals = array();
$deals = mysql_fetch_array($result);
echo json_encode($deals) ;
}
else{
echo 'No records';
}
?>
It is not properly formatted.
JSONP must be a JavaScript program consisting of a single function call (to a function specified in the query string (usually via a callback parameter) which passes one argument (usually an object or array literal).
Your quoted response consists of a JavaScript object literal. Since the property names are identifiers instead of strings, it isn't even JSON. Since you are missing , between key:value pairs, it isn't even valid JavaScript.
The actual response I get (it looks like you are copy/pasting from the Chrome visualisation of the JSON instead of the source code) when I hit that URL is JSON — but not JSONP. So you shouldn't tell jQuery to process it as JSONP.
Since the URL doesn't appear to give permission via CORS, there doesn't appear to be any way to hit it directly with client side JavaScript unless you are hosting your HTML on www.edual.co so you'll need to use some server side code to relay the data to your JS.
JSON requires double-quotes around keys and commas for all but the last item.
...
clicks: "0"
...
should be...
...
"clicks": "0",
...
Note: even integer "keys" need to have double-quotes. So 0: "..." should be "0":"..."
Check out JSONLint in the future to double-check your JSON.
Also, JSON is not JSONP (source). You specify dataType: "JSONP", but you may just want dataType: "json". If so, as Barmar mentioned, you don't need to call $.parseJSON at all since data will already be a JSON object.

PHP returning empty POST array

JavaScript jQuery post:
var animals = {
animalsArray: [],
tripId: <?php echo $_GET['id']; ?>
};
$('.student-check').each(function() {
animals.animalsArray.push($(this).attr('id'));
});
var sendMe = JSON.stringify(animals);
$.post("saveChanges.php", sendMe, function(response) {
console.log(response);
}, "json");
PHP handler:
echo json_encode(print_r($_POST, true));
// Array
// (
// )
Why is the array empty? I'm posting data but the response returns an empty array.
You are encoding the data as JSON, which isn't a format PHP handles natively for form submissions.
Remove var sendMe = JSON.stringify(animals); and pass animals to $.post instead of sendMe. jQuery will encode it using one of the standard formats supported by HTML forms and PHP.
Alternatively see this question for how to get the raw request body.
Also:
echo json_encode(print_r($_POST, true));
json_encode and print_r are both functions that take a data structure and express it as a string. Use one or the other, not both.

Categories

Resources