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.
Related
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);
I've built a php API that provides data in json output, I need to get the values via a get request to then plot as a graph on the page.
The front end web component in hosted on the same server as in the api in this basic structure:
index.php
graph.php
/api/
/api/src
/api/src/api.php
My current code in graph.php is as follows:
<script>
var myJson;
$.getJson('api/src/api.php/poll/results/current/13/', function(jd){
myJson = jd.AnswerCount.1;
});
document.getElementById('jsonhere').innerHTML = myJson; //just to test
</script>
The endpoint outputs data like the following:
{"AnswerCount":{"1":5,"3":1,"2":2,"4":1,"5":5,"6":3,"7":2}}
Which I need loaded into a key-value pair array,
1:5
3:1
2:2
4:1
...
to then be put into the graphing library.
How do I fix my code/write new code to do this? I'm pretty stuck here.
EDIT:
On a hunch I logged all the get requests via wireshark, and no request is ever sent to the url in question. Even with an empty function { } ? http://grab.kfouwels.com/pmgW
You can't use a number as an identifier, to access the 1 property you have to say [1] not .1
You have to use the variable containing your data, not x which hasn't been mentioned until you try to assign it somewhere
The A in Ajax stands for Asynchronous. You have to work with your data inside your callback since the function you pass to getJson won't be called until the HTTP response arrived but the line starting document.get will run as soon as the HTTP request has been sent.
I am sending an AJAX request to server and retrieving a response as a json object from the server with javascript code to my android application. I know the key values of the json object(ID, name, status, etc.) but I do not know how to get their values.(100, Mark, success, etc.) I need those data for processing for some other task. Can someone please tell me how to extract data from that json object. When I use alert(http.responseText); as follows I get the json object displayed. I need to get the values out of it.
method used to receive response
http.onreadystatechange = function() { //Handler function for call back on state change.
if(http.readyState == 4) {
alert(http.responseText);
json object I receive
{"header": {"ID":100,"name:"Mark"},"body":{"status":"success"}}
You have to convert The string to an object by doing var response=JSON.parse(http.responseText);
Just treat it like any object - console.log(response['name'])
You need to convert it to a JavaScript object using JSON.parse:
var obj = JSON.parse(http.responseText);
Since some legacy browsers do not have native JSON support you should include json2.js to shim it for those browsers.
you will have to eval the http.responseText to get the json object...
but using eval is not recommended, so you can use the json2 library to parse the text into json object..
or else you can even use the library like jquery and use function parseJSON to get it converted to json object
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.
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.