JSON response at ajax request to JS variables - javascript

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))

Related

How to retrieve JSON data located in a different file

I have 6 json files in the same directory as my index.htm. Each json structure has saved game data in it. I want to let the user choose a file and load its associated json data structure. How can I go about retrieving that data?
I tried using
var myjson = new Object();
$.getJSON("myJSON.json", function(json) {
myjson = JSON.stringify(json);
console.log(myjson);
});
This gives me an XMLHttpRequest error (cross-origin request not supported).
Your execution is fine -- though like the comments on your post suggest, you need to change the protocol you're using. Really just load the HTML page using http://127.0.0.1/mypage.html instead of file://home/website/mypage.html and you can likely keep your javascript the same.
Aside from this, you might want to consider the data in your myJSON.json file. I noticed if the JSON data contains function definitions then it will cause $.ajax() or in this case $.getJSON() to throw a parse error.
So this will not work
{
"json" : function () {
alert("HI");
},
"hello" : 432
}
But this will work
{
"json" : "5",
"hello" : 432
}

Can I use AJAX 'POST' to post data to a JSON file on my server?

I just want the easiest/most simple way to get my data from an AJAX form using 'POST' the data the user entered on my server.
So if the user leaves their name in the input form on the page, then AJAX POST's the data to a JSON file on my server.
Is this possible? Is this the quickest way to get the data that is entered?
Thanks in advance!
*can someone tell me why this got downvoted? Am I violating any terms? I would just like to know in the future. Thanks. :/
Ajax file directly can not write to a file in your server. But you can achieve this by creating simple php script say savejson.php on your server.
Your form:
<form>
<input type="text" id="name" name="name">
<button type="submit" id="submit-btn">
</form>
<script>
$('#submit-btn').on('click', function(e) {
e.preventDefault();
if( $('#name').val() ){
$.ajax({
url : 'savejson.php',
method : 'post',
data : { 'name': $('#name').val() },
success : function( response ) {
alert( response );
}
});
}
});
</script>
Your savejson.php:
<?php
$fp = fopen('names.json', 'w');
fwrite($fp, json_encode($_POST['name']));
fclose($fp);
?>
Ajax is a term that more-or-less just means "Make an HTTP request from JavaScript".
You can use it to make a POST request. You can use it to make the body of that request a JSON text.
You can't POST to a file, only to a URL. You would need server side code that would be responsible for taking the data in the request and writing it to a file.
Yes. This is a rather common question and you'd do good to take a look at the following questions as well:
How can I use JQuery to post JSON data?
Jquery Ajax Posting json to webservice
Essentially, you use a client-side language (Javascript) to send a POST request to your backend. Naturally, you will then require a backend language (such as PHP or node.js).
I'll provide an example:
JS (jQuery):
$.post("http://yourURL.com/backend.php",{
data: {
"name" :"John Smith",
"vehicle":"TARDIS"
}
}).success(function(response){
console.log(response)
//do something with the response
});
PHP
<?php
$data = json_decode($_POST['data'], true);
$name = $data['name'];
$vehicle = $data['vehicle'];
echo "Welcome {$vehicle}-driving $name!";
?>
Your PHP especially should include error checking among other things, but this will suffice for a simple example.
In your console, upon executing the AJAX request you will then see the following:
Welcome TARDIS-driving Doctor!
Which is the output from your PHP file
Sorry to jump in late here.
var name = $('#name').val();
$.ajax({
url : 'somefile.php',
method : 'post',
data : { 'name': name },
success : function( response ) {
console.log( response );
}
});
This will do the trick.
You cannot write to any file using JavaScript alone. Just cookies or local (or session) storage.
AJAX POST sends data to server. The data is in JSON format. You understand this part already.
On server, there needs to be a API to consume this JSON and write it to a file, or better store it in a database.
More questions:
Can it directly write to a file? No
Can API write to the file? Yes, its technically possible but not advisable
How do others do it? They take JSON response and write it to a database in server side code.

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

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

Phonegap - Send array from mvc controller to Javascript using Ajax

I'm using phonegap and I'm trying to send an array encoded as json from a controller to view.
In my controller (server side):
$users = Model_Users::find(1);
$a=$users->to_array();
return json_encode($a);
In my view (into smartphone application using phonegap):
$(document).ready(function() {
$.ajax({
url: 'my/url...',
method: 'POST',
data: {
},
success: function(data) {
alert(data);
}
});
});
This working fine, infact in the view I get this alert:
data = {"name":"Jhon","surname":"Larry","age":"25"}
This work because the result of the query is only one row.
Instead when I try to get more than one query result, example:
$users = Model_Users::find('all');
$a=array();
foreach ($users as $user){
array_push($a,$user->to_array());
}
return json_encode($a);
In this case an empty response comes up, in fact I get this alert:
data = []
What is the problem?
Thanks in advance
I will try to build an answer with some tips based on what we already know thanks to the comments.
First of all now we are sure that the JSON is valid (jsonlint.com for example).
So,now, we are completely sure that the problem resides on the PHP / server-side.
My solutions:
Pay attention to not echo/return something before the value you need;
Change return with echo;
Add an exit; statement after the echoed value to be sure that no other characters will be included in the server answer;
Not exactly needed, but you can even think to set the header('Content-Type: application/json');
Debug looking at the console and using console.log instead of alert() (there are a lot of threads explaining the difference
Hope this will help!

AJAX responseXML

i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.

Categories

Resources