ajax json response array using in php - php

I made an ajax form with json response. The json array contains information out of a mysql database. Now I want to show these datas in a table.
I made a placeholder in the html file which is hidden.
Here my Code for the ajax/json part:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
//alert(select.ID[0]);
//alert(select.ID[1]);
//alert(select.ID.length);
$("#coffee_talk").fadeOut();
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my html:
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />​​​​​​​​​​​​​​​​​
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
$response['ID'] = $getID;
$response['Date'] = $getDate;
$response['Theme'] = $getTheme;
$response['Contributer'] = $getContributer;
$response['Begin'] = $getBegin;
$response['Place'] = $getPlace;
$response['Entrance'] = $getEntrance;
$response['Flyer'] = $getFlyer;
echo json_encode($response);
}
}
Div with id=coffee_talk is my placeholder. Now I wish to fade in the table with its data and if I change the year and submit it with the button I wish to fade the old one out and fade new in.
My only problem is that I need to write this table in php with loops. But I think its not possible in Java Script. What should I do?
PS I used ajax cause I dont want to have a reload all the time.

Your quick solution would be:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
var coffee_talk = $("#coffee_talk");
coffee_talk.fadeOut('fast', function() {
for(i in select) {
row = select[i];
div = coffee_talk.append('<div id="row_'+i+'" />');
for(column in row) {
div.append('<span class="column_'+column+'">'+row[column]+'</span>');
}
}
coffee_talk.fadeIn();
});
}
});
return false;
});
For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).
It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.

Related

Ajax reload frame only works once

I have a timetable on my website. The user can select multiple times. The selected time is inserted into the database and the button turns from green to red, so the user know it's disabled.
I want to do this with only a reload of div.
It does work but it work only once, when pushing the button for the second time the div doesn't refresh / reload.
Update database / refresh;
$('.updateTime').click(function(){
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
var uniqueId = $(this).attr('id');
var sdate = getUrlParameter('date');
$.ajax({
url: './ajax/reservation_insert_times.php',
type: 'POST',
data: {
uniqueId :uniqueId, sdate :sdate
},
success: function(mydiv){
$("#result").load(location.href+ ' #mydiv');
}
});
});
The code for generating the times
<div class="row" id="result">
<?
$result = array();
$query = $db->query("SELECT * FROM reservation_times WHERE datum = '" . db_escape($_GET['date']) . "' ");
while($row = mysqli_fetch_array($query)) {
$result[] = $row['time'];
}
?>
<?
$timestamp = strtotime(date("Y-m-d")." 12:00");
for ($i=0;$i<=32;$i++) {
$time = date('H:i', $timestamp);
$time .= ' UUR';
if (in_array($time, $result)) {
$color = "background-color:red !important";
}
else $color = "";
$timestamp += 15 * 60;
if (isset($checked) && $checked !='') { $color = 'background-color: red;';}?>
<div class="col-xs-4 col-md-3 col-lg-2" id="mydiv">
<button type="button" id="<?=$time;?>" class="btn btn-block btn-success btn-sm text-center" style="padding:10px; margin-bottom:10px; <?=$color;?>" onclick="" <? if (isset($checked) && $checked !='') { echo 'disabled';}?>>
<?=$time;?>
</button>
</div>
<? } ?>
</div>
The code for the reservation_availablity.php call:
$query = $db->query("SELECT * FROM reservation_times WHERE time = '".$uniqueId."'");
if(mysqli_num_rows($query) == 1) {
$remove = $db->query("DELETE FROM reservation_times WHERE time = '".$uniqueId."'");
} else {
if (isset($uniqueId) && $uniqueId !='') :
$sql = $db->query("INSERT INTO reservation_times (time, datum)
VALUES ('".$uniqueId."', '".$newDate."')");
endif;
}
Change you success method of your ajax:
$.ajax({
url: './ajax/reservation_insert_times.php',
type: 'POST',
data: {
uniqueId :uniqueId, sdate :sdate
},
success: function(mydiv){
$("#result").html(mydiv);
}
});
You are sending an ajax to get new content but then in success method instead of loading new content received as ajax response you are again loading the content of the same div. That's why it is working for the first time but will remain unchanged next time onwards.
//Wrong
$("#result").load(location.href+ ' #mydiv');
// Correct
$("#result").html(mydiv);
So, now whenever this ajax send to the server, it will update the content of div#result. And to allow user to manually refresh the content of this div as and when desired then you will have to call this ajax upon click of a button labled as Refresh Timetable.

Get ajax json data individually

I have a slight problem with my code, lets say i have a json like this one :
[{"img":"john.png","name":"John","username":"#john"},
{"img":"mark.png","name":"mark","username":"#mark"}]
I wanna get data organized like :
John #john john.png
Mark #mark mark.png
But every time the data comes out like this:
John Mark #john #mark john.png mark.png
This is my Php Code:
<?php
class search{
public function gettingvalues($search_value){
require_once('conx.php');
$dir = "usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
$results[] = $json;
}
echo json_encode($results);
}
}
}
}
?>
This the index code:
<?php
if (isset($_POST['data'])) {
require('search.php');
$search = new search;
$search->gettingvalues($_POST['data']);
header('Content-Type: application/json; charset=utf-8');
die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data) {
var img = [];
var username = [];
var name = [];
$.each(json_data, function(index, element) {
img.push(element.img);
username.push(element.username);
name.push(element.name);
})
$('#feedback').html('');
$('#feedback').html(name+username+img);
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
Actually this is my first time with json, i don't know what is the problem or maybe i missed something, I hope getting some answers.
You need to build the HTML in the order that you want it displayed.
var html = '';
$.each(json_data, function(index, element) {
html += `${element.name} ${element.username} ${element.img}<br>`;
}
$("#feedback").html(html);

Using JQuery Append From AJAX

I want to create a dropdown list that populated by another dropdown list. I'm using AJAX and PHP.
I have created my AJAX file like this:
<?php
if(isset($_POST['selname']))
{
include('config.php');
$clientId = $_POST['selname'];
$query = "SELECT tv.*, v.* FROM t_vorder tv LEFT JOIN m_vehicle v ON tv.tv_vehicleid = v.v_id WHERE tv_orderid = '$clientId'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$namek = "";
$namek .= $row['v_id'];
if($row['v_jenis'] != "" || !empty($row['v_jenis']))
{
$namek .= ' - '.$row['v_jenis'];
}
if($row['v_platno'] != "" || !empty($row['v_platno']))
{
$namek .= ' - '.$row['v_platno'];
}
if($row['v_merk'] != "" || !empty($row['v_merk']))
{
$namek .= ' - '.$row['v_merk'];
}
$xx .= "<option value='$row[v_id]'>$namek</option>";
}
return $xx;
exit;
}
?>
After that, I called this AJAX file to my main program, here's my JQuery code:
function getVehicle()
{
var selname = $("select[name=noorder]").val();
$('#combobox2').html('');
$.ajax({ url: "getVehicle.php",
data: {"selname":selname},
type: 'post',
dataType: "json",
success: function(output) {
console.log(output);
$('#combobox2').append(output);
}
});
}
And last is my HTML code:
<select name="noorder" id="combobox" class="form-control">
//get my vehicle from database
<?php
$querycon = mysqli_query($conn, "SELECT * FROM m_order WHERE o_status='1' ORDER BY o_id");
while($rowcon = mysqli_fetch_array($querycon, MYSQLI_ASSOC))
{
$invoice = sprintf("%s%"."04d", $rowcon['o_code'], $rowcon['o_id']);
?>
<option value="<?php echo $rowcon['o_id']; ?>"><?php echo $invoice; ?></option>
<?php
}
?>
</select>
<select name="kendaraan" class="form-control" id="combobox2" onclick="getVechile();">
</select>
My Ajax works fine, my console log return that the file finished load. But my dropdown list not appended by Jquery. Anyone know where's my mistakes?
You did't request for json obj/data into ajax success callback, then no need for dataType: "json", inside ajax properties. Remove that and change return $xx; into echo $xx;
AJAX request gets data from PHP file only when its printed out on the page.
Returning and data from PHP (AJAX backend) to jQuery/Javascript does not mean anything.
Change
return $xx;
to
echo $xx;
You use the dataType: "json" in your ajax call, so it get response in JSON. First remove dataType: "json" line from ajax call. Then replace return $xx; with echo $xx; in your php script.
Hope this solution may works for you, Thanks!

How to update dynamically populated content with AJAX

I have some code which populates like so:
<select class="form-control" name="accommodation_ID" id="accommodation_ID">
<option value="-1">-- Please Select --</option>
<?php
$AccomodationID = 13; //For testing purposes
$accommodation_query = mysqli_query($conn,"SELECT ENTITIES.LastName,
ACCOMMODATION.AccomodationID, ACCOMMODATION.PUPoint
FROM ACCOMMODATION, ENTITIES WHERE ENTITIES.Entity_ID =
ACCOMMODATION.Entity_ID")
or die("Error: ".mysqli_error($conn));
while($accommodation_Results = mysqli_fetch_array($accommodation_query)){
if($accommodation_Results['AccomodationID'] == $AccomodationID){
echo '<option selected value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
$PUPoint = $accommodation_Results['PUPoint'];
}
else{
echo '<option value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
}
}
?>
</select>
<label>Pick Up Point</label>
<input type="text" name="PUPoint" readonly value="<?php echo $PUPoint; ?>">
This code works no problem, it checks the database and looks for a match, if it does, set is as the selected option, grab the PUPoint (Pickup point) variable and store it in the input field.
My problem now, is when I go to select a different option from the dropdown list, the pickup point input field doesn't update anymore. This is what I had, working before I implemented the above:
j$('select[name=accommodation_ID]').change(function(event) {
event.preventDefault();
var accommodationID = j$(this).val();
post_data = {'accommodation_ID':accommodationID};
var data = {
"action": "Accommodation_Details"
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
j$('input[name=PUPoint]').val( data["PUPoint"] );
},
error: function (request) {
console.log(request.responseText);
}
});
});
booking_Modify.php
//checks and switch statement related code
$return = $_POST;
$return["accommodation_ID"] = $_POST["accommodation_ID"];
$return["SQL"] = "SELECT * FROM ACCOMMODATION WHERE AccommodationID = ".$_POST["accommodation_ID"]."";
$query = mysqli_query($conn,"SELECT * FROM ACCOMMODATION WHERE AccomodationID = ".$_POST["accommodation_ID"]."")
or die("Error: ".mysqli_error($conn));
$row = mysqli_fetch_array($query);
$return["PUPoint"] = $row["PUPoint"];
$return["json"] = json_encode($return);
echo json_encode($return);
I've done some echoing/console.log and noticed that it's always passing the same Accommodation ID number (13) into booking_Modify.php. It doesn't change when I select a different option now. I don't know if it's because of the "selected" attribute applied to the option element now. Any ideas would be greatly appreciated
You have defined your $AccomodationID = 13; //For testing purposes before which is printed in every iteration of the while loop instead of the current ID. Probably you want to write $accommodation_Results['AccomodationID'] as the option value.

how to update PHP variable with Jquery Ajax?

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Categories