Converting an ajax object into a string - javascript

I have an ajaxed in element that I'm trying to convert into a string that can be stored into a variable. After I put it into the variable, the variable does not console.log; it says it's an object. How do I get it to print out the content of the variable?
Here's the code I'm using:
$.get('/Default.aspx?PageID=15018909&A=WebApp&CCID=21437&Page=1&Items=500', function(data){
$('#ajaxResults').html(data).find("ul").remove();
var ajaxResult = $('#ajaxResults').html($('#myArray').text());
console.log(ajaxResult);
});
I also need to run a replace() on that ajax result, but I can't because the object isn't a string.

You are taking the data back from $.get() and sending it to an element, then reading the element in. data already contains the information you need, see $.get
Why wouldn't you just retrieve the unparsed text data from the jqXHR parameter to the success callback?
$.get('/Default.aspx?PageID=15018909&A=WebApp&CCID=21437&Page=1&Items=500', function(data,status,jqXHR){
console.log(jqXHR.responseText);
});
Or conversely, just look at the data itself?
$.get('/Default.aspx?PageID=15018909&A=WebApp&CCID=21437&Page=1&Items=500', function(data,status,jqXHR){
console.log(data);
});
If you know the data is already an object
JSON.stringify(data)

Related

Cannot Access responseJSON object

I have the following code and I want to access the json of the outside of the initial call.
var crimes = $.getJSON('url');
console.log(crimes);
the console logs an object with a "responseJSON" element, but I can't access it. The code:
console.log(crimes[responseJSON]);
returns an error saying respponseJSON is undefined. I need to cycle through this large dataset in another for look so I only want to call it once rather than every time in the loop that comes after. How do I access the responseJSON object?
$.getJSON returns a jqXHR object, and while it may have a responseJSON property, you cannot access it this way (or at that moment). You have to "wait" until the browser performed the Ajax request. You do this by passing a callback to $.getJSON, which gets called when the response is available.
From the jQuery documentation (adapted):
$.getJSON( "ajax/test.json", function( data ) {
// access data here
});
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.
It seems you are not familiar with Ajax, so you should definitely read the jQuery tutorial about Ajax.
See also: How do I return the response from an asynchronous call?

How do I get the id I need from this JSON response from within a JS file

I have made an AJAX call from my JS file and I got a response like this (there are many more properties returned, but to simplify I am showing the JSON in this question like this:
{"release":"{\"avatar_url\": null, \"created\": \"2015-11-16T16:42:16+00:00\", \"guest_access_url\": null, \"id\": 2168982}","data":"Success"}
What I need is the value of the "id" field above response object
I tried response.release.id, response.release["id"] etc , didn't work.
Your response.release is another json so it needs to be parsed to object otherwise you cannot evaluate it.
Hoping your success callback is like below will work.
success = function(response) {
// If response is an object then access else parse it to object
var id = JSON.parse(response.release).id;
}
I guess if the json you paste is what you got, probably you have received it as string and not like a JSON object.
So there are 2 solutions for that:
var response = '{"release":"{\"avatar_url\": null, \"created\": \"2015-11-16T16:42:16+00:00\", \"guest_access_url\": null, \"id\": 2168982}","data":"Success"}' //This is the response data you get from ajax call
response = JSON.parse(response);
Now the variable response has the json object of the string the ajax call returned. So to access to the value you need you could do as you say response.release.id

Passing array through ajax

I'm fairly new to the jQuery execute on the same page stuff. So far I have been passing only single values trough ajax which is working fine. Now, I need to pass an array which is created by checkboxes through ajax.
My form html, dynamically created by php:
<input type=checkbox class=box name=box[] value=".$row['DoosID']." />
My jQuery:
var BackorderDate = $("#BackorderDate").val();
var Box = $(".box").val();
if( (TerugleverDatum == "") ){
$("#backorderresult").html(" * Some Error .").fadeIn("Slow").fadeOut(3000);
} else {
$("#backorderresult").fadeOut();
$.ajax({
type :'POST',
url :'./backorder.php',
data : box : Box,
backorderdate: BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
}
My PHP:
$boxlist = json_encode($box);
foreach($boxlist as $boxvalue){
// Do something with every value
}
this gives me a javascript error on submit saying box is not defined.
change this:
data : box : Box, backorderdate: BackorderDate, // invalid way of sending
to this:
data : {box : Box, backorderdate: BackorderDate}, // valid way
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs.
More Info
Why don't you try enclosing all the data values in a open and close curly braze( { and } ) .
Else it will conflict with the syntax of $.ajax method.
I think it is causing the problem.
You are sending data value in wrongly manner -
The data property should always be a JavaScript object. It's properties are serialized into a regular query string (for GET requests), or a normal post body parameter string (for POST requests). This serialized string is then sent to the server, along with the AJAX request.
On the server you can read the properties of the data object as if they were sent as simple request parameters, via either GET or POST. Just like if the properties had been fields in a form.
Try this :
$.ajax({
type :'POST',
url :'./backorder.php',
data : 'box='+Box+'&backorderdate='+BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
For more information see jQuery Ajax
You might want to refer to the php file like this: url :'../backorder.php' (double dots). At least, that's how I do it always.

How can I iterate this json?

"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there

Turning post request data into .each() function

I'm using this code
$.post("assets/scripts/chat/load_convos.php",{}, function(data) {
$.each(data, function(index, value) {
alert(value);
});
,and the return of the data is [57,49] but it just doesn't do anything... If I replace the data just after the $.each( with [57,49] it works but not with the data in its place.
I'm not the best with Javascript so all help is much appreciated.
What do you mean with "the data is [57,49]" ?
My guess is, that you expect a (JSON)-object but you just receive a string. My second guess is that jQuery interpretates the result the wrong way and does not identify the return as JSON-String and hence, does not implicit JSON.parse it.
Check the content-types of the request. Try to call data = JSON.parse(data); manually before calling the each loop. Actually jQuery should be able to identiy that string as a JSON result itself, so I'm also wondering which jQuery version you use.
Another shot you might have is to call .getJSON() instead of .post() directly.
You can use JSON.parse or eval('('+response+')'); but probably the solution is to specify to jQuery or the library you are using that the response is JSON.
By the way, no all browsers have the JSON object, so if your library don't provide it you'll have to use the eval solution.
Specify json as your datatype.
Taken from jquery.post documentation
Example: Posts to the test.php page and gets contents which has been
returned in json format
(<;?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>).
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");

Categories

Resources