Accessing details of ajax response JSON - ajax

I have a really stupid beginner jquery question, even if I saw a lot of similar question here:
From PHP with ajax I send this:
public function to_json() {
return json_encode(array( 'test_id' => 'test_value' ));
}
In the jquery file's success part I put:
function(data) {
alert(data);
}
And it shows this in the alert window:
{"test_id":"test_value"}
Which is fine, I guess, but if I change the function to this:
function(data) {
alert(data.test_id);
}
I got:
undefined
What am I missing?

What am I missing?
To set the Content-Type HTTP response header to application/json in your PHP script:
header('Content-Type: application/json');
Or to set the dataType parameter to json on the client:
$.ajax({
url: '/foo.php',
dataType: 'json',
success: function(data) {
alert(data.test_id);
}
});
The first is preferred because this way your server side script properly indicates to the client the content type it is using. And jQuery is intelligent enough to use this reponse header and automatically parse the response from the server before feeding it to the success callback.

You are missing to use the function parseJSON
reference:http://api.jquery.com/jQuery.parseJSON/
That function converts the json string into a javascript object

You need to parse it like this:
function(data) {
var obj = $.parseJSON(data);
alert(obj.test_id);
}

None of the answers posted so far worked for me.
This is what I had to do to get it working:
$.ajax({
url: '/foo.php',
success: function(data) {
var json = data.responseJSON;
alert(json.test_id);
}
});

Related

Using form data to dynamically construct url using ajax

I have the following ajax code that takes in 3 variables and passes them to a php file, and this is all fine and dandy. I want to do a redirect using the value stored in one of these variables. I figured I could just do window.location.href = within the success in the ajax call, but for some reason, it doesn't seem to respond to the click, and simply does nothing.
Here is the ajax function, hope y'all can help!
$("#findItem").click(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.ajax({
type: 'get',
url: 'http://plato.cs.virginia.edu/~aam3xd/cabbage/closestBuildingWeb.php',
data: {
foodItemId: $('#foodItem').val(),
sentLongitude: position.coords.longitude,
sentLatitude: position.coords.latitude
},
success: function(data){
//$('#answer').html(data);
//the following line doesn't seem to be executing....
window.location.href = foodItemId+"/"+sentLatitude+"/"+sentLongitude;
}
});
});
I think you should use your url into that window.location
window.location.href = "www.example.com/"+foodItemId+"/"+sentLatitude+"/"+sentLongitude;

DJANGO Jquery/ajax get 'httpresponse' JSON

I have been picking away at this, though thought I would reach out for some advice, if I may, I am fairly new to AJAX.
Right, I am using the django framework, I post the data to the server, which works great, then receive some data back on the callback function, which works, though I want this to be in JSON format so I can populate a table. Currently it either renders in plain text or the browser asks me to download the json data, meaning somethings not quite catching on the $.get part. My code is:
#views.py
if request.POST:
est_show = login_a.test()
return HttpResponse(est_show, content_type='application/json')
<!--JQUERY/AJAX-->
<script type="text/javascript">
$(document).on("submit","#these_choices",function (event) {
var data_form = $('#these_choices').serialize();
if(data_form) {
$.ajax({
type: "POST",
url: "{% url Create_this %}",
data: {'test':'test','csrfmiddlewaretoken': '{{ csrf_token }}'},
cache:false,
success: function(){
jQuery(document).ready(function ($) {
$.get('{% url Create_this %}', function(data) {
alert(data[0]);
});});
},
error: function(){
alert('error !!!!');
}
});}
else {
alert('error elsewhere');
}
event.defaultPrevented(); //not running PreventDefault returns json using defaultPrevented returns json and doesnt render anything when this is blanked out...
return false;
});
</script>
It also seems the alert(data[0]) is being ran before the json data is being received in the browser. Any advice will be appreciated?
Many thanks
Try setting the mimetype in the HttpResponse to application/json. When you don't specify a dataType in the ajax request, JQuery automatically tries to infer it based on the mimetype of the response.
return HttpResponse(est_show, mimetype='application/json')
Alternatively, you can set the dataType to json to tell JQuery to expect json.

406 Error when returning JSON object – Unexpected content

A few colleagues and I have a problem whereby the response from an ajax call returns some unexpected content. Rather than getting a simple JSON object back with various properties, the value of result.responseText is the HTML markup of a generic 406 status error page, saying the MIME type is not accepted by the browser.
The call is made like so:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('.promotion_banner .loader').hide();
$('.promotion_banner').html(result);
},
error: function (result) {
var obj = result.responseText;
if (obj.isRedirect) {
document.location = obj.redirectUrl;
}
else {
$('.promotion_banner .loader').hide();
$(".error-wrapper").removeClass("hidden");
var generic_error = document.getElementById('generic_error').value;
$(".error-wrapper p").html(generic_error);
}
},
beforeSend: function() {
$('.promotion_banner .loader').show();
}
});
The controller response to the call is like so:
Response.StatusCode = (int)HttpStatusCode.NotAcceptable; // 406
return Json(new { errorMessage = LocalErrorMessages.Website_Promotions_FreeFiver_General_Problem, isRedirect = false } );
We would expect result.responseText to contain key values for errorMessage and isRedirect, but they’re not there.
It’s worth pointing out that this code is multi-tenanted, shared by the current application and another one, where it works absolutely fine.
We’ve tried:
- Configuring IIS to show detailed error responses rather than a custom page for more detail – gives us nothing extra towards solving the problem.
- Allowing all response content types to the call
- Changing the culture of our site (which is currently es-ES)
- Various web.config tweaks
Has anyone ever had this problem?
Simplify your request. Maybe something like:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: 'GET',
data: {foo:'bar', one:'two'},
dataType: 'json',
success: function (result) {
console.dir(result);
},
error: function (xhr) {
console.dir(xhr)
}
});
And post the response from the server. This kind of error seems a request problem rather than server configuration issue

How use Facebook Javascript SDK response in Ajax request?

Supposing I have the following code which returns a Javascript object which I can read in Firebug's console:
FB.api('/me',function(apiresponse){
console.log(apiresponse);
});
How can I then use the data from apiresponse in an Ajax request on the same page?
Currently my Ajax request looks as follows:
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
I know very little about Javascript, but reading around the subject leads me to think I have to convert the Javascript object to a JSON string. Is that correct? Am I on the right track?
You could put your AJAX call inside the handler for the API call like below..
FB.api('/me', function(apiresponse){
console.log(apiresponse);
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
});
one possible way:
define a global variable in your javascript, e.g. var myVar1;
set apireponse to the global variable in your FB.api callback (i.e. where u call console.log)
reference the var myVar1 in your ajax fcn.

ajax problem with sencha touch

I am trying to submit a form using ajax in the sencha touch framework. It's a simple form that asks for a user's name, email address, and a brief message. I then want to post the data to a php script that simply emails the data to me.
The problem I have is when I try to submit the form I get the following error:
"SyntaxError: Unable to parse JSON string"
The code to send the request is as follows:
var userName = name.getValue();
var userEmail = email.getValue();
var userMessage = message.getValue();
Ext.Ajax.request({
url:'path/to/phpfile.php',
jsonData:{"name":userName, "email":userEmail, "message":userMessage},
method:"POST",
success:function(){
alert("Success!");
},
failure:function(){
alert("Error");
}
});
The error occurs in the sencha touch framework on line 14583, which is
Ext.util.JSON = {
encode: function(o){
return JSON.stringify(0);
},
decode: function(s){
return JSON.parse(s); //this is line 14583
}
};
I'm just starting to learn Ext and sencha touch so could someone please point in the right direction here? Any threads/tutorials/examples would be greatly appreciated.
Thanks in advance
Maybe your Server uses Content Negotioation. In this case it respects the Request-Header-Parameter Accept, which is Accept: */* in your case. So the Server sends your Script HTML or XML which can't be read as JSON.
Change your Code to the following:
Ext.Ajax.setDefaultHeaders({
'Accept': 'application/json'
});
Ext.Ajax.request({
url:'path/to/phpfile.php',
params:{"name":userName, "email":userEmail, "message":userMessage},
method:"POST",
success:function(){
alert("Success!");
},
failure:function(){
alert("Error");
}
});
Source: http://www.sencha.com/learn/legacy/Manual:RESTful_Web_Services
What happens if you change the Ajax Request to the following.
Ext.Ajax.request({
url: 'php/file.php',
method: 'post',
params: { id: idvar, data1: Ext.encode(schouw), data2: Ext.encode(opmerkingen) },
success: function(response) {
//Reponse
}
});
In my own application this, direct, encoding of the data to JSON works great.
Are you sure the var's you are sending are filled with data? Within my application I use the below code to substract data from the input values (slightly different);
formID.getValues().inputFieldID

Resources