Why can I not iterate over this object? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am trying to iterate over an object, but the jquery $.each won't fire.
This is the outcome of the $fileNames variable:
and this is the code I've built so far:
$("input[type=button]").on("click", function(){
$searchtag = '';
$files = '';
$fileNames = {};
// first get all files in the directory
$.ajax({
url: "php/cse.php",
data: "requestFileNames=true",
method: "POST",
success: function(result){
$result = JSON.parse(result).toString();
$result += ",";
$count = ($result.match(/o/g)||[]).length + 1;
for (var i = 1; i <= $count; i++) {
$fname = $result.substr(0, $result.indexOf(','));
$fileNames[$fname] = {};
$result = $result.replace($fname + ",", "");
}
}
});
console.log($fileNames);
$.each($fileNames, function(key, value){
// this does not fire, for some reason.
});
});
Why is it not working?

Make async false, but this will pause the code.
$.ajax({
url: "php/cse.php",
data: "requestFileNames=true",
method: "POST",
**async: false,**
success: function(result){
$result = JSON.parse(result).toString();
$result += ",";
$count = ($result.match(/o/g)||[]).length + 1;
for (var i = 1; i <= $count; i++) {
$fname = $result.substr(0, $result.indexOf(','));
$fileNames[$fname] = {};
$result = $result.replace($fname + ",", "");
}
}
});
Or call the function (i.e. $.each()) within success or complete method

Related

AJAX keep showing wrong data from array

I have a loop that calls multiples AJAX to find out if there's any booking in the database or not. JS will pass the data from an array to AJAX and find it out in database through SQL query.
However, the data returned from the AJAX is correct, and if it's there in database, i want to to show the data returned from AJAX and the current value of array in current loop, but still the data that i show from the array is the last index of array.
javascript :
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
for (var j = 0; j < lap.length; j++){
for (var i = 0;i < jam.length; i++){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
}
return false;
}
PHP File:
<?php
ob_start();
$error=""; // Variable To Store Error Message
$connection = mysqli_connect(/*credential*/);
$tgl = $_POST['date'];
$time = $_POST['time'];
$lap = $_POST['lapangan'];
//Query
$query = mysqli_query($connection, "SELECT * FROM lapangan_book WHERE tanggal='$tgl' and jam='$time' and lapangan='$lap'");
$rows = mysqli_num_rows($query);
$data = mysqli_fetch_array($query);
if($rows > 0){
echo $data['lapangan'];
}else{
echo "0";
}
?>
The output should be
Lapangan A
22lapA
22Lapangan A
But keep showing
Lapangan A
22lapBat
22Lapangan Batminton
Yes, this is happening because of the Asyncroniouse behavior of ajax. There is two tricks you have to send asynchronous request by async: false or you have to call the recursive function after success response from ajax request.
Trick 1- Pass option aysnc: false in ajax request, but some browser will throws warning in synchronous request of ajax
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
Trick 2: Recursive function, this is most accurate way of calling
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
var i=0;
var j=0;
var ajaxCall= function(){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
var recursiveCall=true;
i=i+1;
if(i>=jam.length){
j=j+1;
if(j>=lap.length) recursiveCall= false;
else i=0;
}
if(recursiveCall===true)
{
ajaxCall();
}
},
error: function () {
$('#output').html('ERROR!');
},
});
}
ajaxCall();
return false;
}
I have written code for your understanding might be your have to made come modification in this code

php sees, for example, 11 as 1

function zwrot() {
var zwrot = document.getElementsByClassName("zwroc");
var i;
for (i = 0; i < zwrot.length; i++) {
if(zwrot[i].checked){
parseInt(zwrot[i])
var ajax = $.ajax({
url: 'php/request.php',
type: 'POST',
data: {zwrot: zwrot[i].value},
success: function(data)
{
$.growl.notice({
title: "INFO",
message: "Oddano książkę" });
}
})
}
}
setTimeout(function() {
location.reload()
}, 2000
);
}
php code:
if(isset($_POST['zwrot'])) {
$zwrot=$_POST['zwrot'];
$n = count($zwrot);
for ($i=0;$i<$n; $i++){
$data=date("d-m-Y");
$zapytanie5 = mysqli_query ($link, "UPDATE zamowienie SET data_zwrotu='$data' WHERE id_zamowienie=$zwrot[$i]");
$zapytanie6 = mysqli_query ($link, "UPDATE ksiazka INNER JOIN zamowienie ON ksiazka.id_ksiazka=zamowienie.id_ksiazka SET ilosc=ilosc+1 WHERE id_zamowienie=$zwrot[$i];");
}
}
everything is ok, until id is a one-digit number. the problem occurs with two-digit numbers, php sees, for example, 11 as 1
I dont think you're passing any array to your php. and that's not how you pass and receive an array through ajax if ever, you need json for that.
Anyway, try this:
if(isset($_POST['zwrot'])) {
$zwrot=$_POST['zwrot'];
$data=date("d-m-Y");
$zapytanie5 = mysqli_query ($link, "UPDATE zamowienie SET data_zwrotu='$data' WHERE id_zamowienie=$zwrot");
$zapytanie6 = mysqli_query ($link, "UPDATE ksiazka INNER JOIN zamowienie ON ksiazka.id_ksiazka=zamowienie.id_ksiazka SET ilosc=ilosc+1 WHERE id_zamowienie=$zwrot;");
}
Or if you want to pass by array:
function zwrot() {
var zwrot = document.getElementsByClassName("zwroc");
var i;
var zwrot_array = [];
for (i = 0; i < zwrot.length; i++) {
if(zwrot[i].checked){
zwrot_array[i] = zwrot[i].value;
}
}
var ajax = $.ajax({
url: 'php/request.php',
type: 'POST',
data: {zwrot: JSON.stringify(zwrot_array)},
success: function(data)
{
$.growl.notice({
title: "INFO",
message: "Oddano książkę"
});
setTimeout(function() {
location.reload()
}, 2000
);
}
});
}
PHP:
if(isset($_POST['zwrot'])) {
$zwrots = json_decode($_POST['zwrot']);
$data=date("d-m-Y");
foreach ($zwrots as $zwrot) {
$zapytanie5 = mysqli_query ($link, "UPDATE zamowienie SET data_zwrotu='$data' WHERE id_zamowienie=$zwrot");
$zapytanie6 = mysqli_query ($link, "UPDATE ksiazka INNER JOIN zamowienie ON ksiazka.id_ksiazka=zamowienie.id_ksiazka SET ilosc=ilosc+1 WHERE id_zamowienie=$zwrot;");
}
}

loop executes only last array element using php, ajax and javascript

Hi friends am trying to save the data from the loop here is my code.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body onload="searchVideo();">
<?php
ini_set('max_execution_time', 300);
$query = "SELECT * FROM `playlists`";
$result = mysqli_query($mysql,$query);
while($row=mysqli_fetch_assoc($result)){
$id=$row['id'];
$playlists=$row['playlists'];
$myArray = explode(',', $playlists);
$length = sizeof( $myArray);
$myArray[0]=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-
$myArray[1]=PLFgquLnL59ak1QNHmrUSjNM6WTegpgX__
for ($i=0; $i<$length; $i++){
echo "
<script>
var pageToken = '';
var numOfResult = 0;
var maxResults = 200;
function searchVideo(){
var separator = ',';
$.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken=' + pageToken + '&playlistId=$myArray[$i]&key=APIKEY&callback=?',function(data){
var l = data.items.length;
pageToken = data.nextPageToken;
numOfResult += l;
var itemUrl = '';
var videoids = [];
for(var i = 0; i < l; i++) {
if( i == 0) {
separator = ',';
}
else {
separator = ',';
}
var videoid = data.items[i].snippet.resourceId.videoId;
var title = data.items[i].snippet.title;
$.ajax({
method: 'POST',
url: 'add.php',
data: { title: title, videoid: videoid }
})
.done(function(data) {
});
}
if( numOfResult <= maxResults) {
searchVideo();
}
});
}
</script>
";
}
}
?>
add.php
<?php
$title = mysqli_real_escape_string($mysql,$_POST['title']);
$videoid = mysqli_real_escape_string($mysql,$_POST['videoid']);
$thumbnail_url = 'http://img.youtube.com/vi/'.$videoid.'/hqdefault.jpg';
$sql = "INSERT INTO ytfb(name,video_name,thumbnail_url) VALUES('$title','$videoid','$thumbnail_url')";
$create_post_query=mysqli_query($mysql,$sql);
if(!$create_post_query)
{
die("Connection failed".mysqli_error($mysql));
}
?>
When am trying to save the data using ajax in add.php the elements from the last array element are only saved the elements from the first array element is not saved how can I be able to save the data from all the array elements. Can anyone please help me out with this
Define the function searchVideo outside the cycle and organize to call it with different parameters. In cycle change global vars or input parameters of searchVideo.
Now you get this result because finaly executes the last istance of this function.
for(var i = 0; i < l; i++) {
if( i == 0) {
separator = ',';
}
else {
separator = ',';
}
var videoid = data.items[i].snippet.resourceId.videoId;
var title = data.items[i].snippet.title;
Here i will be the index of last element so only last item is getting stored.
You have to loop the ajax call through the loop to get all elements to be saved.

display data js from datebase sql [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I would like to push my value of textbox to sql and then display it.
I read a lot topics but still nothing. I have always problem to explain my problems but I hope u will see what i want to do escpecialy when u look at db2.php
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: "POST",
url: "db2.php",
data: {'name': nw },
success: function (json) {
jss = json.PYT;
oss = json.ODP;
console.log(jss);
}
});
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
and my db2.php .
<?php
header('Content-type: application/json');
include 'connect.php';
if (isset($_POST['name'])) {
$name = $_POST['name'];
$queryResult = $connect->query("select * from Chatbot where '$name' LIKE
CONCAT('%',PYT,'%')");
$result = array();
while($pomoc = $queryResult->fetch_assoc()){
$result[] = $pomoc;
}
}
echo json_encode($result);
Now my result is {}, echo is null.
console.log(nw)
VM289:1 dsasa
undefined
I know how to get just output from ajax but if i want to push this data everything goes wrong. Best regards
UPDATE. Now I would like to get jss value out of this function to the other one.
var jss = {}; //(first line code)
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
UPDATE 2
var jss2 = {};
var nw;
$(function(){
username();
$("#textbox").keypress(function(event){
if ( event.which == 13) {
if ( $("#enter").prop("checked") ){
$("#send").click();
event.preventDefault();
}
}
});
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
})
function send_message(message){
var prevState = $("#container").html();
if(prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + "<span class = 'bot'>Chatbot: </span>" + message);
}
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hi!");
}
function myFunction() {
var x = document.getElementById("textbox").value;
}
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
I think this is what you need to do with your function so that you can use the jss variable properly, once the ajax request has completed:
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
});
}
Any code which relies on the jss variable must not be executed until after the ajax call has completed. Since ajax calls run asynchronously, the only way to guarantee this is for that code to be included in (or triggered from) the "success" callback function in your ajax request.

javascript code not executing in order [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
So I'm trying to fetch data from a server in json format.
with this code
for (var i = 0; i < hosts.length; i++) {
var tempUrl = url + hosts[i];
jQuery.ajax({
type : "GET",
dataType : "json",
username : "user",
password : "password",
url : url,
async : true,
success : function (data) {
//var obj = data.data.host.status;
//console.log(obj);
jsonHosts.push(data.data);
console.log("added data");
}
});
}
followed by this code block
for (var i = 0; i < jsonHosts.length; i++) {
console.log("dog");
console.log(jsonHosts[i].host.status);
document.getElementById('test').innerHTML += "<br>" + jsonHosts[i].host.status;
document.getElementById('test').innerHTML += '<br>Some new content!';
}
console.log("done");
problem is, my console will show "done" then "added data" and my webpage will be blank.
I've tried putting the first section in a function and trying to get my code to wait for the function to finish executing but to no avail.
anyway I can make this code execute in order/have the second block wait on the first block
Move below portion of code into success callback function
success : function (data) {
//var obj = data.data.host.status;
//console.log(obj);
jsonHosts.push(data.data);
for (var i = 0; i < jsonHosts.length; i++) {
console.log("dog");
console.log(jsonHosts[i].host.status);
document.getElementById('test').innerHTML += "<br>" + jsonHosts[i].host.status;
document.getElementById('test').innerHTML += '<br>Some new content!';
}
console.log("done");
}
The ajax is async so the success function runs after your loop. try this:
for (var i = 0; i < hosts.length; i++) {
var tempUrl = url + hosts[i];
jQuery.ajax({
type : "GET",
dataType : "json",
username : "user",
password : "password",
url : url,
async : true,
success : function (data) {
//var obj = data.data.host.status;
//console.log(obj);
console.log("done");
jsonHosts.push(data.data);
console.log("added data");
DataCame(jsonHosts);
}
});
}
function DataCame(jsonHosts){
for (var i = 0; i < jsonHosts.length; i++) {
console.log("dog");
console.log(jsonHosts[i].host.status);
document.getElementById('test').innerHTML += "<br>" + jsonHosts[i].host.status;
document.getElementById('test').innerHTML += '<br>Some new content!';
}
}

Categories

Resources