How to handle jSON XMLHttpRequest response? - javascript

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.

Related

Modify XHR request response object (Json format) using Javascript

I need some help trying to modify the response of an XHR request. My application is calling the api with the url:
https://xxxxxxxx.xxxxxxxx.com/api/bookings?locale=en
The api returns a objects in json format, where I need to replace this response with my own created json file (in the same object format)
I'm using Nightwatch, and have looked at this libery quite some time now.
Xhook
I have already created the JSON file with name "reservations.json".
Have looked at the xhook.after method which look like this:
browser.injectScript('//cdn.rawgit.com/jpillora/xhook/1.3.1/dist/xhook.min.js', function() {
xhook.after(function(request, response) {
if (request.url.match('api/bookings'))
response.text = "testtest";
});
})
Hope someone will help me on this one.

Why when sending data over AJAX, do you have to JSON.stringify() your objects?

JSON stands for javascript object notation (as I'm sure you're aware), so why, when sending json via ajax do you need to turn it into a string to send it? Is it simply a formatting thing, or what?
This may belong in another place, if so, let me know, I'll close it and move it.
Obviously, I'm not looking for opinions, I'd like to know the actual answer.
Just to make sure I'm clear, I understand what JSON.stringify() does, and its counterpart JSON.parse(). I just want to know, why using stringify is required.
Thanks!
when sending json via ajax do you need to turn it into a string to send it?
If it isn't a string, then it isn't JSON in the first place.
JSON is a text based data format. HTTP is a text based communications protocol.
JSON stands for javascript object notation
JSON is based on the syntax for JavaScript literals. A JavaScript object is not JSON.
AJAX is all about HTTP requests, which are basically "text" requests to a server. That's the main reason why you have to stringify your object: That way it's turned into text that can "travel" over HTTP.
When sending data to a web server, the data has to be a string.
That's why we are using JSON.stringify() function to convert data to string and send it via XHR request to the server.
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "submit.php";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
// Converting JSON data to string
var data = JSON.stringify({ "name": name.value, "email": email.value });
// Sending data with the request
xhr.send(data);

On jQuery.post, I get the message: The method GET is not allowed for the requested URL

I have the following problem:
I work on a Flask application, and I want to pass some data to the server via AJAX. I am pretty new on this AJAX thing, so I can't get something right.
On my client side, when the user clicks on an icon, I want to pass some data via jQuery.post stored in the variable message:
jQuery("#icon_ID").click(function() {
var message = {
'GRAPH_TYPE': graphType
};
var _sendOnSuccess = function () {
}
var jqxhr = jQuery.post('/graph', message, _sendOnSuccess, 'json');
});
On my server side, I have the following code:
#app.route('/graph', methods = ['POST'])
#login_required
def physical_graph():
ret_data = request.form['GRAPH_TYPE']
return ""
All I want to do for now is to access the GRAPH_TYPE on the server side. However, when I click on the icon, I get the error message:
Method Not Allowed
The method GET is not allowed for the requested URL.
I really don't understand why Python tells me that I am using the GET method, when in fact I am using the POST method.
Can please someone help me with this? What should I do to solve this problem? If there's some other method I can use, feel free to give me advice of any kind. Just bear in mind that besides jQuery, I don't want to use other JavaScript library.
Thank you in advance!
It's because you are passing an object as data like
var message = {
'GRAPH_TYPE': graphType
};
In this case jQuery attempts to URL encode the object and by default sends with the data type application/x-www-form-urlencoded; charset=UTF-8 ans sends a GET request. To overcome this problem make sure that you’re passing jQuery a string for the data parameter and to do this you can use JSON.stringify like
var message = JSON.stringify({ "GRAPH_TYPE": graphType });

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.

Send JS object to JSP page [duplicate]

This question already has answers here:
Call Servlet and invoke Java code from JavaScript along with parameters
(3 answers)
Closed 6 years ago.
I have a JS object in a JavaScript file. I have to pass this object to a JSP page. The page picks up this object and processes it. How can I do it?
The same way you get any other data from a web browser to an HTTP server.
Encode it in an HTTP request by submitting a form / setting the window location / using XMLHttpRequest / etc.
There are a couple of issues you need to resolve first, are you doing this in an AJAX style of request? is this a form submission? is there going to be on-going interaction within the page-session between the client/server passing JSON objects back-and-forth?
Lets tackle the simple case of a form submission, once you get that you should be able to get the remaining cases going as they are just "extensions" of this base case. Say you have some form that will submit the data in some field:
<form name='my_form' id='my_ford_id'>
<input type='hidden' name='my_input_field' />
</form>
then at some point in time you have a piece of code that executes and you have your JSON object
function myFunction() {
var json_data = getJsonData();
document.forms['my_form']['my_input_field'].value = json_data;
document.forms['my_form'].submit();
}
You will then on the JSP side receive this data as a JSON string inside of a form field, at which point you need to process it, lets assume you have some kind of a JSON library available to you, the code might look something like this:
<%
String myInputField = request.getParameter("my_input_field");
if(myInputField != null) {
try {
JSONObject myObject = new JSONObject(myInputField);
}
catch(JSONException e) {
}
}
%>
If you need an "AJAX" style of interaction, you will be making a number of such requests in the page, but fundamentally it falls back to the original problem of submitting the data. Since you are using forms in this example, and JSP, you don't have to worry at any point about encoding, the browser/server will take care of things for you.
When you send json object the servlet receive it in the same way of receiving data sent by submitting the form, for example, if you send a variable "action" with value="getCountries"
var option = {
"action": "getCountries"
};
$.getJSON('YourServlet', option, function() {
//hadle the result returned by servlet
});
The defualt method is GET, in the servlet you handle the request as you handle a normal request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action != null) {
if (action.equals("getCountries")) {
List coutries = getAllICountries(request); //get the countries
String json = new Gson().toJson(coutries);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(json);
return;
}
}
}
Notice how we return the result from servlet to javascript, we return a json object.
"JSON" Site helps you to manage Json Objects in JSp/java.
You have to convert the string obtained from javascript to a json object.Then manage it easily.

Categories

Resources