Ajax call inside an ajax success not working - javascript

I am trying to make an Ajax call inside another Ajax success function but it somehow doesn't work. I get the following error in my console. I don't understand what it means:
Object { readyState: 0, getResponseHeader: .ajax/v.getResponseHeader(), getAllResponseHeaders: .ajax/v.getAllResponseHeaders(), setRequestHeader: .ajax/v.setRequestHeader(), overrideMimeType: .ajax/v.overrideMimeType(), statusCode: .ajax/v.statusCode(), abort: .ajax/v.abort(), state: .Deferred/d.state(), always: .Deferred/d.always(), then: .Deferred/d.then(), 10 moreā€¦ }
I found something like below from the object
statusText:"SyntaxError: An invalid or illegal string was specified"
JS
//Update the board with the moves so far made
var updateBoard = function() {
var style;
$.ajax({
type: "POST",
url: "engine/main.php",
data: {code: 2},
success: function(response) {
if(response != "") {
var obj = JSON.parse(response);
lastClick = obj[obj.length - 1].player;
$(obj).each(function (i, val) {
if (val.player == 1) {
style = "cross";
}
else if (val.player == 2) {
style = "circle";
}
$('td[data-cell="' + val.cell + '"]').html(val.sign).addClass(style);
});
if(obj.length > 2) {
makeDecision();
}
}
else {
lastClick = null;
$('td').html("").removeClass();
}
setTimeout(updateBoard, 1000);
}
});
};
updateBoard();
function makeDecision() {
console.log('starting decision function');
$.ajax({
type: "engine/main.php",
data: {code: 3},
success: function(winner) {
console.log('end');
console.log(winner);
},
error: function(data) {
console.log(data);
}
});
}
PHP
if(isset($_POST['code'])) {
$code = $_POST['code'];
//Handle player number on game start
if($code == 1) {
if (!isset($_COOKIE['gamePlay'])) {
header('Location: index');
}
$playerCode = $_COOKIE['gamePlay'];
$player = $playersHandler->getPlayer($playerCode);
echo $player;
}
// Update board with new moves
else if($code == 2) {
$currentPosition = $gameHandler->getMoves();
echo $currentPosition;
}
else if($code == 3) {
$result = $code; //$gameHandler->decide();
echo $result;
}
//Reset Board
else if($code == 4) {
$gameHandler->reset();
}
}

You are passing an invalid string to type property inside the makeDecision function ajax call. You should set this as following:
type: 'POST',
url: 'engine/main.php',
...
instead of
type: 'engine/main.php'
Make sure that the following line
var obj = JSON.parse(response);
returns an array, not an object. If obj is not an array, then obj.length is undefined

You can not get length of object directly obj.length in javascript.So if you are getting response properly.Get length of Parsed object like this..
var length = Object.keys(obj).length;
Then
lastClick = obj[length-1].player;
Make correct use of $.each like this..
$.each(obj,function (i, val){
//code
});

You can call ajax again inside the ajaxComplate event like this:
$( document ).ajaxComplete(function() {
$.ajax({
type: "post",
url: 'engine/main.php',
data: {code: 3},
success: function(winner) {
console.log('end');
console.log(winner);
},
error: function(data) {
console.log(data);
}
});
});

Related

Javascript: $.ajax is null inside the for loop

I have an onclick function btn-book, and inside it is a for loop for the data of Ajax. I'm sure that data have values but i dont get it why i always get null. here is the code of the onclick.
$('#mapContainer').on('click', '.btn-book', function(e){
e.preventDefault();
var id = e.currentTarget.id;
var routeOrigin = route_Search.origin;
routeOrigin = routeOrigin.filter(function(e){return e});
var url = base_url;
for(var i = 1; i <= desNo; i++){
$.ajax({
type: "POST",
url: url,
data: {
id: id,
origin: $('#route-origin'+i).val(),
origin_contactperson: $('#origin-contactperson'+i).val(),
origin_company: $('#origin-company'+i).val(),
origin_phonenumber: $('#origin-phonenumber'+i).val(),
origin_notes: $('#origin-notes'+i).val(),
origin_Lng: routeOrigin[i-1].lng(),
origin_Lat: routeOrigin[i-1].lat(),
},
success: function(msg)
{
console.log(msg);
},
error: function()
{
alert("An error occured while updating. Try again in a while");
}
})
}
});
use like this.
$('#mapContainer').on('click', '.btn-book', function(e){
e.preventDefault();
var id = e.currentTarget.id;
var routeOrigin = route_Search.origin;
routeOrigin = routeOrigin.filter(function(e){return e});
var url = base_url;
var origin = [], origin_contactperson = []
for(var i = 1; i <= desNo; i++){
origin.push($('#route-origin'+i).val());
origin_contactperson.push($('#origin-contactperson'+i).val());
.....
}
$.ajax({
type: "POST",
url: url,
data: {
id: id,
origin: origin,
origin_contactperson: origin_contactperson,
origin_company: origin_company,
origin_phonenumber: origin_phonenumber,
origin_notes: origin_notes,
origin_Lng: origin_Lng,
origin_Lat: origin_Lat
},
success: function(msg)
{
console.log(msg);
},
error: function()
{
alert("An error occured while updating. Try again in a while");
}
})
});

Response string JavaScript undefined

I have a program written in angularjs. I'm receiving json data from server when online. I'm developing offline mode now..
I have the problem here but i dont know why i cant fix.
I saved json info to localStorage when program to offline get this json string.
service.js - For webservicecall
webServiceCallPost: function(data, action) {
console.log("data "+JSON.stringify(data));
console.log("action "+JSON.stringify(action));
var deferred = $q.defer();
if (navigator.connection.type != "none") {
return $.ajax({
type: "POST",
url: appConst.serviceUrl.service + action,
crossDomain: true,
dataType: "json",
data: data,
timeout: 2000000,
async: true,
success: function(response) {
localStorage.setItem(data + action, JSON.stringify(response));
deferred.resolve();
},
error: function(xhr, ajaxOptions, thrownError) {
$ionicLoading.hide();
if (xhr.status == 0) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else if (xhr.status == 404) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
}
},
beforeSend: function() {},
complete: function() {}
});
} else {
window.plugins.toast.showShortBottom($translate.instant("checkNetWorkConnection"));
$ionicLoading.hide();
var response1 = JSON.parse(JSON.stringify(localStorage.getItem(data + action)));
return $http.get('').then(function(response) {
return response1;
});
}
}
Controller.js - Retriveing response.
Services.webServiceCallPost('', appConst.services.get_menu_card).then(function(response) {
$ionicLoading.hide();
console.log("Response: " + JSON.stringify(response));
if (response[1].response.status == 1) {
if (response[0].data.menu.length > 0) {
var categoryResponse = [];
angular.forEach(response[0].data.menu, function(value, key) {
if (value.menu_image_name != '') {
var extraData = {
imageUrl: appConst.serviceUrl.menu_image_url + value.menu_image_name
}
}
else {
var extraData = {
imageUrl: 'img/screen.png'
};
}
angular.extend(value, extraData);
categoryResponse.push(value);
});
$rootScope.categories = globalMethods.getDashboardGridView(categoryResponse, 2);
}
if (response[0].data.addons.length > 0) {
$rootScope.totalAddons = [];
angular.forEach(response[0].data.addons, function(value, key) {
var extraData = {
"finalCost": value.price,
"quantity": 1,
imageUrl: appConst.serviceUrl.addon_image_url + value.addon_image
};
angular.extend(value, extraData);
$rootScope.totalAddons.push(value);
});
}
$scope.getSiteSettings();
}
$rootScope.dashboardHistoryId = $ionicHistory.currentHistoryId();
});
Console Output :
When i check from json pretty print its looking same.
Online Response : https://codepaste.net/op0boq
Cached Response : https://codepaste.net/y3bkd6
Problem:
TypeError: Cannot read property 'status' of undefined
When i want to get response1.response.status ok is getting.
But when i'm offline and i get cachedResponse1.response.status its retriving status is undefined. But exactly same data, why ?
if this code
var cachedResponse = JSON.parse(JSON.stringify(localStorage.getItem('' + appConst.services.get_menu_card)));
uses an asynchronous call
console.log("Cached Response: " + cachedResponse);
won't wait for it to finish and would print undefined
Thanks for answer to #PatrickEvans
Then you might have not returned the right thing... but also you shouldn't be doing JSON.parse(JSON.stringify(localStorage.getItem()) it should just be JSON.parse(localStorage.getItem()) localStorage items are already strings, stringifying it is going to mess up what you are trying to do
and
return $q.when(response1);

How to access multidimensional associative json arrays from AJAX jquery function

I have to return a return a multidimensional associative arrays from PHP page for a jQuery AJAX function.
This is my PHP page called 'seachsongs.php'
<?php
$brano = $_POST['brano'];
$sql = "SELECT Titolo, Autore FROM Brani WHERE Titolo = '$brano';";
$ris = $conn->query($sql);
while ($row = $ris->fetch_array()) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
?>
This is my jQuery AJAX function
$(document).ready(function () {
$('#nBrano').keyup(function () {
nomeBrano = $(this).val();
$.ajax({
type: "POST",
data: {brano: nomeBrano},
url: "searchsong.php",
success: function (data) {
document.write(data);
//alert("Prova" + data['data'][0]["Titolo"]);
/*if (msg != 'null') {
$('#similarSongs').css('display', 'block');
/*$.each(prova, function (key1, value1) {
$.each(value1['two']['three'], function (key1, value1) {
document.write('test');
});
})
$('#similarSongs table').html(tabella);
}
if (msg == 'null') {
$('#similarSongs table').html("Nessun brano simile trovato");
$('#similarSongs').css('display', 'block');
}*/
},
error: function () {
//alert('errore');
}
});
});
});
How can I access to array data from jQuery? What is the correct statement?
alert(data)
print this
{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}
PS: sorry form my bad english.
I've set the data type of this request to be json, so the response returned should be a json object. You can access it by this way:
$(document).ready(function () {
$('#nBrano').keyup(function () {
nomeBrano = $(this).val();
$.ajax({
type: "POST",
data: {brano: nomeBrano},
url: "searchsong.php",
dataType:'json',
success: function (response) {
for(var i=0; i<response['data'].length; i++){
console.log(response['data'][i][/*your_target_index*/]);
}
},
error: function () {
//alert('errore');
}
});
});
});
see more about ajax

How to repeat ajax request depending return

I have this code :
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
});
I want if data == 0 need to make another call on app_auction_end after 10 sec. Can you help me please ? Thx in advance and sorry for my english
Give the operation a named function:
var someFunction = function () {
$.ajax({
//...
});
};
Which you would then use for your .on() call:
.on('finish.countdown', someFunction)
And in the success handler, set a timeout for that function:
if (data == 0) {
setTimeout(someFunction, i_timer);
}
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
//do our initial call otherwise it will never get called.
onEndAuction();
});

function call another without waiting to finish

In my method feedContactCategorySelection, i would like to wait the assignContactCategoryToLocal call to be finished before continuing to run the rest of the code
feedContactCategorySelection();
function feedContactCategorySelection(){
assignContactCategoryToLocal();
var category = sessionStorage.getItem("category");
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
//....
}
}
function assignContactCategoryToLocal() {
var category = sessionStorage.getItem("category");
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
}
});
}
You can pass a callback function to the assignContactCategoryToLocal() that way you can continue running the code only when the ajax is done. Something like this:
feedContactCategorySelection();
function feedContactCategorySelection() {
// Do anything here before running the ajax
// For instance, get category and pass it to the assignContact...
var category = sessionStorage.getItem("category");
...
assignContactCategoryToLocal(category, myCallbackFunction);
}
function myCallbackFunction(category) {
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
}
function assignContactCategoryToLocal(category, callback) {
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
// Now that it is done and successful, run the rest...
callback(category);
}
});
}
}
For sake of example, you can get the category once and then pass it along the functions, maybe that helps understand how they are connected.
EDIT:
To address the issue with the category being null, here is a revised version.
feedContactCategorySelection();
function feedContactCategorySelection() {
// Do anything here before running the ajax
// For instance, get category and pass it to the assignContact...
var category = sessionStorage.getItem("category");
...
// Move the if statement here so it checks the condition earlier.
if (category === null) {
assignContactCategoryToLocal(category, myCallbackFunction);
} else {
myCallbackFunction(category);
}
}
function myCallbackFunction(category) {
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
}
function assignContactCategoryToLocal(category, callback) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
// Now that it is done and successful, run the rest...
callback(category);
}
});
}
Consider using Promise in this case.
Pseudocode as below:
feedContactCategorySelection();
function feedContactCategorySelection(){
assignContactCategoryToLocal().then(function(){
var category = sessionStorage.getItem("category");
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
})
}
function assignContactCategoryToLocal() {
return new Promise(function(resolve, reject){
var category = sessionStorage.getItem("category");
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
resolve()
}
failed:{reject(reason)}
});
})
}
Please check i have added async: false, to wait until get the ajax response.
feedContactCategorySelection();
function feedContactCategorySelection(){
assignContactCategoryToLocal();
var category = sessionStorage.getItem("category");
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
//....
}
}
function assignContactCategoryToLocal() {
var category = sessionStorage.getItem("category");
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
async: false,
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
}
});
}
function feedContactCategorySelection() {
// `data` : `sessionStorage.getItem("category")` or response from `$.ajax()`
assignContactCategoryToLocal().then(function(data) {
// if `category` set , return `category` , else set `category`
var category = sessionStorage.getItem("category") != null
? sessionStorage.getItem("category")
: sessionStorage.setItem("category", JSON.stringify(data));
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
//....
}
// handle errors, if any, from `$.ajax()` call
}, function err(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
})
}
function assignContactCategoryToLocal() {
var category = sessionStorage.getItem("category");
// if `category` is `null` , return `$.ajax()` response
return category == null
? $.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET'
})
: $.when(category)
}

Categories