jQuery : Calling a recursive function in AJAX succes - javascript

I have a problem :
function getArbre (recherche, div){
$.ajax({
//async : false,
type : "GET",
dataType: "json",
timeout : 2000,
url : "test.php?recherche=" + recherche,
success : function(donnees) {
if (donnees.Error) {
alert("Erreur");
} else {
console.log(donnees);
myjson = donnees;
}
},
complete : function(donnees) {
console.log("completed");
//JSONToTree(myjson);
},
error: function(donnees, status, err) {
console.log(status + " : " + err);
}
}).then(function(data){
JSONToTree(myjson);
});
And there is my function :
function JSONToTree(json){
console.log(json.id);
for (i = 0; i < json.Children.length; i++) {
JSONToTree(json.Children[i].id);
}
}
I have a problem, I can't read the content of my JSON, can someone help me ?

I think you are getting a JSON string and need to parse it. You can do this
function JSONToTree(json){
var jsonObj = JSON.parse(json);
console.log(jsonObj.id);
for (i = 0; i < jsonObj.Children.length; i++) {
JSONToTree(jsonObj.Children[i].id);
}
}

Related

Unexpected undefined return value from a function

I'm getting an unexpected undefined return value from a function.
function createselbox(arr) {
console.log('In createselbox');
var startstr = `Something`;
mytemp = '';
for (var i = 0; i < arr.length; i++) {
mytemp = mytemp + '<option>' + arr[i] + '</option>';
}
var ret = startstr + mytemp + `Something else `;
IsStaff = CheckifStaff();
console.log('Checkifstaff is ' + IsStaff);
if (IsStaff) {
console.log('Got true createselbox');
console.log('In sel loop');
ret = startstr + mytemp + `Something more`;
} else {
console.log('Got false createselbox');
}
return ret;
}
function CheckifStaff() {
var data = {
"isstaff": 'check'
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "html",
url: "/functions/checkifstaff",
data: data,
success: function (data) {
var recdata = data;
if (recdata.indexOf('Has add permissions') != -1) {
console.log('Returning true');
return 1;
} else {
console.log('Returning false');
return 0;
}
},
error: function (xhr, textStatus, errorThrown) {
console.log('An error occured in CheckifStaff');
return 0;
}
});
}
The console shows:
In createselbox
appointment.js ? dev = 96168005 : 292 Checkifstaff is undefined
appointment.js ? dev = 96168005 : 305 Got false createselbox
appointment.js ? dev = 96168005 : 158 Returning true
createselbox is called first. But the value from the function is being returned as false, apparently even before the function execution.
Why is this happening?
CheckifStaff() has no explicit return statement, so it returns what all functions return by default, which is undefined.
To make this work, CheckiStaff needs to return something, here, for example CheckiStaff will return a Promise which's value is either 1 or 0. createselbox will now await CheckiStaff and then use the value it returns afterwards
async function createselbox(arr) {
console.log('In createselbox');
var startstr = `Something`;
mytemp = '';
for (var i = 0; i < arr.length; i++) {
mytemp = mytemp + '<option>' + arr[i] + '</option>';
}
var ret = startstr + mytemp + `Something else `;
let IsStaff = await CheckiStaff();
console.log('Checkifstaff is ' + IsStaff);
if (IsStaff) {
console.log('Got true createselbox');
console.log('In sel loop');
ret = startstr + mytemp + `Something more`;
} else {
console.log('Got false createselbox');
}
return ret;
}
function CheckifStaff() {
var data = {
"isstaff": 'check'
};
data = $(this).serialize() + "&" + $.param(data);
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
dataType: "html",
url: "/functions/checkifstaff",
data: data,
success: function (data) {
var recdata = data;
if (recdata.indexOf('Has add permissions') != -1) {
console.log('Returning true');
resolve(1);
} else {
console.log('Returning false');
resolve(0);
}
},
error: function (xhr, textStatus, errorThrown) {
console.log('An error occured in CheckifStaff');
resolve(0);
}
});
});
}
you can also do change your ajax to be like this
$.ajax({
type: "POST",
dataType: "html",
url: "/functions/checkifstaff",
data: data,
success: function (data) {
var recdata = data;
if (recdata.indexOf('Has add permissions') != -1) {
console.log('Returning true');
return 1;
} else {
console.log('Returning false');
return 0;
}
},
error: function (xhr, textStatus, errorThrown) {
console.log('An error occured in CheckifStaff');
return 0;
}
}).then(function(data){
return data
});
i'm not an expert, but i think when you use ajax you should wait for the response - use promise, or async/await func

How to deal with asynchronous problems in javascript

I want to display data stored in ch ! But my problem is that ch is displayed before the data is stored !
I think this is an Asynchronous Problems! How can I solve this problem.
When I try to get length of ch, I get always 0. Even if I store data statically in ch, I get the length 0.
I think this is an Asynchronous Problems! How can I solve this problem.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
$.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml",
success: function(xml) {
var stock = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function()
{
dossier = $(this).attr('dossier');
stock.push(dossier);
});
});
var ch = [];
for (var i = 0; i < stock.length; i++) {
$.ajax({
url: "/mySecondWebServiceURL" + stock[i],
type: "GET",
dataType: "xml",
success: function(xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
ch.push({
"nom": nom,
"matcle": matcle,
"dossier": dossier
});
if ($('#population').val() != null && firstIter == false) {
}
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
The problem is that you are not waiting for the second service to respond.
It should be something like this:
const deferreds = stock.map((stockItem) => {
//... your logic with ch.push here
return $.ajax({
// your call to the second service
});
});
$.when(...deferreds).then(() => {
// your code
// for (var key in ch) {
});
The approach I'd rather take is to break the code down and use Promises. You really should take your time to learn Promises. It's a JavaScript standard and what jQuery uses under the hood.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
return $.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml"
});
}
function getStockArray(xml) {
var stocks = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function() {
{
dossier = $(this).attr('dossier');
stocks.push(dossier);
});
});
});
return stocks;
}
function getStocks(stocks) {
return Promise.all(stocks.map(fetchStock));
}
function fetchStock (stock) {
return $.ajax({
url: "/mySecondWebServiceURL" + stock,
type: "GET",
dataType: "xml"
})
.then(formatStockInfo)
}
function formatStockInfo (xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
if ($('#population').val() != null && firstIter == false) {
}
return {
"nom": nom,
"matcle": matcle,
"dossier": dossier
};
}
function updateSelectMenu (ch) {
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
}
RechercheFiltrée()
.then(getStockArray)
.then(getStocks)
.done(updateSelectMenu);

How to abort ajax request

In my below code if input search vale is empty and as well as search keyword is same means if entered 'abc' got the result again clicked need to abort the ajax request, I had written in beforesend method but browser throwing error "Cannot read property 'abort' of undefined"
Ajax code:
function makeRequest()
{
var searchText='';
var popupRequest = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
popupRequest.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
}
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
var xhr = null;
function makeRequest()
{
if( xhr != null ) {
xhr.abort();
xhr = null;
}
var searchText='';
xhr = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
xhr.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
Define a variable and give your ajax the same alias. Then, everytime the function is being made, you check if (in this example XHR) is null or not. If it is not, you abort() it and give it null value again.

POST variables to model is not working in php codeigniter by using return in success

I tried the following code:
function doAjax() {
var sList = "";
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? "1" : "0");
sList += (sList=="" ? sThisVal : "," + sThisVal);
});
$.ajax({
url: "UserRights/update_rights",
type: "POST",
data:{ X : sList},
success: function(data) {
// alert("Success:"+data);
return data;
}
});
};
In model:
function update_userright()
{
if(!empty($_POST['X']))
{
if(isset($_POST['X']))
{
$checkbox_list =$this->input->post('X');
echo "Posted".$checkbox_list;
}
}
else
{
echo "Nothing";
/* $active=$this->input->post('menulist');
echo "Posted values .$active";
$sql= $this->db->query("UPDATE UserRightsNew SET Active='$active' WHERE UserCode='$default_usercode'; "); */
}
}
When i tried with alert message the values are posted but the return(data) is not working ... anybody guide me?
I think you have error in JavaScript. Try this.
function doAjax() {
var sList = sThisVal = "";
$('input[type=checkbox]').each(function () {
sThisVal = (this.checked ? "1" : "0");
sList += (sList=="" ? sThisVal : "," + sThisVal);
});
var result = '';
$.ajax({
url: "UserRights/update_rights",
type: "POST",
data:{ X : sList},
dataType: "html",
success: function(data) {
alert("Success: "+data);
result = data;
}, error: function(e){
alert(e); //To show errors
}
});
return result;
}
MODEL
update_userright(); //make sure to execute the function
function update_userright()
{
if(!empty($_POST['X']))
{
if(isset($_POST['X']))
{
$checkbox_list =$this->input->post('X');
echo "Posted".$checkbox_list;
}
}
else
{
echo "Nothing";
/* $active=$this->input->post('menulist');
echo "Posted values .$active";
$sql= $this->db->query("UPDATE UserRightsNew SET Active='$active' WHERE UserCode='$default_usercode'; "); */
}
}

Function as a KnockoutJS observable

I have the following script (see below). I have two questions regarding it:
1.What does the following line mean in the context of Knockoutjs?
ko.observable(null);
2.How can I invoke a function not yet defined as in here:
that.activePollingXhr(...
Here is the full script:
$(document).ready(function() {
function ChatViewModel() {
var that = this;
that.userName = ko.observable('');
that.chatContent = ko.observable('');
that.message = ko.observable('');
that.messageIndex = ko.observable(0);
that.activePollingXhr = ko.observable(null);
var keepPolling = false;
that.joinChat = function() {
if (that.userName().trim() != '') {
keepPolling = true;
pollForMessages();
}
}
function pollForMessages() {
if (!keepPolling) {
return;
}
var form = $("#joinChatForm");
that.activePollingXhr($.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false,
success: function(messages) {
console.log(messages);
for (var i = 0; i < messages.length; i++) {
that.chatContent(that.chatContent() + messages[i] + "\n");
that.messageIndex(that.messageIndex() + 1);
}
},
error: function(xhr) {
if (xhr.statusText != "abort" && xhr.status != 503) {
resetUI();
console.error("Unable to retrieve chat messages. Chat ended.");
}
},
complete: pollForMessages
}));
$('#message').focus();
}
that.postMessage = function() {
if (that.message().trim() != '') {
var form = $("#postMessageForm");
$.ajax({url: form.attr("action"), type: "POST",
data: "message=[" + that.userName() + "] " + $("#postMessageForm input[name=message]").val(),
error: function(xhr) {
console.error("Error posting chat message: status=" + xhr.status + ", statusText=" + xhr.statusText);
}
});
that.message('');
}
}
that.leaveChat = function() {
that.activePollingXhr(null);
resetUI();
this.userName('');
}
function resetUI() {
keepPolling = false;
that.activePollingXhr(null);
that.message('');
that.messageIndex(0);
that.chatContent('');
}
}
//Activate knockout.js
ko.applyBindings(new ChatViewModel());
});
ko.observable(null); creates an observable with a value of null. Nothing different than ko.observable(5);, where the value would be 5.
I see that you're using the that.activePollingXhr observable by passing it the result of an ajax call. However, this call is asynchronous and $.ajax doesn't return the data it got from the server, but rather a jquery deferred. You need to use that.activePollingXhr insude the success callback. Here's is how your code might look like:
$.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false,
success: function(messages) {
console.log(messages);
for (var i = 0; i < messages.length; i++) {
that.chatContent(that.chatContent() + messages[i] + "\n");
that.messageIndex(that.messageIndex() + 1);
}
that.activePollingXhr(messages); // <-- Note where the call to activePollingXhr is
},
error: function(xhr) {
if (xhr.statusText != "abort" && xhr.status != 503) {
resetUI();
console.error("Unable to retrieve chat messages. Chat ended.");
}
},
complete: pollForMessages
});
As for the comment under your question: that.activePollingXhr is defined as that.activePollingXhr = ko.observable(null); - an observable with value of null.
That just initializes an observable with null as the initial value.
If you need to invoke a function that is an observable, just add a second set of parenthesis.
that.activePollingXhr()()

Categories

Resources