still not call with ajax in separate javascript file - javascript

I am new in jquery and ajax but my requirement is calling servlet/jsp through ajax using jquery so that my ajax code dosen't work in separate javascript file
Here is my javascript file that I called ajax through jquery :
function insertData(idvalue)
{
var forsplit = idvalue.id.split("_");
var qtsrl = forsplit[2];
var qtno = forsplit[3];
alert(qtsrl);
alert(qtno);
var queryid=idvalue.id;
var qtsrl_id = document.getElementById("qstn_srl_"+qtsrl+"_"+qtno).value;
var qstn_no_id = document.getElementById("qstn_no_"+qtsrl+"_"+qtno).value;
alert(qtsrl_id);
alert(qstn_no_id);
$.ajax(
{
url: "aftermarksave.jsp",
type: "get",
data:{setvalues : queryid},
dataType: "JSON",
success: function(data)
{
alert('Successful :'+data);
},
error: function(data)
{
alert('Not Successful: '+data);
}
});
}
Still not call to jsp page and I tried for Servlet page also that servlet is not called through ajax.

Try Like
$.ajax({
url: "URL",
type: "GET",
contentType: "application/json;charset=utf-8",
data: {setvalues : queryid},
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});
OR
$.get("URL",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});

Related

How to effectively chain 3 ajax calls where One ajax call feeds the other Two ajax calls?

I am trying to find the effective way of chaining 3 ajax calls where one ajax call feeds the other Two ajax calls.
Here is the scanario :
//Invoke the ajax calls
firstAjax('mypage.gng','john-doe').then(secondAjax, thirdAjax).done(function(second_ajax_data, third_ajax-data) {
console.log(second_ajax_data);
console.log(third_ajax-data);
});
//Define our ajax calls
const firstAjax = function(urlAjax, userName) {
return $.ajax({
url: urlAjax,
type: 'POST',
data: userName
)};
const secondAjax = function(sessionId) {
return $.ajax({
url: '/userLogins/getUserLogins',
type: 'POST',
data: sessionId
)};
const thirdAjax = function(sessionId) {
return $.ajax({
url: '/userHistory/getUserHistory',
type: 'POST',
data: sessionId
)};
Basically, the firstAjax call retrieves the sessionId and then it feeds it to the other 2 ajax calls at the same time. With the implementation above i am not able to get the data returned by the last two calls.
I would appreciate any help
I think something like this might work:
function send_ajax_request(data){
$.ajax({
url: "yoururl",
type: "GET",
dataType: "json",
data: {
data: data,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (json) {
next_ajax(json['success']);
},
error: function (xhr, errmsg, err) {
alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
}
function next_ajax(data){
$.ajax({
url: "yoururl",
type: "GET",
dataType: "json",
data: {
coord: JSON.stringify({ "info": data[0], "info2": data[1] }),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (json) {
console.log(json)
},
error: function (xhr, errmsg, err) {
alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
}
Basically, use your Ajax's sucess function to invoke the next Ajax request. Should work!

Calling a javascript function from a global file and return it to append to html

I have a global javascript file 'Global.js' with a Global Handler 'GlobalHandler.ashx',
what i am trying to do is to render some data in the back-end (inside the handler ), than return text data using context.Response.Write(MyString)
The question is how to append the data to my html element .
I looked into the response (200) and the data is there , but i don't know the reason of not appending my text into the html element
I have tried to append them like the classic way success:function(data){
$(elementID).html(data);}
But that doesnt work
Here In Global.js
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here In MyPage.aspx
$(document).ready(function () {
GetProfession("Profession");
});
HERE In the Handler
string functionName = context.Request["functionName"];
GroupDAO GroupDAO = new GroupDAO();
if (functionName.Equals("GetProfession"))
{
var ListOfGroups = GroupDAO.GetGroups();
string Builder = "";
foreach (var group in ListOfGroups)
{
Builder+="<option value='" + group.GroupID + "'>" + group.GroupName + "</option>";
}
context.Response.Write(Builder);
}
I am expecting to have those options appended to the html element 'Profession'
but this unfortunately it does not happening
I found the answer , i did not recognize the logical reason of such behaviour ,
but the data was not in the success method even if the statuc code was 200 .
in fact it was in the error: properties of ajax request .
what i have done is :
instead of appending the data in success to the html element .
i did it in the response text
.
Here is the code before not working :
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here is the one that works
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "text/html; charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data, fata, meta) {
},
error: function (err) {
$("#Profession").html(err.responseText);
//alert(err.responseText);
}
});
}

Can I call ajax function inside another ajax function? [duplicate]

Is it possible to make an ajax request inside another ajax request?
because I need some data from first ajax request to make the next ajax request.
First I'm using Google Maps API to get LAT & LNG, after that I use that LAT & LNG to request Instagram API (search based location).
Once again, is this possible, and if so how?
$('input#search').click(function(e) {
e.preventDefault();
var source = $('select[name=state] option:selected').text()+' '+$('select[name=city] option:selected').text()+' '+$('select[name=area] option:selected').text();
var source = source.replace(/ /g, '+');
if(working == false) {
working = true;
$(this).replaceWith('<span id="big_loading"></span>');
$.ajax({
type:'POST',
url:'/killtime_local/ajax/location/maps.json',
dataType:'json',
cache: false,
data:'via=ajax&address='+source,
success:function(results) {
// this is where i get the latlng
}
});
} else {
alert('please, be patient!');
}
});
Here is an example:
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page=' + btn_page,
success: function (data) {
var a = data; // This line shows error.
$.ajax({
type: "post",
url: "example.php",
data: 'page=' + a,
success: function (data) {
}
});
}
});
Call second ajax from 'complete'
Here is the example
var dt='';
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page='+btn_page,
success: function(data){
dt=data;
/*Do something*/
},
complete:function(){
$.ajax({
var a=dt; // This line shows error.
type: "post",
url: "example.php",
data: 'page='+a,
success: function(data){
/*do some thing in second function*/
},
});
}
});
This is just an example. You may like to customize it as per your requirement.
$.ajax({
url: 'ajax/test1.html',
success: function(data1) {
alert('Request 1 was performed.');
$.ajax({
type: 'POST',
url: url,
data: data1, //pass data1 to second request
success: successHandler, // handler if second request succeeds
dataType: dataType
});
}
});
For more details : see this
$.ajax({
url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data) {
if (data.web == 0) {
if (confirm('Data product upToWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 1},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
else {
if (confirm('Data product DownFromWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 0},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});

JSP AJAX return NULL

i using JQuery Ajax to call REST api in jsp but it return null no matter how i call but it can work in html. is there any way to solve this problem. Cant seem to find a solution in the net.
$(document).ready(function () {
alert('ready');
var accessKey = 'xkg8VRu6Ol+gMH+SUamkRIEB7fKzhwMvfMo/2U8UJcFhdvR4yN1GutmUIA3A6r3LDhot215OVVkZvNRzjl28TNUZgYFSswOi';
var thisUrl = 'http://www.onemap.sg/API/services.svc/getToken?accessKEY=' + accessKey;
$.ajax({
type: "GET",
url: thisUrl,
dataType: 'application/json',
success: function (data) {
alert('data is:' + data.GetToken[0].NewToken);
}
});
alert(thisUrl);
});
dataType should be jsonp
$(document).ready(function () {
var thisUrl = 'http://www.onemap.sg/API/services.svc/getToken?accessKEY=' + accessKey;
$.ajax({
type: "GET",
url: thisUrl,
dataType: 'jsonp',
success: function (data) {
console.log(data)
alert('data is:' + data.GetToken[0].NewToken);
}
});
});
Refer to this article:
http://www.isgoodstuff.com/2012/07/22/cross-domain-xml-using-jquery/
You only need "jquery.xdomainajax.js" that is there in the sample source-code to make it work.
$.ajax({
url: 'https://asdf/asdf',
dataType: "xml",
type: 'GET',
success: function(res) {
var myXML = res.responseText;
alert(myXML);
}
});

function calling ajax returns false

I have a javascript function which makes a JSON call to a web service using jQuery.
In the success function I need to evaluate the JSON response and if necessary make another call to a different method in the same web service.
Here is how I do it:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
end = endFunction(aid);
if (end) {
// do some other stuff
}
}
},
failure: function (errorMsg) { alert(errorMsg.toString()); }
});
}
and the endFunction which is being called from within the ajax success function:
function endFunction(aid) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return hasEnded;
}
Here is the weird stuff. The ajax-call is made all right. The code on the server is running according to plan. However, if I try to set a firebug breakpoint in the success function of endFunction(aid) is is not hit, but the alert box is shown displaying the word true. This is somewhat good since it seems that we are actually reaching the success function. The hasEnded variable however is never set to true so it always returns false.
Calling endFunction(1) from the Firebug console displays an alert box with the word true and returns value false.
What's going wrong?
AJAX is asynchronous — the $.ajax call will not wait for the server to reply.
Therefore, the return hasEnded; line runs before the AJAX callback.
You need to make your endFunction take a callback parameter, like $.ajax does.
http://api.jquery.com/jQuery.ajax/
It looks like you're using "failure" in the documentation you have "error":
error(XMLHttpRequest, textStatus, errorThrown)
also you should do something like this:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
endFunction(aid,function(endv){
if (endv) {
// do some other stuff
}
});
}
},
error: function (errorMsg) { alert(errorMsg.toString()); }
});
}
function endFunction(aid,endcallback) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
endcallback(hasEnded);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
endcallback("?");
}
});
//return hasEnded;
}

Categories

Resources