Currently, the searchform hit, the form get submitted. Then it will fetch data from specified URL which is search/ajax2.php and return data here.
All I want to add is, to include another URL beside the above mentioned one, so that two actions can be performed at the same time.
Now, in the search/ajax2.php it runs a select query. Whereas in additional page that I want to include, which could be writedb.php it inserts data taken from this jason into database. It doesn't have to return anything back to ajax page though!
How to achieve this?
$("#searchform").on("submit", function () {
//$(this).find(':submit').attr('disabled','disabled');
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "search/ajax2.php",
data: data,
success: function (data) {
}
});
Try adding your second url in sucess function like this :
$.ajax({
type: 'POST',
url: 'some_url1',
data: 'some data',
success: function(data){
$.ajax ({
type: 'POST',
url: 'some_url2',
data: 'some data',
success: function(data){}
});
}
});
Related
I have this method:
var chineseCurrency = getChinese();
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
});
}
That is what printed when console.log(chineseCurrency);:
I am not able to make chineseCurrency equal to "price", so it would be "6.80071377". How can I do that? Tried chineseCurrency.responseText, nope, chineseCurrency['responseText'], nope. Tried to JSON.parse(chineseCurrency), nope. Nothing works!
Sorry if repeated, couldn't find any answer at Stackoverflow.
How do I return the response from an asynchronous call?
Data that is received as response to asynchronous ajax call cannot be returned from the function that calls $.ajax. What you are returning is XMLHttpRequest object (see http://api.jquery.com/jquery.ajax/) that is far from the desired data.
var chineseCurrency = null;
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny",
success: function(data) {
alert("success1: chineseCurrency=" + chineseCurrency);
chineseCurrency = data.ticker.price;
alert("success2: chineseCurrency=" + chineseCurrency);
// do what you need with chineseCurrency
}
});
}
You are not taking the data from that is returned from the Ajax call. instead you are just returning the ajax object.
Change your code to :
$.ajax(
{
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
data :{},
error : function(data)
{
console.log('error occured when trying to find the from city');
},
success : function(data)
{
console.log(data); //This is what you should return from the function.
}
});
I have an ajax function call that has a variable sum with value as 5. But when I try to access this variable outside the ajax function call, am getting null value.
Is there any way to access the value outside the ajax function?
$.ajax({
type: "POST",
url: "Service.asmx/chart",
data: appid,
success: function(data) {
var mydata = 5;
}
});
alert(mydata);
Try this:
$.ajax({
type: "POST",
url: "Service.asmx/chart",
data: appid,
success: function(data) {
doGetMyData(data);
}
});
function doGetMyData(data){
alert(data);
}
The first "A" in AJAX means Asynchronous, so your code runs the alert before the request completes. To achieve the goals you want, you may try to make your request synchronous adding the async:false option to your query:
$.ajax({
type: "POST",
url: "Service.asmx/chart",
data: appid,
async:false,
success: function(data) {
doGetMyData(data);
}
});
function doGetMyData(data){
alert(data);
}
The bad news is synchronous request locks your browser until it's finish, it's a good pratice to avoid this.
I am using Ajax to add contents on my database. And here's the code:
function addToFavorites(){
var recipe_id = $("#recipe_id").val();
var url = connect_url+'addFavorite.php?user_id='+user_id+'&recipe_id='+recipe_id;
$.ajax({
type: 'POST',
data: [{
user_id: user_id,
recipe_id: recipe_id
}],
url: url,
async: true,
jsonpCallback: 'userCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
alert("HELLO!!!");
},
error: function (e) {
alert("ERROR!");
}
});
}
The Ajax call was successful and I was able to add records on the database but I'm just wondering why is it not displaying the alert message if the calling was successful? Is there something wrong with my code? Or is there something wrong with my understanding? Thanks!
you must give a response with some info to the ajax or it won't know the response succeeded
I think it goes a little something like this:
In my view:
from django.core import serializers
And later....
data = serializers.serialize('json', MODEL.objects.filter(id=id), fields=('points'))
return HttpResponse(data)
In my jQuery:
$.ajaxSetup({
dataType: "json"
});
$('#selector .selector_detail a').click(function() {
var call_to = $(this).attr('href');
$.ajax({
url: call_to,
type: "POST",
complete: function() {
console.log('Ajax Complete')
},
success: function(data) {
points = data(fields.points)
console.log('Ajax Successful')
console.log(data);
},
error: function(xhr) {
console.log('Whoops, something went wrong. XHR Response:' + JSON.stringify(xhr));
},
});
return false;
});
I want the value of points, but I have no idea how to get it out. I can see it in the console.log when I look at the data Objects. What am I missing?
if data is a json object and the correct headers are set, you can access it's properties using a dot:
data.points
data[0].points //if points is an array
//this is not correct
data(fields.points);
I don't know what's the exact structure of 'data' but you can derive it from your console.log(data);
EDIt - if data has the structure you outlined in the comment you can access points like this:
alert(data[0].fields.points);
add dataType: 'json' to your .ajax call.
$.ajax({
url: call_to,
dataType: 'json',
type: "POST",
then its jut data.points in your success function, or perhaps data.field.points. I can't tell from your post.
This works fine:
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
This returns 400 Bad Request (Just a reformulation of the above jQuery using .ajax to support error handling).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
I think you just need to add 2 more options (contentType and dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
===============
and for post
$.ajax({
type: 'post',
must be met with
app.post('/', function(req, res) {
I was getting the 400 Bad Request error, even after setting:
contentType: "application/json",
dataType: "json"
The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.
This was my initial code:
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
Now after making the request, I checked the console tab in the browser development tool.
It looked like this:
responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.
Changing the data object creation like below fixed the issue for me:
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
I assume other possible errors could also be identified by logging and inspecting the error object.
Your AJAX call is not completed with the following two params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType is the type of data you're sending
dataType is what you're expecting back from the server
In addition try to use JSON.stringify() method. It is used to turn a javascript object into json string.