Using javascript to loop through PHP response - javascript

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

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

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

actually i use depentdropdown list with ajax but its not working

actually I am creating a dependent dropdown list but my ajax js_base_url not going to controller. I don't know what's a problem. table name is system_detail, and software_detail. and my controller name is SoftwaredetailController.php and SystemdetailController.php
my ajax code:
function getEmployee(id){
$.ajax({
type:'POST',
url: JS_BASE_URL + 'systemdetail/get-employee',
data:{'id':id},
// dataType: 'text',
success: function(data) {
var options = '<option value="">Please Select</option>';
if ( data ) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
options +='<option value="'+json[i].system_id+'">'+json[i].system_id+'</option>'
}
$('#software_detail-system_id').html(options);
return false;
}
$('#software_detail-system_id').html('');
$('#software_detail-system_id').html(options);
},
});
}
my controller code:
public function actionGetEmployee()
{
echo"<i am here>";die;
$postData = Yii::$app->request->post();
// echo "<pre>";
// print_r($postData['id']]);
// die;
$allSystemDetail = SystemDetail::find()
->where(['user_id' => $postData['id']])
->asArray()
->all();
if ($allSystemDetail){
return json_encode($allSystemDetail);
}else{
return false;
}
}
my dropdownlist list code:
<?= $form->field($model, 'user_id')->dropDownList(
ArrayHelper::map(Employee::find()->asArray()->all(),'id','employee_id'),
[
'onchange' => 'getEmployee(this.value)',
'prompt'=>'Please Select',
])->label('Employee Id'); ?>
<?= $form->field($model, 'system_id')->dropDownList(
ArrayHelper::map(SystemDetail::find()->asArray()->all(),'system_id','system_id'),
[ 'prompt' => 'Select System id']); ?>
You should use Url::to(['controller/action']) in JS code like :
function getEmployee(id){
$.ajax({
type:'POST',
url: "<?php echo yii\helpers\Url::to(['systemdetail/get-employee']); //url for ajax call ?>",
data:{'id':id},
// dataType: 'text',
success: function(data) {
var options = '<option value="">Please Select</option>';
if ( data ) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
options +='<option value="'+json[i].system_id+'">'+json[i].system_id+'</option>'
}
$('#software_detail-system_id').html(options);
return false;
}
$('#software_detail-system_id').html('');
$('#software_detail-system_id').html(options);
},
});

Same type of data once called is a JSON Object but when called 2nd time it turns out to be a string

Following is my JS Code.
function showresult(data){
jQuery.each(data, function(key, value) {
var count = 1;
if(key == 0){
jQuery.each(value, function(key, value) {
var str = value.split(',');
jQuery.each(str, function(key, value1) {
eval("document.getElementById('image"+count+"').src = '"+value1+"';");
count++;
});
});
}
if(key == 1){
var count = 1;
jQuery.each(value, function(key, value) {
jQuery.each(value, function(key, value1) {
jQuery('#image'+count).after(value1+'%');
count++;
});
});
}
});
}
When I doalert(data), I get [object Object], following is the data I am passing to the function.
[{"path":"patternimages/041929_d.jpg,patternimages/016630_d.jpg,patternimages/039462_d.jpg,patternimages/065862_d.jpg,patternimages/041984_d.jpg,patternimages/041931_d.jpg,patternimages/041939_d.jpg,patternimages/075066_d.jpg"},{"percentage":["100","100","99","98","98","97"]}]
When another call made to the same function but with different data, after alert(data) gives me following result. I was expecting [object Object] after alert but I didn't got that type of result after alert.
[{"path":"patternimages/051696_d.jpg,patternimages/026965_d.jpg,patternimages/047889_d.jpg,patternimages/050544_d.jpg,patternimages/019186_d.jpg,patternimages/005978_d.jpg,patternimages/044707_d.jpg,patternimages/045949_d.jpg,patternimages/104967_d.jpg,patternimages/006135_d.jpg,patternimages/006897_d.jpg,patternimages/017471_d.jpg"},{"percentage":["83","83","80","80","65","63","63","63","62","59","59","51"]}].
Following is my PHP Code
public function result($result) {
$results = array();
while ($row = mysql_fetch_array($result)) {
$id[] = $row['image_id'];
$percentage[] = $row['percentage'];
}
if (#count($id) > 1) {
$id = array_unique($id);
} else {
#$id = $id;
}
$fresult = $this->GetResult($id);
$count = mysql_num_rows($fresult);
if ($count > 1) {
while ($row = mysql_fetch_array($fresult)) {
$ids[] = $row['id'];
$names[] = $row['name'];
$percentages[] = $row['percentage'];
}
$percent_val = array();
$res = implode(',patternimages/', $names);
$path['path'] = 'patternimages/' . $res;
$percent_val['percentage'] = $percentages;
array_push($results, $path);
array_push($results, $percent_val);
} else {
$results = 'No Data Found';
}
return $results;
}
the result is encoded to JSON response like this echo json_encode($results, JSON_UNESCAPED_SLASHES);
EDIT JS code
$.ajax({
type: 'post',
dataType: "json",
url: url,
data: {color1: color1},
success: function(data) {
showresult(data);
}
});

Categories

Resources