I think I'm going mad.
I'm using json objects all over this project in exactly the way I am here, except this example isn't playing nice. Anyone able to see what's wrong with it?
The json object is:
{"theurl":"http://localhost:8888/sitename/success"}
My javascript is:
function startSuccess_stripe(responseText, statusText, xhr, $form){
console.log(responseText);
if(typeof responseText !== 'undefined'){
console.log(responseText);
if(responseText['stripe']){
alert('Your card has been declined. Please try again.');
}else{
console.log(responseText);
console.log('ELSE: '+responseText['theurl']);
// window.location = responseText['redirect'];
}
}
};
As you can see it's full of console logs. The output looks like this:
{"theurl":"http://localhost:8888/sitename/success"} main.min.js:2
{"theurl":"http://localhost:8888/sitename/success"} main.min.js:2
{"theurl":"http://localhost:8888/sitename/success"} main.min.js:2
ELSE: undefined
Why is the last one undefined?? This is how I'm referencing every other json object value in the code, and haven't had any issues, I'm baffled.
EDIT: #JasonP 's suggestion was it. The header wasn't set on this particular page, so it was being treated as HTML, not json. As I'm using codeigniter the specific code missing was $this->output->set_content_type('application/json'); as part of the controller. For others you can set the dataType as part of the ajax call.
Related
I am making an AJAX post request with response in JSON.
My ajax code is
$.ajax({
type: "POST",
url: "admin/vendors_post.php",
data: "vendet_req=fetch&venid="+sel_ven,
dataType: 'json',
beforeSend: function(){
$('#trans_loader').css("display", "table");
},
success: function(response){
console.log(response);
}
});
Consoling the object shows
When consoled object is explored
The problem is that, the object that I have received in response is not showing some object properties when explored. But when I try to call them explicitly using the dot notation, I get the proper value. I wasted my time looking for those few variables that were not shown when I console the whole response object. For reference, the properties 'id', 'com_name', 'cat_name', etc are not displayed when the console object is explored (refer attached image number 2 above).
What can be the issue? Why the object was not consoled with all properties? I am using jQuery 2.2.0. And using php 5.4.31 on the server side.
NOTE: The object size as per JavaScript is 24, while the actual size, sent from the server, is 29. Though I am able to access those 5 properties explicitly. I am sending data from php post file after 'json_encode()'ing.
Adding my comment here, so it's easier to find from the references:
If there's a data transformation between the console.log() and when you expand the items in the console, this can happen.
When the data is logged to the console, it's the state you are after, however if anything changes your data throughout the code, the entry in the browser's console will refer to the updated values.
Yes. #Alex is correct. #Yogesh try to avoid that function call and check the console.
This has nothing todo with jQuery or PHP, it's how Chrome works.
2 things to notice:
In Chrome when you use console.log on an object, it shows only the first 5 properties without sorting them. When you expand the object, it shows all the properties sorted alphabetically.
As #Alex Szabó said, if the object properties changed after using console.log(), the expanded object will display the current properties by the time of expanding.
Please try using
console.log(JSON.stringify(response))
I'm trying to do a getJSON call to a page within my domain that is simply a json array, which is not returning anything given the script in my webpage:
<script>
$('#genButton').click(function() {
console.log("click");
$.getJSON("http://mygithub.github.io/repository/quotedb.json", function(data){
console.log("executing");
var entry = data[Math.floor(Math.random()*data.length)];
console.log(entry);
$("#quoteDisplay").text(entry);
}).fail(function() {
console.log( "error" );
});
})
</script>
When the button is clicked, the console logs the "click", but never logs "executing", but also doesn't log any errors related to the getJSON. The debugger also never pauses within the getJSON function.
My question is, 1. Is it valid for quotedb.json to be literally a webpage with just a single json array? Or does the page need to be annotated in some way so that the getJSON request knows where to pick up the json from? 2. If (1) is fine, then are there any other reasons you can see why nothing from the getJSON return function would appear?
The json is again one array of json objects, in the form:
{
"character": ""
"quote": ""
}
EDITS
With the edited code, it now outputs "click" followed by "error" from the .fail() method of the $.getJSON call now.
I tried removing the ?callback? section of the url as suggested below, which did not work.
The /repository/ section of my url seems to be necessary to access the file.
Try without ?callback=? at end of url, see jQuery.getJSON()
JSONP
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead. See the
discussion of the jsonp data type in $.ajax() for more details.
There are some similar posts on SO about this topic but they are all dealing with search and I am trying to do something different. I have tried to apply some of the logic in answers to other questions here but w/o success. Essentially I just want users to be able to enter a status update ID into a text field, hit a button then display all meta data associated with that tweet. If I leave the callback=? part off of the URL string I get a response back but it's empty, which is obviously due to the security restrictions put in place by the Twitter API.
Here is what I am working with currently:
$.getJSON("http://www.twitter.com/statuses/show/73051651728084992.json?callback=?",
function(Data)
{
if(Data.length)
{
var Content = "";
$.each(Data, function(i, Row)
{
alert("We Have Data");
Content += Row;
});
$("#Result").append(Row);
}
else
alert("No Result for that ID!");
})
Which comes back w/ no data, yet the request does come back w/ a 200 HTTP response. Obviously I am missing something as far as the callback goes, I am just not sure what. Just as a crude proof of concept I was going to output all of the data to the Result div and pretty it up later. Obviously first things first I need to actually have some data to work with!
What am I missing?
Remove the ?callback=? from the url and try again. You are asking Twitter's api to wrap the response in a callback ? which would result in invalid JSON. Also, whenever in doubt, load the url manually in your browser to examine whether the response is correctly formatted.
Also, change to this, since $.getJSON() returns an Object, not a string:
if (Data) {
var Content = "";
..
}
I have the following snippet of code:
$('input#teamName').live('blur', function() {
var value = $(this).val();
if (value) {
$.getJSON('api/event_company/'+value, function(data) {
console.log('why does this not want to work?');
});
}
});
Basically all it's doing is requesting some data from the server when a form field changes. My problem is that nothing in the callback function every gets called even though I can see using firebug that it has successfully sent a request to the server and received a valid JSON response.
If I change the getJSON parameters to:
$.getJSON('api/event_company/'+value, alert('Blah'));
Then the alert pops up as expected. Any ideas what might be causing this behavior?
If the JSON is invalid, the parsing will fail and the handler won't be called. From getJSON docs:
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.
See if your JSON validates.
Your second example is not correct. It should instead be,
$.getJSON('api/event_company/'+value, function() {
alert('Blah');
});
I have a script for updating a database table. I need to return a JSON array and to update some tables with JQUERY.
my php script:
$update = mysql_query("UPDATE PLD_SEARCHES SET STATUS = 1, TOTAL_RESULTS = ".$scrapper->getTotalResults().",RESULTS = $resultCounter WHERE ID = ".$searchId);
$output = array("status"=>"COMPLETED","results"=>$resultCounter,"totalResults"=>$scrapper->getTotalResults());
echo json_encode($output);
jquery code:
$("button").live("click", function(event) {
event.preventDefault();
$.getJSON("startsearch.php", {
searchId: $(this).val()
}, function(data) {
alert(data[0].status);
});
now ...the problem is that if i use $.post("startsearch.php",{ searchId: $(this).val() }, function(data)) the script gets executed and i get a nice alert with value undefined. if i add the parameter "json" the script doesn't get executed anymore. I tried to use getJSON but again the same problem.
Anybody has any ideas? I am desperate...this has been bugging me for almost a week and I still haven't managed to solve it.
In your php file make sure to set the correct content type:
header("Content-type: application/json; charset=utf-8");
so that jquery can correctly eval the response into a json object.
You can get to your response data as follows:
alert(data.status);
alert(data.results);
alert(data.totalResults);
please don't use alert, install firebug into your firefox or enable the javascript console in chrome or safari. after that you can use console.log(data);
my guess is that data isn't an array. also have a look at the each() exmaple on the jquery docs http://docs.jquery.com/Ajax/jQuery.getJSON
Well, I'm trusting json2.js to parse the json data returned from AJAX request. You can download it from http://json.org. This library provide a better way to parse any string, and will throw an exception if the sting is not in json.
I always write my AJAX request like this:
$.post(URL,
{ PARAM },
function(data){
try {
var r = JSON.parse(data);
//this for your code above
alert (r.status); //should be 'COMPLETED'
}
catch (e) {
//data is not in json format, or there are another exception in try block
//do something about it
alert('Exception occured, please check the data!');
}
});
When processing json, the array in php will become a variable member in json. So if in your php it is $output['status'], then in json, it will be r.status.