Getting variable from mySql to jQuery via ajax - php

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.

Related

Getting data from php using ajax not working

I am trying to make an Ajax request and get the data from a PHP file; that is, a single row based on a where condition. I don't know how to extract the PHP array in JavaScript.
My Ajax code:
function loadData(Sno)
{
$.ajax({ //create an ajax request to
type: "GET",
url: "php/getgreetings.php?loadsno=" + Sno,
dataType: "json", //expect html to be returned
success: function(data){
response = jQuery.parseJSON(data);
alert (response.Greet_Name);
}
});
}
My PHP code:
require('db.php');
$loadsno = $_GET['loadsno'];
$query = "SELECT * from Greetings where greetsno=".$loadsno ;
$result = sqlsrv_query($conn,$query);
$data = array();
while ($row = sqlsrv_fetch_array($result))
{
$data[] = $row;
}
echo (json_encode($data));

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

Weird jQuery .post behavior

I have several clones of this script throughout my site and they work. The function is to enable liking, following, etc. (anything that requires a reference table to store the like, follows, etc.) The problem is with my liking function its running the .post 12 times. My follow script has the same jquery code but doesn't do this. So I resorted to checking my fave.php/unfave.php files, but I can't find any errors. Its the same as my follow.php/unfollow.php files. Can anyone spot or realize this odd behavior?
Basically I'm getting 12 entries into my DB. Why?
fave.js
$(document).ready(function(){
$(function(){
$(".fvspan").on("click", ".favebtn", function(){
var fvs = $(this).attr('id');
if(fvs)
{
$.ajax({
type: "POST",
url: "/mobile/inc/vdfave.php",
data: "fvs=" + fvs,
cache: false,
success: function(data){
$("span#" + fvs + ".fvspan").html("<img id='" + fvs + "' class='favebtn-un' src='/assets/faved.png' height='50px'>");
}
});
}
else { }
});
});
$(function(){
$(".fvspan").on("click", ".favebtn-un", function(){
var fvs = $(this).attr('id');
if(fvs)
{
$.ajax({
type: "POST",
url: "/mobile/inc/vdunfave.php",
data: "fvs=" + fvs,
cache: false,
success: function(data){
$("span#" + fvs + ".fvspan").html("<img id='" + fvs + "' class='favebtn' src='/assets/fave.png' height='50px'>");
}
});
}
else { }
});
});
});
vdfave.php
<?php
session_start();
//Make an SQL connection
include('/home/bfreak/www/inc/dbc.php');
$myself = $_SESSION['username'];
$ref = $_POST['fvs'];
$date = date("Y-m-d h:i:s");
if (!isset($_SESSION['loggedIn'])) { }
else{$myinfo = mysql_query("SELECT * FROM users WHERE username = '$myself'");}
while($myid1 = mysql_fetch_array($myinfo))
{
$myid = $myid1['id'];
//Insert form data into database with corresponding structure, in respective order, of SQL columns.
$fvd = "INSERT INTO faves (vid, usr, date) VALUES ('$ref', '$myid', '$date')";
if (!mysql_query($fvd, $con)) {die('Fatal Error: ' . mysql_error());}
}
mysql_close($con);
?>
Make sure you don't have duplicate usernames in users table in database. while loop may be running 12 times.
Change this:
mysql_query("SELECT * FROM users WHERE username = '$myself'");
to following:
mysql_query("SELECT * FROM users WHERE username = '$myself' LIMIT 1");
and check again.
I figured it out! i ran the js script in the loop. I took it out and it works!

Insert parsed JSON into html

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

Struggling to decode JSON in jquery ajax success callback from PHP script

I've been trying to find an answer for this for hours but really struggling.
I have a simple jquery Ajax function which sends data to a PHP script. The data is then used to conduct a MySQL query and the results are included as an array. I'm sending the array back using json_encode but can't work out how to display the array at the other end. I've posted the code below. The console.log is displaying Object {modules: Array[0]}
. There should be 3 entries in the array.
The PHP
<?php
include_once('../../dbconnect.php');
$name = $_POST['uploadname'];
$query = "SELECT * FROM marking_assignments WHERE name = '$name'";
$details = $conn->query($query);
$modules = array();
while ($row = $details->fetch_assoc()){
$modules[] = $row['unit'];
}
$dataarray = array("modules"=>$modules);
echo json_encode($dataarray);
?>
The jQuery
var uploadname;
$("#uploadname").blur(function(){
uploadname = $(this).val();
$.ajax({
url: "uploadnames.php",
type: "POST",
data: {uploadname: uploadname},
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
you should use:
var parsedData = jQuery.parseJSON(data);
and then:
console.log(parsedData)

Categories