I have two very similar functions but only one works - javascript

Why does the first function work and not the second one? Both of the functions are within the same script statement. When I run the second function on my webpage it doesn't even get past the ajax statement but I am not sure what the actual problem is with it as I used the same template as the first function. Also please bear in mind I am very new to the Java API.
function summonerLookUp() {
SUMMONER_NAME = $("#userName").val();
if (SUMMONER_NAME !== "") {
$.ajax({
url: 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' + SUMMONER_NAME + '?api_key=RGAPI-F6099CCD-E674-478D-B9BF-2090B52A116C',
type: 'GET',
dataType: 'json',
data: {
},
success: function (json) {
SUMMONER_NAME_NOSPACES = SUMMONER_NAME.replace(" ", "");
SUMMONER_NAME_NOSPACES = SUMMONER_NAME_NOSPACES.toLowerCase().trim();
summonerLevel = json[SUMMONER_NAME_NOSPACES].summonerLevel;
summonerID = json[SUMMONER_NAME_NOSPACES].id;
document.getElementById("sLevel").innerHTML = summonerLevel;
document.getElementById("sID").innerHTML = summonerID;
sumName = json[SUMMONER_NAME_NOSPACES].name;
sumID = json[SUMMONER_NAME_NOSPACES].id
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error getting Summoner data!");
}
});
} else {}
}
function getMasteryData() {
SUMMONER_NAME = $("#userName").val();
sumID = string(sumID);
if (SUMMONER_NAME !== "") {
$.ajax({
url: 'https://euw.api.pvp.net/championmastery/location/EUW1/player/' + sumID + '/champions?api_key=RGAPI-F6099CCD-E674-478D-B9BF-2090B52A116C',
type: 'GET',
dataType: 'json',
data: {
},
success: function (json) {
bestchampid = json[0].championId;
document.getElementById("bcID").innerHTML = bestchampid;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error getting Summoner data for the ID!");
}
});
} else {}
}
Sorry for bad formatting but I hope you can understand it.

You should remove this line from the second function
sumID = string(sumID);
as there is no default function named string. Use String() instead.

Related

AJAX POST Request execute only first call on safari

$('#course_id').change(function() {
var courseid = $(this).val();
getuniqueid(courseid);
//alert(courseid);
});
function getuniqueid(courseid){
if (courseid == '0')
{
alert("Please select the Course.");
document.getElementById("course_id").value = "<?php echo $id ?>";
document.getElementById("course_id").focus();
return false;
}
$.ajax({
type: "POST",
url: 'createuniqueid.php',
data: {
courseid:courseid
},
datatype:'json',
cache: false,
success: function( data ) {
//alert(data);
$('#custom').val(data);
console.log("success");
}
});
}
function coupon_submit(elm){
var sender_name = document.getElementById("sender_name").value;
var sender_email_id = document.getElementById("sender_email_id").value;
var receiver_name = document.getElementById("receiver_name").value;
var receiver_email_id= document.getElementById("receiver_email_id").value;
var courseid = document.getElementById("course_id").value;
var uniqueid = document.getElementById("custom").value;
$.ajax({
type: "POST",
url: "datastring.php",
data: { sender_name: sender_name,
sender_email_id: sender_email_id,
receiver_name: receiver_name,
receiver_email_id:receiver_email_id,
courseid:courseid,
uniqueid:uniqueid
},
cache: false,
success: function( data ) {
alert(data);
console.log("success....");
},
error: function(jqXHR, textStatus, errorThrown,data) {
console.log("error. textStatus: %s errorThrown: %s", textStatus, errorThrown);
}
});
}
It works fine on chrome, IE, Firefox but not on Safari. On Safari it executes only first AJAX call.
I need to call first getuniqueid and then coupon_submit. But for debugging process I placed coupon_submit function's code in getuniqueid function, the code of datastring.php get executed. Means it executes first AJAX call only.
Appriciate any help in advance!!

Ajax Call not being accessed in most pages

This is a very weird problem but I will provide as much detail as possible. This Javascript function is in a separate .js file and referenced into various HTML pages in a Cordova application. When a push notification, with 2 parameters: id, type, is received into the device, a function called LaunchFromNotif is executed with these 2 parameters passed as arguments.
function LaunchFromNotif(id, type) {
try {
var ebyidurl = url + "ReturnEByID";
var nbyidurl = url + "ReturnNByID";
if (type != null) {
if (type == "n") {
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code here
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "e") {
$.ajax({
type: 'GET',
url: ebyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "a") {
combined(id);
}
}
} catch (exception) {
//window.location = "Warning2.html";
}
}
Combined(id) is another function with 2 Ajax calls. I used when and then, to make sure that the first ajax call completes before starting the second.
function combined(id) {
alert("combined");
$.when(
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
alert("success of first ajax");
},
error: function (xhr, status, error) {
alert('Error 1: ' + error);
}
})
).then(function () {
$.ajax({
type: 'GET',
url: Verifytempurl,
data: { Username: localStorage.getItem('user') },
success: function (data) {
alert("success of second ajax");
},
error: function (xhr, status, error) {
alert('Error 2: ' + error);
}
});
});
The problem is that this is working well in only one HTML page. In 3 other pages in which I tried, it shows the "combined" alert and seems to never access the Ajax call. The logic seems to make sense, especially since it is in working order in one page. What could normally go wrong in something of the sort? I am left with few debugging possibilities, especially since this is a Cordova app and being tested on mobile devices.
Thanks in advance!

Getting error trying to submit data using JQuery ajax

When I try to run the following JQuery ajax, I get an error saying that a parameter is missing and it will not send the data. I can't find any syntax errors. What am I doing wrong?
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: fd,
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
Why not use jQuery native form encoder?
$.ajax({
...
data: $('#illustrationTypeForm').serializeArray(),
...
});
Try This
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: $('#illustrationTypeForm').serializeArray(),
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
To make ajax request using jQuery a type 'POST' you can do this by following code :
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

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

jQuery $.ajax(), pass success data into separate function

I am using the jQuery $.ajax() function. I have put this into a parent function, which passes some values into the ajax function. What I would like to do, is have a user defined callback function, which gets the data param passed in from the ajax success function.
Here is what I was thinking would work, but it is not:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: callback
});
}
Then I want to be able to call that function, and pass in my custom function so that I can use the success functions data from inside that function:
testFunc('my string data', function(data){
alert(data);
});
I am wanting this to be the same as:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
}
Works fine for me:
<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
}
var test = function(str, cb) {
var data = 'Input values';
$.ajax({
type: 'post',
url: 'http://www.mydomain.com/ajaxscript',
data: data,
success: cb
});
}
test('Hello, world', callback);
</script>
You can use this keyword to access custom data, passed to $.ajax() function:
$.ajax({
// ... // --> put ajax configuration parameters here
yourCustomData: {param1: 'any value', time: '1h24'}, // put your custom key/value pair here
success: successHandler
});
function successHandler(data, textStatus, jqXHR) {
alert(this.yourCustomData.param1); // shows "any value"
console.log(this.yourCustomData.time);
}
this is how I do it
function run_ajax(obj) {
$.ajax({
type:"POST",
url: prefix,
data: obj.pdata,
dataType: 'json',
error: function(data) {
//do error stuff
},
success: function(data) {
if(obj.func){
obj.func(data);
}
}
});
}
alert_func(data){
//do what you want with data
}
var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);
In the first code block, you're never using the str parameter. Did you mean to say the following?
testFunc = function(str, callback) {
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: str,
success: callback
});
}
I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)
Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:
function GetProcedureById(procedureId)
{
var includeMaster = true;
pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pString,
datatype: "json",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
success: function(msg)
{
LoadProcedure(msg);
},
failure: function(msg)
{
// $("#sometextplace").text("Procedure did not load");
}
});
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
if (jdata.length < 10)
{
$("select#cptIcdProcedureSelect").attr('size', jdata.length);
}
else
{
$("select#cptIcdProcedureSelect").attr('size', '10');
};
var options = '';
for (var i = 0; i < jdata.length; i++)
{
options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
};
$("select#cptIcdProcedureSelect").html(options);
};

Categories

Resources