Insert parsed JSON into html - php

I've tried many methods, from tutorials and other questions posted but nothing seems to work. I'm trying to get data sent from php into divs and variables with jquery. I have the array set up on the php side, and everything works fine but on the jquery side i always get an unexpected identifier error or the div is left blank or both
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_rowtest = parseInt(var_numdatacheck);
function waitupdate(){
$.ajax({
type: 'POST',
url: 'update.php',
data: {function: '3test', datacheck: var_rowtest},
dataType: "json",
success: function(check) {
var data = JSON.parse(check);
var_rowtest = data[id]; // sets the variable numcheck as the new id number
$('#datacheck').html(data[0]); // I've confirmed data[0] has a value but the div is left blank
}
error: function(msg) {
console.log(msg)// here i get an unexpected identifier error
}
});
}
$(document).ready(function() {
waitupdate();
});
The output from the php is
{"id":"4","0":"Name"}
here is the actual php code
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$check['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery)){
?>
<?php $check[]= $row['First Name']; ?>
<?php
}
echo json_encode($check);
}
?>
</div>
</ul>

This will work for you,
var var_rowtest = data['id'];
var value= data[0];
set variable var_rowtest and value in your div as needed.
I guess var_rowtest = data[id]; is not a proper syntax, use above syntax

Please try and change your variable names, and that error function declared in the $.ajax threw a JS error for me.
Another thing that is unnecessary is the JSON.parse - I made the PHP script called "update.php" return back the correct header:
<?php header('content-type: application/json');?>
This code works:
var numDataCheck = 1,
rowTest = parseInt(numDataCheck);
function waitupdate() {
$.ajax({
type: 'POST',
url: 'update.php',
data: {function: '3test', datacheck: rowTest}, dataType: "json",
success: function(data) {
rowTest = data.id;
$('#datacheck').html(data[0]);
}
});
}
$(document).ready(function() {
waitupdate();
});

Related

ajax dropdown box when a variable exists

I am trying to make an ajax call for the an dropdown box(dynamic)
when the variable $place is available it will make an ajax call and populate
the dropdown box.
I am trying to pass the variable $place to listplace.php and encode it in json data and get the datalist values but not sure the encoded json file is correct
I just given a try and not sure below code works, please help.
Dropdown box
<select>
<option selected disabled>Please select</option>
</select>
Ajax call
<?php if(isset($_GET['place']) && $_GET['place'] !='') {?>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $place ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
var $el = $("#name");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
}
});
</script>
<?php } ?>
listplace.php
<?php
$sql = #mysql_query("select placename from employee where placename= '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
Change your AJAX call to the following.
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<?php } ?>
And your PHP to
<?php
$place = $_POST['place'];
$sql = #mysqli_query($conn,"select placename from employee where placename= '$place'");
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r['placename'];
}
if (count($rows)) {
echo json_encode(['option'=> $rows]);
}else {
echo json_encode(['option'=> false]);
}
var request;
// Abort request is previous doesnt end
if (request) {
request.abort();
}
// Make request
request = $.ajax({
type: "POST",
url: 'listplace.php',
dataType: 'json',
// One option is passed php into script
data: {
department: '<?= $place ?>'
}
// but I prefer this solution
// html markup:
// <div style='display:none;' data-place>YOUR_PLACE</div>
// or hidden input, in final it doesnt matter...
data: {
department: $('[data-place]').text()
}
});
request.done(function(response, textStatus, jqXHR){
// check response status
// HTML Markup:
// <select id='select'></select>
var select = $('#select');
select.empty();
// add default option first one disabled, selected, etc.
// data are rows in your situatios
// append data to select with lodash for example
// _.map(response.rows, function(row){...}
// jQuery each
// $.each(response.rows, function(index,row){...}
})
request.fail(function(){
// do something
})
request.always(function(){
// do something
})
in your .php is missing line
$place = $_POST['department'];

How to pick multiple rows of values of the same id value from the database and display in ajax?

I have written code for button to send a value to php file using ajax as show below :
<script>
$(document).ready(function(){
$(".open-AddBookDialog").click(function(){
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax({
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result1){
var packagetype = package_type;
alert(packagetype);
}
});
});
});
</script>
This is the ajax code for the button which i have written. My button code is :
<a data-toggle="modal" id="custId" data-name="<?php echo $arr["package_name"]; ?>" data-id="<?php echo $arr["id"]; ?>" href="#myModal" class="open-AddBookDialog btn btn-submit" OnClick='change(this);'>Book / Enquiry / Pay</a>
When clicking this button in href, I want to send a id value to a php file using ajax.
data1.php
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
$arr = mysqli_fetch_array($query1);
echo $arr['package_type'];
echo $arr['package_price'];
mysqli_close($con);
?>
using the id value, I want to pick multiple rows of package type and package price from the database having the same id value.After picking the multiple rows of these values i want to send it to the main php file and display all the values of all the rows picked from the database.
Can anyone suggest how to do this ?
<script>
$(document).ready(function()
{
$(".open-AddBookDialog").click(function()
{
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax(
{
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result)
{
resultJson=jQuery.parseJSON(result);
$.each(resultJson.packageDetails, function(i, item) {
var packagetype = item.package_type;
var package_price = item.package_price;
alert("packagetype :- "+packagetype+" ----- package_price :-"+package_price);
});
}
});
});
});
</script>
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
//$arr = mysqli_fetch_array($query1);
while( $strPackageResult=mysqli_fetch_array($query1,MYSQLI_ASSOC) )
{ $ArrPackage[]=$strPackageResult; }
if( isset($strPackageResult) ){ unset($strPackageResult); }
mysqli_free_result($query1);
if( isset($query1) ){ unset($query1); }
$myResultPackageArray=array();
if( isset($ArrPackage) && is_array($ArrPackage) && count($ArrPackage)>0 ) {
$tempArray=array();
foreach( $ArrPackage as $tempPackage )
{
$tempArray['package_type']=$tempPackage['$tempPackage'];
$tempArray['package_price']=$tempPackage['package_price'];
$myResultPackageArray['packageDetails'][] =$tempArray;
}
}
mysqli_close($con);
echo json_encode($myResultPackageArray);
?>
There are some basic things you should know first then you can easily rectify your errors.
Debuging javascript
Prepared Statements
PHP Error Handling
This is not you have asked but as a programmer i will suggest you to go through it.
As going through your code
var packagetype = package_type;
package_type is undefined. If you are using chrome inspect element and check the console you will see the error.
Hope this will work.

how to return an array in AJAX call in php

I have a form that has a select option , So I am trying to update the form/table with some content from database when I select a type in the select option ,
SO for that I did an ajax call something like this.
$("#selectPlantilla").on("change",function(){
var descripcion = $(this).val();
//alert(descripcion);
var url="http://index.php";
var posting = $.post(url, {
im_descripcion: descripcion,
}).done(function (data) {
alert(data);
});
});
And then I validated the call in php on the same inde.php page like this
if(isset($_POST['im_descripcion']))
{
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
$result = mysql_fetch_array($result);
print_r($result);
}
The problem I am facing is in the alert window it return the whole page instead of just the $result that I have printed , So can any one help me out how I can channelize it properly , I have use the values from the array $result to update in the form using JQuery .
Thanks in Advance
For returning PHP array data in Ajax, JSON will make your life the simplest.
$result = mysql_fetch_array($result);
echo(json_encode($result));
This will return the array in a format that is easily usable by JavaScript. Try this to see its content:
alert(JSON.stringify(data));
With JSON, you should be able to fetch data or iterate through it in JavaScript
Try this
In Javascript
<script type="text/javascript">
var $ =jQuery.noConflict();
$(document).ready(function(){
$('.dropdown_class').on('change', function() {
var m_val = this.value;
var datastring = "im_descripcion="+m_val;
$.ajax({
type: "POST",
url: "lunchbox_planner.php",
data: datastring,
cache: false,
success: function(result) {
var v = $.parseJSON(result);
var l = v.length;
for(var i=0;i<l;i++){
var sh_d = "<div class='coco3'>"+v[i]+"</div>";
$('.mon_tea').append(sh_d);
}
}
});
});
});
</script>
<div class="mon_tea">
In PHP
<?php
if(isset($_POST['im_descripcion'])) {
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
while($row_sh = mysql_fetch_array($result)){
$all_incr[] = $row_sh['col_name'];
}
echo json_encode($all_incr);
}
?>

jQuery autosave running success function, but not updating MySQL

My jQuery autosave is running the success function, but not updating the MySQL database. What am I doing incorrectly?
jQuery:
function autosave() {
var t = setTimeout("autosave()", 5000);
var translation = $("#doc-translation").val();
if (translation.length > 0) {
$.ajax({
type: "POST",
url: "update-draft-submission.php",
data: translation,
cache: false,
success: function() {
$(".autosaved").empty().append("saved");
}
});
}
}
PHP:
<?php
session_start();
//retrieve our data
$iddoc = $_GET['iddoc'];
$trans = translation;
$transowner = $_SESSION['userid'];
$true = 1;
include "../dbconnect.php";
$query = "UPDATE translations
SET trans='$trans'
WHERE iddoc='$iddoc'
AND transowner='$transowner'";
mysqli_query($query);
mysqli_close();
echo "Saved";
?>
You are not fetching the data in your PHP correctly:
$iddoc = $_GET['iddoc'];
$trans = translation;
iddoc is not passed as a GET parameter anywhere
"translation" is not a variable (neither do I think it is a constant)
Your SQL will break if it does not get the required values in the query.
Update your javascript so:
$.ajax(
{
type: "POST",
url: "update-draft-submission.php",
data: data: {translation:translation,iddoc:"XXX"},
cache: false,
success: function()
{
$(".autosaved").empty().append("saved");
}
});
Replace XXX with your iddoc value.
Then in PHP fetch them as:
$iddoc = $_POST['iddoc'];
$trans = $_POST['translation'];

Getting variable from mySql to jQuery via ajax

I'm trying to get a variable to jQuery from mySql database.
Here's the php code, getTime.php:
include('connect.php');
$sql = "select * from timer";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$hours = $row['hours'];
$minutes = $row['minutes'];
//echo $hour.":".$minutes;
}
$timeHour = $_POST['hours'];
echo $timeHours;
Here's the ajax POST request for another file:
var timeHour = "";
$.ajax({
type: "POST",
url: "ajax/getTime.php",
data: timeHour
});
$(document).ready(function() {
alert(timeHour);
});
But the alertBox doesn't show anything.
It should be really easy, but i haven't found an example that it explains it.
UPDATE
Thanks! But now i have another problem - I want to use my variables "timerHours" and "timerMinutes"...
$.ajax({
type: "POST",
url: "getTime.php",
success: function(data){
//alert(data);
timerArr = data.split(":")
timerHours=timerArr[0];
timerMinutes=timerArr[1];
}
});
... but it gives 'undefined:undefined' - when i alert data - it works fine.
var today = new Date();
var endTime= new Date(today.getFullYear(), today.getMonth(), today.getDate(), timerHours, timerMinutes , 00);
console.log(timerHours+":"+timerMinutes);//Console: undefined:undefined
var second = (endTime.getMinutes()-today.getMinutes())*60+(endTime.getSeconds()-today.getSeconds());
And if I put it on the doTime function and print it to the html it's working fine too.
function do_time() {
//console.log(timerHours+":"+timerMinutes);//Console: 21:50
second--;
$("#timer").html("Time left: "+second);//Output: Time left: NaN
$('#setTime').html("Hours: "+timerHours+" Minutes: "+timerMinutes);//Works fine too.
}
First of all your getTime.php probably returns nothing right now. Try calling it directly from your browser or check firebug what it is returning. Your code seems almost right but you are overriding it with a probably inexistent $_POST['hours']; Your code should look like this:
include('connect.php');
$sql = "SELECT * FROM timer";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$hours = $row['hours'];
$minutes = $row['minutes'];
}
echo $hours.':'.$minutes;
Then, another problem is that you seem to be passing nothing to data in your ajax and expect it to return something into it. AJAX data is what you pass on to your server and what gets sent back is data that you have to work with, try this out instead:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "ajax/getTime.php",
function(data){
alert(data);
}
});
});
Good luck
Let's assume that you are trying to get the PHP time to POST to your page from an AJAX request.
include('connect.php');
$sql = "select * from timer";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$hours = $row['hours'];
$minutes = $row['minutes'];
//echo $hour.":".$minutes;
}
// $timeHour = $_POST['hours']; This isn't needed.
echo $hour.":".$minutes;
And created ajax POST request for another file:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "ajax/getTime.php",
success: function(data){
alert(data);
}
});
});
Set up your jquery like this. The datastring variable will be passed through like $_POST variables. So if you need to pass something, put it here. If not, make it an empty string at least.
var dataString = 'hours=' + $("field#id").val();
$.ajax({
type: "POST",
url: "getTime.php",
data: dataString,
success: function(data) {
//create jquery object from the response html
var $response=$(data);
//query the jq object for the values
var hours = $response.filter('div#hours').text();
var minutes = $response.filter('div#minutes').text();
$("label#hours").val(hours);
$("label#minutes").html(minutes);
}
});
Of course, this will only return the first result for hours and minutes. If you need all of them, you would just put the above into a lool. $response.filter('div#hours').each() or something.
Then, in getTime.php:
include('connect.php');
$sql = "select * from timer";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$hours = "<div id=\"hours\">".$row['hours']."</div>";
$minutes = "<div id=\"minutes\">".$row['minutes']."</div>";
echo $hours;
echo $minutes;
}
Let me know if you have more questions.

Categories