Handle JSON server response in javascript - javascript

I've seen many similar issues, but they didn't provide answer for my question.
My Server form JSON string and put it into response:
List<String> list = getSomeList();
JSONArray jsArray = new JSONArray(list);
System.out.println(jsArray);
response.setContentType("application/json");
response.getWriter().write(jsArray.toString());
But in my javascript handle function when I alert response, it alert ALL page!
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
alert(response); //alert all page!
var list = JSON.parse(response.toJSON()); //doesn't work!
}
}
Question: how could I separate only jsArray in javascript?
P.S. As I understand, my JSON.parse(response.toJSON()) doesn't work because response contain the whole page?

Disclaimer: I don't know java.
Server-side, the problem is probably that your response is not closed after writing your JSON Array, allowing other (html) text to be written. Try this:
response.setContentType("application/json");
response.getWriter().write(jsArray.toString());
response.getWriter().close();
Client-side, responseText is a string, and strings don't have a toJSON() function defined.
var list = JSON.parse(http.responseText);
should suffice.

Related

JSON.parse returns error when trying to save response text to access object fields.

I am new to Javascript and Ajax. I was trying to write some code wherein I parse the JSON response of a HTTP request and then access different elements within the response object. But I keep running into 2 different errors. I tried looking through various solutions on stack overflow, but i havent been able to get them to work. Any help would be greatly appreciated.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
document.getElementById("lola1").innerHTML = json;
initMap(json);
}
};
I want to pass in only the results array from the response object. However if I do this, The page display is " [object Object] "
When I try to do JSON.parse within the initMap method, then i get a syntax error on JSON.parse
SyntaxError: JSON Parse error: Unexpected identifier "undefined"
if (this.readyState == 4 && this.status == 200) {
var json = this.responseText;
initMap(json);
}
function initMap(response_val) {
// Process input results
document.getElementById("lola1").innerHTML = JSON.parse(response_val)
...
Thanks.
The problem is you're trying to set the innerHTML to an object. innerHTML can only be a string, therefore it tries to coerce your object into a string. If you really want to display the entire responseText, you could simply document.getElementById("lola1").innerHTML = this.responseText;
I made an example fiddle to further show what setting the innerHTML of an object vs the stringified representation of the object looks like:
https://jsfiddle.net/tuqd9x8k/
You can try and log the information using
console.log(this.responseText);
console.log(json.parse(this.responseText));
You will see the difference and between the two and better visualize your response data.
I managed to fix the issue in my code. #jas7457 was right, setting innerHTML to an object caused issues. I wasn't sure how it looked. But i printed it to console.log.
The code now looks like
var response = JSON.parse(this.responseText);
// error checking
if (!response.results || !response.results.length) {
console.log("No results");
return;
}
// there should only be one object in the result array
var result = response.results[0];
console.log(result);
if (result.businesses) for (var i=0; i < result.businesses.length; i++) {
parse the nested son businesses object in the results..
}
And this works for me. Thank you too much for all the help! I really appreciate it!

How to user AJAX response using only HTML/JS

I am trying to use AJAX and Javascript (no jQuery) to update a DIV on my page to display an AJAX request based off of the user submitted response.
I have two questions.
1) How can I alter the AJAX request based off the user submitted response? I would also like to store the response for other AJAX requests on the same page as well. The below code does not seem to return anything to my browser and is not updating the DIV.
function loadXMLDoc(){
var xmlhttp = new XMLHttpRequest(),
userReq = documents.forms["form"]["req"].value;
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxRequest" + "userReq",true);
xmlhttp.send();
}
2) The AJAX request I'm using returns a JSON object. How do I use Javascript to modify and only display particular values of the returned JSON?
i.e The following JSON is returned from an AJAX call, only update the DIV to show Anna's last name, "Smith".
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
ad 1) userReq is a variable containing a value, if you use it as "userReq" you will get the literal string "userReq" rather than the value of the variable userReq
xmlhttp.open("GET","ajaxRequest?userReq=" + userReq,true);
This will allow your server side script to receive the value of userReq in the request variable named "userReq"
ad 2) JSON is the Javascript object notation, so using JSON in Javascript is quite easy
var myObject = JSON.parse(xmlhttp.responseText);
// get only Anna's last name
document.getElementById("myDiv").innerHTML = myObject.employees[1].lastName;

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

Can't display JSON on page

I have been trying to get my JSON code from a PHP file which is connected to my database to display on my website using an XMLHttpRequest, but we cant split them and display it.
We are using an php file example.php that does the following:
function jsonFromQuery($result) {
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result, MYSQL_ASSOC)) {
$json[] = $r;
}
} else {
$json = "Table is empty";
}
return json_encode($json);
}
This will display the json code as following on the website if you open the php file:
[{"UserID":"2","Firstname":"Piet","Lastname":"Klaas","Age":"23","Specialization":"Voet","Branch":"Been","Interests":"Hoofd","Hospital":"OLVG","Email":"pietklaas#gmail.com","ProfilePicture":""}]
With this we use the following javascript file to request this php file and stringify and try and display it.
var request = new XMLHttpRequest;
request.open('GET' , 'http://myurl.nl/example.php', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
var obj = JSON.stringify(request);
var firstname = obj.Firstname;
document.writeln(firstname);`
But I get a massive string which includes the type status etc. And don't know how to split this up to display on their own. For example only Firstname = Piet on the page.
When you get the data back from PHP it's already in the form of a string. You need to use JSON.parse() to convert it into an object you can use. Try...
var obj = JSON.parse(request.responseText);
var firstname = obj[0].Firstname;
document.writeln(firstname);`
Note as well that the Json you're getting back is a list of objects: [{...},{...},{...}], so you can't just call .Firstname as you haven't specified which object you care about. Hence the [0] in the example above to pick out the first object.
One other thought... At present if your PHP doesn't find any results it's going to send back something that isn't in the format you're expecting. Consider either wrapping the list in an object with a status...
{
"Success": true,
"Results": [{...}, {...}]
}
Or make the PHP script return a different HTTP code to indicate failure (404 seems appropriate here)
For future reference, JSON.stringify does the opposite - it takes a complex object and converts it into Json
You are parsing the whole XMLHttpRequest object
var obj = JSON.parse(request);
try using just the response body
var obj = JSON.parse(request.responseText);

How to handle jSON XMLHttpRequest response?

I'm trying to control the json response I send back to the client but didnt know exactly how..
Here is a simple demo:
js code
xhr = new XMLHttpRequest();
xhr.open("POST", "page.aspx", true);
xhr.send();
// handle the response with xhr.responseText
.cs code
bool success = false;
string message = String.Empty;
// Create JSON Response
var jsonData = new
{
success = success,
message = message
};
Response.Write(jsonData);
The problem is that when I look on the xhr.responseText I see:
"{ success = False, message = }
<!DOCTYPE html PUBLIC ....
....
..
"
You want to do Response.Clear() and then Response.End() after writing the jsonData.
Then you'll need to handle the JSON response in javascript. I recommend Crockford's JSON library.
I also recommend using jQuery's $.ajax() function rather than hand-rolling your own XHR calls.
PS. Ajax calls would be better made to either ASHX resources or PageMethods/WebMethods declared on your ASPX page. Better still, abandon webforms and use ASP.NET MVC with JsonResults returned from your Controller.
PPS. If you do end up using WebMethods, this article is excellent.
You need to Response.Clear() to clear the response before Response.Write
Your cs code is not generating valid JSON (in addition to it displaying other things after the JSON data). All JSON descriptors must be double quoted, and so must any string values. Values are separated from their descriptors by colons. Example:
{"success": false, "message": "It didn't work"}.
Have a look at http://json.org/ for libraries to use with specific languages.

Categories

Resources