loop executes only last array element using php, ajax and javascript - 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.

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

Why my json is returning false?

I need some help, i can't understand why my json is returning false...
This is my Ajax :
var xhr10 = getXhr();
length=document.getElementById('ChoosenStuff').options.length;
ListChoosenStuffNames = [];
for(var i=0;i<length;i++)
{
ListChoosenStuffNames[i] = document.getElementById('ChoosenStuff').options[i].value;
}
xhr10.onreadystatechange = function(){
if(xhr10.readyState === 4 && xhr10.status === 200){
Selection = JSON.parse(xhr10.responseText);
for(var i = 0; i < Selection.length; i++) {
document.getElementById('ShowResult').innerHTML += Selection[i] + "\n\r";
}
}
};
xhr10.open("POST","Ajax/AjaxGetDTravauxCorrespondant.php",true);
xhr10.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr10.send("ListChoosenStuffNames="+ListChoosenStuffNames);
And then my php file with my query which works on phpMyAdmin :
include '../Reglage/ConnexionBDD.php';
$res = [];
$Query="Select NomDomaineTravaux from equipement
JOIN typeequipement ON equipement.CodeTypeEquipement =
typeequipement.CodeTypeEquipement
JOIN domainetravaux ON typeequipement.IDDomaineTravaux =
domainetravaux.IDDomaineTravaux
WHERE NomEquipement=:stuff";
$rep = $bdd->prepare($Query);
$custom = $_POST['nomsEquipementsChoisis'];
$rep->bindParam(':stuff',$custom);
$rep->execute();
$NomDomaineTravaux= $rep->fetch(PDO::FETCH_ASSOC);
$res[$i]= $NomDomaineTravaux;
echo json_encode($res, true);
I have {NomDomaineTravaux: "Divers"}
how do i use this to display "Divers" in my js file with obj = JSON.parse(xhr.reponseText) ?
I tried obj.NomDomaineTravaux but it says that he dont recognize this... :(
Thanks A LOT,

Spell email address for forums

How can I make the code of the mail to spell it and undetectable for forum when I try to put it in html
Thank's anticipated
Like this ! but more sophisticated
<h>mariaburkke76</h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>#<h><h><h><h><h>g<h><h><h><h><h><h><h><h><h><h><h>m<h><h><h>a<h><h>i<h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>l<h><h><h><h>.<h>com<h><h><h><h><h><h><h><h><h>
You could use a combination of XOR (w/ random key) and base64/atob.
Though it wont stop a bot which is specifically designed to scrape your forum, see below.
<?php
$email = 'mariaburkke76#gmail.com';
function xor_email($str) {
$key = mt_rand(1, 192);
for ($i = 0; $i < strlen($str); $i++) {
$str[$i] = chr(ord($str[$i]) ^ $key);
}
return $key.'.'.base64_encode($str);
}
$enc = xor_email($email);
?>
<e data-enc='<?= $enc ?>'/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
var decode = function(key, hash) {
var salt = parseInt(key);
var result = '';
for (var i=0; i<hash.length; i++) {
result += String.fromCharCode(salt ^ hash.charCodeAt(i));
}
return result;
}
$(document).find('e').each(function(){
var data = $(this).data('enc').split(".");
$(this).replaceWith(decode(data[0], atob(data[1])));
});
</script>
Would generate the following.
<e data-enc='102.WgdGDhQDAFtECwcPChIJXAsHFA8HBBMUDQ0DUVAmAQsHDwpIBQkLRFgLBxQPBwQTFA0NA1FQJgELBw8KSAUJC1pJB1g='/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
var decode = function(key, hash) {
var salt = parseInt(key);
var result = '';
for (var i=0; i<hash.length; i++) {
result += String.fromCharCode(salt ^ hash.charCodeAt(i));
}
return result;
}
$(document).find('e').each(function(){
var data = $(this).data('enc').split(".");
$(this).replaceWith(decode(data[0], atob(data[1])));
});
</script>
From a harvesters point of view, once determined the method of protection one could easily scrape out the email as followed. Just so you're under no illusions that security through obscurity will not protect you from a custom-made email bot/scraper/harvester.
<?php
$html = '<e data-enc=\'102.WgdGDhQDAFtECwcPChIJXAsHFA8HBBMUDQ0DUVAmAQsHDwpIBQkLRFgLBxQPBwQTFA0NA1FQJgELBw8KSAUJC1pJB1g=\'/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
var decode = function(key, hash) {
var salt = parseInt(key);
var result = \'\';
for (var i=0; i<hash.length; i++) {
result += String.fromCharCode(salt ^ hash.charCodeAt(i));
}
return result;
}
$(document).find(\'e\').each(function(){
var data = $(this).data(\'enc\').split("-");
$(this).replaceWith(decode(data[0], atob(data[1])));
});
</script>';
function xor_email($str, $key) {
for ($i = 0; $i < strlen($str); $i++) {
$str[$i] = chr(ord($str[$i]) ^ $key);
}
return $str;
}
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
//
foreach ($doc->getElementsByTagName('e') as $e) {
// parse out XORed string
$enc = $e->getAttribute('data-enc');
$enc = explode('.', $enc);
$decoded = xor_email(base64_decode($enc[1]), $enc[0]);
// parse out email
$sub_doc = new DOMDocument();
$sub_doc->loadHTML($decoded);
foreach ($sub_doc->getElementsByTagName('a') as $a) {
echo $a->nodeValue;
}
}
https://3v4l.org/T0mlp
You could use ROT13 simple cipher. It is used to screen out spam bots.

Datalist not opening after repopulation

I'm using AJAX to retrieve information from a database, this was provided for me through another question on StackOverflow, and I've got it working how I want (Minus this one fluke).
Here's how this is set up:
<script>
var input = document.getElementById('search_bar');
input.addEventListener('keypress', function () {
callServer(input);
});
</script>
<script>
function callServer (input) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//return the JSON object
console.log(xmlhttp.responseText);
var arr = JSON.parse(xmlhttp.responseText);
var parentDiv = document.getElementById('items');
parentDiv.innerHTML = "";
//fill the options in the document
for(var x = 0; x < arr.length; x++) {
var option = document.createElement('option');
option.value = arr[x];
//add each autocomplete option to the 'list'
parentDiv.appendChild(option);
};
}
}
xmlhttp.open("GET", "incl/search.php?value="+input.value, true);
xmlhttp.send();
}
Now, when typing into the input field I expect the datalist to update continuously, which it does, the only issue is that the dropdown list is not visible, and I can't access it until I click off of the input field, and then back on the dropdown arrow.
How can I resolve this?
PHP Code for those who are curious:
<?php
include 'connection.php';
$results = array();
if(!isset($_GET['value'])) {
array_push($results, 'No results found.');
die(json_encode($results));
}
$value = $_GET['value'];
$statement = $connection->prepare("SELECT name FROM `item_table`.`items` WHERE `name` LIKE :val LIMIT 5");
$value = '%'.$value.'%';
$statement->bindParam(":val", $value);
if($statement->execute()) {
$rows = 0;
while($row = $statement->fetch()) {
$rows++;
array_push($results, $row['name']);
}
if($rows == 0) {
array_push($results, 'No results found.');
die(json_encode($results));
}
} else {
array_push($results, 'No results found.');
die(json_encode($results));
}
echo json_encode($results);
?>
The JSON being sent to the client is being parsed correctly, just to re-iterate, the issue is that the datalist is not being shown properly.

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Categories

Resources