DJANGO Jquery/ajax get 'httpresponse' JSON - ajax

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.

Related

D3 - passing JSON data through AJAX call

I'm using Ajax to call data which is in JSON format from the server and when its successful want to pass it to D3.
$(document).ready(function() {
$.ajax({
url: "{% url 'charts_data' %}",
method: 'GET',
data : {
airline_category: 1,
year_category: 5
},
success: function(data){
console.log(data) // Correctly logs data to console
d3.json(data, function(dataSet){
console.log(dataSet) // Null with error 404
})
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
});
I understand I need to provide URL instead data to d3.json. But I want to use this Ajax called data object to build the chart. Ajax called data is in JSON format, how can I use it with D3?
Here is console.log of data:
console.log(data)
Don't bother with d3.json() if you already have the data from the ajax call. Just do everything in success that you would otherwise have done in the body of d3.json.

Return a a json object from an ajax call to a django view

Am trying to return a json object to render to a grid in my template.
This is how i do it.
views.py
def ajax_up(request):
history_data=Upload_history.objects.all()
history=serializers.serialize("json",history_data)
return HttpResponse( history, mimetype='application/json' )
html
$(".reply").click(function(){
$.ajax({
url: "/ajax_up/",
type: 'GET', //this is the default though, you don't actually need to always mention it
dataType: "json",
success: function(data) {
alert("awasome"+ data)
},
failure: function(data) {
alert('Got an error');
}
});
so i declare an object to hold the data as
var data = {{history|safe}};
where history is returned from the ajax call as in view above
but when i do alert(data), i get [object object],[object object].....
can any one help please?
Sounds like it's working, but alert just displays a string. Since your data is not a string, it'll show [object Object].
Either serialize the data with JSON.stringify or use console.log instead of alert to see the data in your browser javascript console.

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;

Accessing details of ajax response JSON

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);
}
});

Grails: Passing a javascript variable to a template

I am new to ajax so maybe this is obvious. I've tried many different not-working approaches. I have javascript that when you click on a button:
an ajax call that grabs some data from a controller - returns an object
display that data in a template that I will show on the page
Here is the javascript/ajax:
<script type="text/javascript">
$("#show").click(function () {
$.ajax({ url: '/Myproject/result/index',
type: "POST",
data: { id: id},
success: function(result) {
alert("Success:" + result); // Can see getting object back.
}});
$(".resulttable").show();
});
Here is the key line in grails view template:
<g:each in="${allResults}" status="i" var="result">
How do I get the data from the javascript to the gsp code (ie allResults)?
Do I have to "refresh" this template to display new data?
thanks.
You just can't make your javascript/jquery code populate things in the gsp, since the gsp is processed server-side and javascript is processed client-side, after the gsp rendered all html documents and populated them with your model. You need to be aware that your page was already processed, so things like ${variables} won't be reloaded anymore. So when you do this:
$(".resulttable").show();
It's not gonna show the result you're waiting for. You have to use javascript code to reload your result table.
So if you're using ajax here, you should use the function success to alter your html table via javascript/jquery since you already have the response you wanted. Maybe this read can help you. Oh, and I think it would be better if in your ajax call, you would define a dataType (json works great in your case), like this:
$("#show").click(function () {
$.ajax({ url: '/Myproject/result/index',
type: "POST",
data: { id: id},
dataType: 'json',
success: function(result) {
alert("Success:" + result); // Can see getting object back.
}});
$(".resulttable").show();
});
Just to make clear what kind of response you're getting from the controller.
You do not need to write your ajax calls the hard way. There are some Grails intern tags you can use inside your html:
http://grails.org/doc/latest/ref/Tags/remoteFunction.html
http://grails.org/doc/latest/ref/Tags/submitToRemote.html
http://grails.org/doc/latest/ref/Tags/remoteLink.html
Following the links you will find some nice examples...

Resources