php sees, for example, 11 as 1 - javascript

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;");
}
}

Related

ajax response returns every value as a single character

I am trying to figure out where I go wrong in this request. I have an ajax post request and I receive the response as single character. For example instead of "name":"john" I get:
n
a
m
e
j
o
h
n
This is my code:
$.ajax({
url: 'test.php',
type: "POST",
data: ({
name: 'john'
}),
success: function(data) {
var JSONString = data;
var JSONObject = JSON.parse(JSONString);
console.log(JSONString);
load(JSONString);
},
error: function() {
alert('error');
}
});
}
<?php
$db = new SQLite3('database.db');
$userAnswer = $_POST['name'];
$results= $db->query("SELECT * FROM 'database' where name='".$userAnswer."'");
$data= [];
while ($res= $results->fetchArray(1))
{
array_push($data, $res);
}
echo json_encode($data);
?>
function load(res) {
var JSONObject = res;
var arr = Object.values(JSONObject);
for (var i = 0; i < arr.length; i++) {
}
}
}

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

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.

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

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

Using javascript to loop through PHP response

I have the following code to store the search results, but at the moment it rewrites the variables each time the loop is run, I need to some how pass to my javascript the data in rows so I can show a table on the html page with the results in.
$num = mysql_num_rows($sql);
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
while ($row = mysql_fetch_array($sql)){
$json['data']['name'] = $row['name'];
$json['data']['barcode'] = $row['barcode'];
$json['data']['serial'] = $row['serial'];
}
}
else
{
$json['success'] = FALSE;
}
echo json_encode($json);
Javascript
$.ajax({
type: 'POST',
url: 'search/search.php',
crossDomain: true,
data: {data: data},
dataType: 'json',
async: false,
success: function (response){
if (response.success) {
$('#search-results').show();
var name = response.data.name;
var barcode = response.data.barcode;
var serial = response.data.serial;
$("#searchname").html(name);
$("#searchbarcode").html(barcode);
$("#searchserial").html(serial);
}
else {
console.log("fail");
}
},
});
Try changing the while loop with below -
$i = 0;
while ($row = mysql_fetch_array($sql))
{
$json[$i]['data']['name'] = $row['name'];
$json[$i]['data']['barcode'] = $row['barcode'];
$json[$i]['data']['serial'] = $row['serial'];
$i++;
}
JS -
if (response.success)
{
$('#search-results').show();
for(field in response.data)
{
var name = field.name;
var barcode = field.barcode;
var serial = field.serial;
$("#searchname").html(name);
$("#searchbarcode").html(barcode);
$("#searchserial").html(serial);
}
}
On the PHP side:
// Keep only the desired columns
$jsonRow = array();
foreach (array('name', 'barcode', 'serial') as $column) {
$jsonRow[$column] = $row[$column];
}
// Add the row to the JSON response
$json['data'][] = $jsonRow;
The output will look like this:
{
"success": true,
"data": [
{
"name": "NAME1",
"barcode": "BARCODE1",
"serial": "SERIAL1"
},
{
"name": "NAME2",
"barcode": "BARCODE2",
"serial": "SERIAL2"
}
]
}
Then on the JavaScript side, iterate over the array response.data and build the table:
var $table, $tbody, i, row;
$table = $('<table>');
$table.append('<thead><tr><th>Name</th><th>Barcode</th><th>Serial</th></tr></thead>');
$tbody = $('<tbody>').appendTo($table);
for (i = 0; i < response.data.length; ++i) {
row = response.data[i];
// Then generate the HTML elements for this row using the strings
// row.name, row.barcode, row.serial and add them to the table
$('<tr>')
.append($('<td>').text(row.name))
.append($('<td>').text(row.barcode))
.append($('<td>').text(row.serial))
.appendTo($tbody);
}
$('body').append($table);

Categories

Resources