What I like is the best way to handle my .fail() & .done() when my ajax request returns with a assoc array that I parse.
This is my current code and my current problem is .fail(). always firing.
Note: I tested my something.php and its giving me the right response when it fail or when it succeeded this is the actual response to my something.php
Fail :
{
"ac":"failed"
}
Success :
{
"alias": "cd9d0e2e",
"sso": "http://somethin.com/home/site/cd9d0e2e?dm_sso=2!dsa654654sa56d FGfre4f645465fTIxYWE3NGZkMzk0NGM3NzIyMWFhNWQyMTgifQ",
"ru": "http://somethin.com/login/resetpwd?uuid=asd1as3d1as321d-4370-be5d-123a3s2d1a3sd13a2s",
"ac": "something#sample.com",
"fn": "Fish",
"ln": "Fillet"
}
$(document).ready(function(){
$('#btn-create').click(function(e){
e.preventDefault();
var cSite = createSite();
cSite.done(sendMail).fail(failOption).always(alwaysOption);
}
});
function createSite() {
var promise = $.Deferred();
$.ajax({
url: 'something.php',
method: 'POST',
data:"template_id="+template_id+"&original_url="+original_url+"&email="+email+"&first_name="+first_name+"&last_name="+last_name
}).then(function(data) {
var dataa = JSON.parse(data);
//debugger;
if(dataa.ac === 'failed') {
promise.reject(dataa);
} else {
promise.resolve(dataa);
}
});
return promise;
}
function sendMail(dataa) {
console.log(dataa);
}
You can return the promise form your createSite function.
var cSite = createSite(); and then use with .then, .done, .always or .fail etc.
$(document).ready(function() {
$('#btn-create').click(function(e) {
e.preventDefault();
var cSite = createSite();
cSite.done(function(resp) {
var dataa = JSON.parse(resp);
sendMail(dataa);
}).fail(failOption).always(alwaysOption);
});
});
function createSite() {
var promise = $.ajax({
url: 'something.php',
method: 'POST',
data: "template_id=" + template_id + "&original_url=" + original_url + "&email=" + email + "&first_name=" + first_name + "&last_name=" + last_name
})
return promise;
}
function sendMail(dataa) {
console.log(dataa);
}
Okay I figure it out now .. this is the code that works now.
$(document).ready(function(){
$('#btn-create').click(function(e){
//debugger;
e.preventDefault();
$(this).html('Creating Site');
var template_id = $("#template_id").val();
var original_url = $("#original_url").val();
var email = $("#email").val();
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$.ajax({
url: 'create-site-con.2.php',
method: 'POST',
data:"template_id="+template_id+"&original_url="+original_url+"&email="+email+"&first_name="+first_name+"&last_name="+last_name
}).done(function(resp) {
var dataa = JSON.parse(resp);
if (dataa.ac === "failed"){
failOption(dataa);
}
else{
sendMail(dataa);
}
});
});//click
});//doc ready
Related
I have this code fragment:
if(!encryption_state){
if(cKey=="" || cKey==null){
cKey=getKey(aid); //here we trying to obtain key
if(cKey!="" && cKey!=null && cKey!=undefined){
if(isJSON(jKey) && encryption_state){
var tjKey = JSON.parse(jKey);
tjKey[aid] = cKey;
jKey = JSON.stringify(tjKey);
}else{
jKey = json.stringify({aid: cKey});
}
encryption_state=true;
}
}
if(!encryption_state){
if(cKey=="" || cKey==null){
cKey=rndstr(32); //generate string
}
var arr = {};
if(isJSON(jKey)) arr = JSON.parse(jKey);
arr[aid] = cKey;
jKey = JSON.stringify(arr);
encryption_state = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But when i call getKey(kaid) function:
function getKey(kaid){
$.ajax({
method: "POST",
url: "/?mod=key&fnc=syncKey",
data: {
aid: kaid
},
done: function(data) {
var tret = (JSON.parse(data)['msg']);
return tret;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Browsers don't continue do function getKey(), they do next commands in parent function, i don't know why they ignore web server answer and don't let function return server response :(
in general, an ajax call is asynchronous. That means, a sequence like
var a = 0;
a = getAwithAjaxFromServer(...);
console.log(a);
will immediately print "0" while the ajax is still runnng.
Your entire logic with cleyand encryption_state has to be put into the done function:
if(!encryption_state){
if(cKey=="" || cKey==null){
cKey=getKey(aid);
}
}
and in your ajax:
function getKey(kaid){
$.ajax({
method: "POST",
url: "/?mod=key&fnc=syncKey",
data: {
aid: kaid
},
done: function(data) {
var tret = (JSON.parse(data)['msg']);
.... PUT ALL THE LOGIC HERE .....
}
});
}
You must understand asynchronous mechanism in javascript to continue calling ajax. There are a lot of resources and stackoverflow questions. For example: https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascript
So, you can convert the code so:
if(!encryption_state){
var serverKeyCallback = function(cKey) {
if(cKey!="" && cKey!=null && cKey!=undefined){
if(isJSON(jKey) && encryption_state){
var tjKey = JSON.parse(jKey);
tjKey[aid] = cKey;
jKey = JSON.stringify(tjKey);
}else{
jKey = json.stringify({aid: cKey});
}
encryption_state=true;
}
};
var localKeyCallback = function(cKey) {
if(!encryption_state){
if(cKey=="" || cKey==null){
cKey=rndstr(32); //generate string
}
var arr = {};
if(isJSON(jKey)) arr = JSON.parse(jKey);
arr[aid] = cKey;
jKey = JSON.stringify(arr);
encryption_state = true;
}
}
manageKey(cKey, aid, serverKeyCallback, localKeyCallback);
}
function manageKey(cKey, kaid, serverKeyCallback, localKeyCallback) {
if(cKey=="" || cKey==null) {
$.ajax({
method: "POST",
url: "/?mod=key&fnc=syncKey",
data: {
aid: kaid
},
done: function(data) {
var tret = (JSON.parse(data)['msg']);
serverKeyCallback(tret);
localKeyCallback(tret);
}
});
}
else {
localKeyCallback(cKey);
}
}
Defining two encapsulated pieces of code, one to execute after serverResponse, and the other to execute after the serverResponse or when you have the cKey locally stored. I haven't tested the code, but it must work as you expect.
I have 2 functions that fetch data via the jQuery AJAX method.
Both look identical save for the URL. Both requests are successful and show the data in console, but only one returns the data through the parent function.
saveLoc fetches data that says "OK", and the "OK" is returned if printed to console in the parent code.
getLoc fetches data that is a number, say "17". The number is printed to console from within the function, but in the parent code, the variable (savedLoc) simply returns undefined
Any advice? Am I missing something?
function saveLoc(story,chapter,loc) {
jQuery.ajax({
type: "GET",
url: "index.php?action=saveloc&story="+story+"&chapter="+chapter+"&loc="+loc,
data: "",
cache: false,
success: function (data2) {
console.log("Location saved: "+loc);
return data2;
}
});
}
function getLoc(story,chapter) {
jQuery.ajax({
type: "GET",
url: "index.php?action=getloc&story="+story+"&chapter="+chapter,
data: "",
cache: false,
success: function (data) {
console.log("Location retrieved: "+data);
return data;
}
});
}
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var story = $.urlParam('story');
var chapter = $.urlParam('chapter');
$(document).ready(function(){
var start = 1;
var savedLoc = getLoc(story,chapter);
console.log("savedLoc: "+savedLoc);
if(savedLoc > 0) {
var d = $(document).height(),
c = $(window).height();
var scrollPos = Math.floor((savedLoc / 100) * (d - c));
window.scrollTo(0, scrollPos);
}
setTimeout(function() {
$(window).on('scroll', function(){
console.log("scroll detected");
setTimeout(function() {
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / d) * 100;
saveLoc(story,chapter,scrollPercent);
},3000);
});
},6000)
});
The ajax getLoc is a asynchronous task, so your savedLoc = getLoc(); will not get the return value of it's success function.
For managin asynchronous tasks, like ajax, there are some solutions:
Original and Simple way: If you want to get the return value of ajax, you should use a global variable, and transfer a callback into the ajax function, like getLoc, then call the callback in success;
Promise, manage the asynchronous tasks with synchronous way, refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise;
manage the asynchronous tasks with synchronous way provided in ES6, refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator
async await, a replacement for generator, refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
and for more information, refer to the blog, https://blog.risingstack.com/asynchronous-javascript/
function saveLoc(story,chapter,loc) {
jQuery.ajax({
type: "GET",
url: "index.php?action=saveloc&story="+story+"&chapter="+chapter+"&loc="+loc,
data: "",
cache: false,
success: function (data2) {
console.log("Location saved: "+loc);
return data2;
}
});
}
function getLoc(story,chapter, callback) {
jQuery.ajax({
type: "GET",
url: "index.php?action=getloc&story="+story+"&chapter="+chapter,
data: "",
cache: false,
success: function (data) {
console.log("Location retrieved: "+data);
savedLoc = data;
callback && callback();
}
});
}
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var savedLoc;
var story = $.urlParam('story');
var chapter = $.urlParam('chapter');
$(document).ready(function(){
var start = 1;
getLoc(story,chapter, afterLocCallback);
function afterLocCallback() {
console.log("savedLoc: "+savedLoc);
if(savedLoc > 0) {
var d = $(document).height(),
c = $(window).height();
var scrollPos = Math.floor((savedLoc / 100) * (d - c));
window.scrollTo(0, scrollPos);
}
setTimeout(function() {
$(window).on('scroll', function(){
console.log("scroll detected");
setTimeout(function() {
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / d) * 100;
saveLoc(story,chapter,scrollPercent);
},3000);
});
},6000)
}
});
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
Firstly, getLoc is not returning anything. so put a return statement in there.
secondly, $.ajax returns jqXHR object. You can use then, done, fail methods on this object. If you are not familiar with these read about promise concepts.
Once your async call is successful do the rest of the operations inside the then method.
function saveLoc(story,chapter,loc) {
//return the ajax promise here
return jQuery.ajax({
type: "GET",
url: "index.php?action=saveloc&story="+story+"&chapter="+chapter+"&loc="+loc,
data: "",
cache: false,
success: function (data2) {
console.log("Location saved: "+loc);
return data2;
}
});
}
function getLoc(story,chapter) {
//return the ajax promise here
return jQuery.ajax({
type: "GET",
url: "index.php?action=getloc&story="+story+"&chapter="+chapter,
data: "",
cache: false,
success: function (data) {
console.log("Location retrieved: "+data);
return data;
}
});
}
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var story = $.urlParam('story');
var chapter = $.urlParam('chapter');
$(document).ready(function(){
var start = 1;
getLoc(story,chapter).then(function(data){
var savedLoc = data;
console.log("savedLoc: "+savedLoc);
if(savedLoc > 0) {
var d = $(document).height(),
c = $(window).height();
var scrollPos = Math.floor((savedLoc / 100) * (d - c));
window.scrollTo(0, scrollPos);
}
setTimeout(function() {
$(window).on('scroll', function(){
console.log("scroll detected");
setTimeout(function() {
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / d) * 100;
// I think you are not using the return value of this call. So not using any promise then here.
saveLoc(story,chapter,scrollPercent);
},3000);
});
},6000)
});
});
I make a call to a function that makes an ajax call like this:
send.startMonitoring({'fetchMethod': 'notificationInterval', 'lastmodif':0}).then(function(value){
console.debug(value);
});
But the error I'm getting is this:
Uncaught TypeError: Cannot read property 'then' of undefined in
jquery
As in above, I'm calling startMonitoring function which is on another page and passing an object for it to make ajax call to the server. That function returns value from server and I want to be able to do something with it. That's why I'm trying to use .then to process the value returned.
Since I'm getting the above error, how could I modify it so that
returned value can be processed? Also how and when I can use .then()?
var interface = (function(config) {
return {
transporter: function(options) {
return config.ajax(options);
},
startMonitoring: function(options) {
var PERIOD_NOT_VISIBLE = 60000;
var PERIOD_VISIBLE = 5000;
var timer = 0;
var timestring = 0;
(function callThis(timestamp) {
interface.transporter(options).then(function(value) {
if (value[1].notification[0].output == null) {
timestring = value[1].notification[0].lastmodif;
console.log(timestring);
return value;
}
}).catch(function(e) {
});
timer = setTimeout(function(){
callThis();
if (interface.isMonitoring() == 0 ) {
clearTimeout(timer);
}
}, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
})();
}
};
})(settings);
This is how ajax calls made:
ajax: function(opt) {
var defaultData = settings.getDefaultDataset();
var self = this;
var opt = $.extend({}, defaultData, opt);
var output = [];
return new Promise(function(resolve, reject) {
token = window.es.token;
opt[token] = "1";
jQuery.ajax({
method: "POST",
url: self.system.path+"/index.php",
"data": opt,
error: function() {
reject('error');
},
success: function(result) {
output.push(opt, result);
resolve(output);
}
});
});
}
Change startMonitoring to accept and call a callback parameter
startMonitoring: function(options, callback) {
var PERIOD_NOT_VISIBLE = 60000;
var PERIOD_VISIBLE = 5000;
var timer = 0;
var timestring = 0;
(function callThis(timestamp) {
interface.transporter(options).then(function(value) {
callback(value);
}).catch(function(e) {
});
timer = setTimeout(callThis, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
})();
},
Tidy up ajax to remove the Promise constructor anti-pattern, and to use .then of the promise returned by jQuery.ajax
ajax: function(opt) {
var defaultData = settings.getDefaultDataset();
var opt = $.extend({}, defaultData, opt);
var output = [];
var token = window.es.token;
opt[token] = "1";
return jQuery.ajax({
method: "POST",
url: this.system.path + "/index.php",
"data": opt,
})
.then(function(result) {
output.push(opt, result);
return output;
});
}
Change how you call startMonitoring to pass in a callback function
send.startMonitoring({'fetchMethod': 'notificationInterval', 'lastmodif':0}, function callback(value){
console.debug(value);
});
In jQuery, you can use the $.Deferred() function. For example :
function startMonitoring() {
var deferred = $.Deferred();
jQuery.ajax({
url: your_url,
type: 'GET',
success: function (data) {
deferred.resolve(data);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise();
}
Then, you can call your function :
startMonitoring().done(function (data) {
//Went well
}).fail(function (error) {
//Error
});
This is what the code below does:
Goes to a table in a database and retrieves some search criteria I will send to Google API (the PHP file is getSearchSon.php)
After having the results, I want to loop around it, call the Google API (searchCriteriasFuc) and store the results in an array
The last part of the code is doing an update to two different tables with the results returned from Google API (updateSearchDb.php)
In my code, I am using setTimeout in a few occasions which I don't like. Instead of using setTimeout, I would like to properly use callback functions in a more efficient way (This might be the cause of my problem) What is the best way of me doing that?
$(document).ready(function() {
$.ajax({
url: 'getSearchSon.php',
type: 'POST',
async: true,
dataType: 'Text',
/*data: { }, */
error: function(a, b, c) { alert(a+b+c); }
}).done(function(data) {
if(data != "connection")
{
var dataSent = data.split("|");
var search_criterias = JSON.parse(dataSent[0]);
var date_length = dataSent[1];
var divison_factor = dataSent[2];
var length = search_criterias.length;
var arrXhr = [];
var totalResultsArr = [];
var helperFunc = function(arrayIndex)
{
return function()
{
var totalResults = 0;
if (arrXhr[arrayIndex].readyState === 4 && arrXhr[arrayIndex].status == 200)
{
totalResults = JSON.parse(arrXhr[arrayIndex].responseText).queries.nextPage[0].totalResults;
totalResultsArr.push(totalResults);
}
}
}
var searchCriteriasFuc = function getTotalResults(searchParam, callback)
{
var searchParamLength = searchParam.length;
var url = "";
for(var i=0;i<searchParamLength;i++)
{
url = "https://www.googleapis.com/customsearch/v1?q=" + searchParam[i] + "&cx=005894674626506192190:j1zrf-as6vg&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM&dateRestrict=" + date_length;
arrXhr[i] = new XMLHttpRequest();
arrXhr[i].open("GET", url, true);
arrXhr[i].send();
arrXhr[i].onreadystatechange = helperFunc(i);
}
setTimeout(function()
{
if (typeof callback == "function") callback.apply(totalResultsArr);
}, 4000);
return searchParam;
}
function callbackFunction()
{
var results_arr = this.sort();
var countResultsArr = JSON.stringify(results_arr);
$.ajax({
url: 'updateSearchDb.php',
type: 'POST',
async: true,
dataType: 'Text',
data: { 'countResultsArr': countResultsArr },
error: function(a, b, c) { alert(a+b+c); }
}).done(function(data) {
var resultsDiv = document.getElementById("search");
if(data == "NORECORD") resultsDiv.innerHTML = 'Updated failed. There was a problem with the database';
else resultsDiv.innerHTML = 'Update was successful';
}); //end second ajax call
}
//llamando funcion principal
var arrSearchCriterias = searchCriteriasFuc(search_criterias, callbackFunction);
}
else
{
alert("Problem with MySQL connection.");
}
}); // end ajax
});
How you did it in 2015
Callbacks are things of the past. Nowadays you represent result values of asynchronous tasks with Promises. Here is some untested code:
$(document).ready(function() {
$.ajax({
url: 'getSearchSon.php',
type: 'POST',
async: true,
dataType: 'text'
/*data: { }, */
}).then(function(data) {
if (data == 'connection') {
alert("Problem with MySQL connection.");
} else {
var dataSent = data.split("|");
var search_criterias = JSON.parse(dataSent[0]);
var date_length = dataSent[1];
var divison_factor = dataSent[2];
return Promise.all(search_criterias.map(function(criteria) {
return $.ajax({
url: "https://www.googleapis.com/customsearch/v1"
+ "?q=" + criteria
+ "&cx=005894674626506192190:j1zrf-as6vg"
+ "&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM"
+ "&dateRestrict=" + date_length,
type: 'GET'
});
})).then(function(totalResultsArr) {
totalResultsArr.sort();
var countResultsArr = JSON.stringify(totalResultsArr);
return $.ajax({
url: 'updateSearchDb.php',
type: 'POST',
async: true,
dataType: 'text',
data: { 'countResultsArr': countResultsArr },
error: function(a, b, c) { alert(a+b+c); }
});
}).then(function(data) {
var resultsDiv = document.getElementById("search");
if(data == "NORECORD") {
resultsDiv.innerHTML = 'Updated failed. There was a problem with the database';
} else {
resultsDiv.innerHTML = 'Update was successful';
}
});
}
}).then(null, function() {
alert('Some unexpected error occured: ' + e);
});
});
This is how you do it in 2016 (ES7)
You can just use async/await.
$(document).ready(async() => {
try {
var data = await $.ajax({
url: 'getSearchSon.php',
type: 'POST',
async: true,
dataType: 'text'
/*data: { }, */
});
if (data == 'connection') {
alert("Problem with MySQL connection.");
} else {
var dataSent = data.split("|");
var search_criterias = JSON.parse(dataSent[0]);
var date_length = dataSent[1];
var divison_factor = dataSent[2];
var totalResultsArr = await Promise.all(
search_criterias.map(criteria => $.ajax({
url: "https://www.googleapis.com/customsearch/v1"
+ "?q=" + criteria
+ "&cx=005894674626506192190:j1zrf-as6vg"
+ "&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM"
+ "&dateRestrict=" + date_length,
type: 'GET'
}))
);
totalResultsArr.sort();
var countResultsArr = JSON.stringify(totalResultsArr);
var data2 = await $.ajax({
url: 'updateSearchDb.php',
type: 'POST',
async: true,
dataType: 'text',
data: { 'countResultsArr': countResultsArr },
error: function(a, b, c) { alert(a+b+c); }
});
if(data2 == "NORECORD") {
resultsDiv.innerHTML = 'Updated failed. There was a problem with the database';
} else {
resultsDiv.innerHTML = 'Update was successful';
}
}
} catch(e) {
alert('Some unexpected error occured: ' + e);
}
});
UPDATE 2016
Unfortunately the async/await proposal didn't make it to the ES7 specification ultimately, so it is still non-standard.
You could reformat your getTotalResults function in the following matter, it would then search rather sequential, but it should also do the trick in returning your results with an extra callback.
'use strict';
function getTotalResults(searchParam, callback) {
var url = "https://www.googleapis.com/customsearch/v1?q={param}&cx=005894674626506192190:j1zrf-as6vg&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM&dateRestrict=" + (new Date()).getTime(),
i = 0,
len = searchParam.length,
results = [],
req, nextRequest = function() {
console.log('received results for "' + searchParam[i] + '"');
if (++i < len) {
completeRequest(url.replace('{param}', searchParam[i]), results, nextRequest);
} else {
callback(results);
}
};
completeRequest(url.replace('{param}', searchParam[0]), results, nextRequest);
}
function completeRequest(url, resultArr, completedCallback) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = function() {
if (this.readyState === 4 && this.status == 200) {
var totalResults = JSON.parse(this.responseText).queries.nextPage[0].totalResults;
resultArr.push(totalResults);
completedCallback();
}
};
req.send();
}
getTotalResults(['ford', 'volkswagen', 'citroen', 'renault', 'chrysler', 'dacia'], function(searchResults) {
console.log(searchResults.length + ' results found!', searchResults);
});
However, since you already use JQuery in your code, you could also construct all the requests, and then use the JQuery.when functionality, as explained in this question
Wait until all jQuery Ajax requests are done?
To get the callback execute after google calls are finished you could change:
var requestCounter = 0;
var helperFunc = function(arrayIndex)
{
return function()
{
if (arrXhr[arrayIndex].readyState === 4 && arrXhr[arrayIndex].status == 200)
{
requestCounter++;
totalResults = JSON.parse(arrXhr[arrayIndex].responseText).queries.nextPage[0].totalResults;
totalResultsArr.push(totalResults);
if (requestCounter === search_criterias.length) {
callbackFunction.apply(totalResultsArr);
}
}
}
}
then remove the setTimeout on searchCreteriaFuc.
Consider using promises and Promise.all to get all much cleaner :D
Hello everybody. I have a problem with my code. I use the jquery framework. When I want to call $.ajax(requestOptions), function xmlParser(xml) don't working.
I try to find a resolve this problem, but I can't nothing find.
$(document).ready(function () {
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser //Calling function
};
function xmlParser(xml) {
$("#load").fadeOut();
$(xml).find("Valute").each(function() {
$("#outputListValutes").append(
"<option value=" + $(this).find("CharCode").text() + ">" + $(this).find("CharCode").text() + "</option>");
});
};
$.ajax(requestOptions);
$("#clear").click(function() {
var sumValue = document.getElementById("sum").value = "";
var resValue = document.getElementById("result").value = "";
});
$("#convert").click(function(xml) {
//var selectCurrency = $("#inputListCurrency").val();
//findData(xml);
}(requestOptions));
function findData(xml) {
var decimalOnly = /^\s*-?[1-9]\d*(\.\d{1,2})?\s*$/;
try{
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if(value == "") throw new Error("Empty value");
else if(!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if(value < 0) throw new Error("Value isn't to be below zero");
else if(isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function() {
if(shortName == $(this).find("CharCode").text()) {
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch(e) {
alert(e);
}
}
});
change the success parameter of the request to use the xmlParser function (forgot () ):
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser(data) //Calling function
};
I found the solution this promlem. I am happy.
var courseFilePath = "xml/Course_Currency_02-07-2014.xml";
var listCurrency = [];
function insertOptions(){
for (var i = 0; i < listCurrency.length; ++i){
$("#outputListCurrency").append(
"<option value=" + listCurrency[i] + ">" + listCurrency[i] + "</option>");
}
}
function xmlParser(xml){
$("#load").fadeOut();
$(xml).find("Valute").each(function(){
var value = $(this).find("CharCode").text();
listCurrency.push(value);
});
listCurrency.sort();
};
function findData(xml){
var decimalOnly = /^\s*-?[0-9]\d*(\.\d{1,2})?\s*$/;
try {
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if (value == "") throw new Error("Empty value");
else if (!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if (value < 0) throw new Error("Value isn't to be below zero");
else if (isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function(){
if (shortName == $(this).find("CharCode").text()){
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch (e){
alert(e);
}
}
$(document).ready(function(){
$.ajax({
type: "GET", //The method of sending for data
url: courseFilePath, //It is reference on xml file
dataType: "xml", //The type of data
success: function(xml){
xmlParser(xml);
insertOptions();
}
});
//insertOptions();
$("#clear").click(function() {
document.getElementById("sum").value = "";
document.getElementById("result").value = "";
});
$("#convert").click(function() {
var selectCurrency = $("#inputListCurrency").val();
$.get(courseFilePath, findData, "xml");
});
});