I am a newbie to PHP and MySQL development. I have built an app in Cordova using Visual Studio. The app works in the following way:
User selects a serial number from a drop down
After selecting a serial number, the data is showed on the chart
There is a toggle switch in the app, through which i am inserting the on or off state in the database based on the serial number
What I want to do?
When a user select any serial number, the switch will show the last ON or Off state based on Command Name of that particular serial number.
For this, I have generated a msql query and this query shows me the last command name of selected serial number
Below is my PHP code:
<?php
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
$cmd_Name = $_REQUEST['Command_Name'];
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
mysqli_close($con);
echo $cmd_Name;
?>
Below is my AJAX call in JavaScript:
$.ajax({
method: "GET",
url: "http://localhost:MyPort/server/toggleFetch.php",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = data;
if (dt.Command_Name == "On") {
$("#cmn-toggle-7").prop('checked', true);
}
else if (dt.Command_Name == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function (xhr, status, error) {
alert(xhr.responseText, status, error);
//toastr.success('Data not fetched', '', { timeOut: 2000 })
//alert('Error');
}
});
But it doesn't show the required result and gives error as shown in below image:
Updated Code:
Bellow is my php updated code
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
//$cmd_Name = $_REQUEST['Command_Name'];
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
mysqli_close($con);
echo $row["Command_Name"];
Bellow is the ajax
$.ajax({
method: "GET",
url: "http://localhost:MyPort/server/toggleFetch.php",
//dataType: "json",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = data;
if (dt == "On") {
$("#cmn-toggle-7").prop('checked', true);
}
else if (dt == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function (xhr, status, error) {
alert(xhr.responseText, status, error);
//toastr.success('Data not fetched', '', { timeOut: 2000 })
//alert('Error');
}
});
Now when running the code i am not getting any error but still i am not getting my required result i.e. the toggle doesn't change it's state
For more information please see the image bellow
I don't know what's the problem, any help would be highly appreciated.
This error means, that AJAX didnt send Command_Name via GET. You will have to check variable tData if it contains some value.
First step: dont send command_name with AJAX to PHP script (This causes Error on Line 5!!), it is not needed. Second step: in Php script you will have to change echo $command_name, to echo result from DB based on $dsn. So echo result from DB.
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $row["Command_name"]; //This should show ON/OFF state from DB to AJAX.
Related
How to make an animated table only animate when a new record is added to the database.
Ajax/Js (in index.php):
$.ajax({
url : 'Not sure what goes here?',
data : {Not sure what goes here?},
dataType : 'application/json', // Is this correct?
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
var newitem = function(response){
var item = $('<div>')
.addClass('item')
.css('display','none')
.text(response)
.prependTo('#scroller')
.slideDown();
$('#scroller .item:last').animate({height:'0px'},function(){
$(this).remove();
});
}
My php (latest.php):
include ('db.php');
$sql2 = "SELECT * FROM `feed` ORDER BY `timez` DESC";
$res2 = mysql_query($sql2) or die(mysql_error());
while($row3 = mysql_fetch_assoc($res2)){
$user = $row3['username1'];
$action = $row3['action'];
$user2 = $row3['username2'];
echo ''.$user.''.$action.''.$user2.'<br>'; // Needs to be a json array?
I can't get this to work, here's how the table operates http://jsfiddle.net/8ND53/ Thanks.
$.ajax({
url : your_php_file.php',
data : {data you'r going to send to server}, // example: data: {input:yourdata}
success: function(response) {
$('#table_id').append('<tr>'+response+'</tr>'); // response is the date you just inserted into db
}
});
in your_php_file.php:
add the item into db
echo that inserted data # if you echo, then you can catch this with ajax success function then you append it into your table.
try to fill as below:
$.ajax({
type: "post"
url : 'locationOfphpCode/phpCode.php',
data : {data you want to pass}, //{name: "dan"}
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
in your php code you need to receive the data you have passed from the ajax call:
<?php
$name = $_POST['name'];
...
?>
you may add some validations in your php code.
hope this will help you.
the example you have given is using setInterval(newitem, 2000)
so you have to call ajax function on some fixed interval.
I'm developing live auction site, with real-time bidding system. I'm using LONG POLLING when user bids on item. I've chose long polling because WebSockets are not yet very supported and NODEJS is to complicated for me to implement right now. So I'm stuck with this simle ajax long polling, which works great for about five bids.
So the problem is: Bidding works great for 5-6 item bids in 1 second intervals (I get instant response from server-ajax), but the 7th (click) on bid button this response-long polling hangs for about 16-22 seconds and then completes the request. At the end everything is updated in database and completed but after every 5-6 bids response/ajax call hangss for about 16-22 seconds.
How could I reduce this time, that everything should go smoothly no matter how many times user bids, without lag...
I'm using Apache/PHP/MySql on localhost/wamp
My code:
index.php
<script type="text/javascript" charset="utf-8">
var old_timestamp = <?php echo $old_timestamp;?>; //here i'm echoing last timestamp of auction
function waitForMsg(){
jq.ajax({
type: "POST",
url: "http://localhost/bid/comet/poll.php",
data: {"old_timestamp" : old_timestamp},
async: true,
cache: false,
success: function(data){
var json = eval('(' + data + ')');
if(json['msg'] != "") {
jq('#comet_display').html(json['msg']); //here I show ID of which auction item was bidded
}
old_timestamp = json['old_timestamp'];
setTimeout('waitForMsg()',100);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout('waitForMsg()',1000);
}
});
}
jq(window).load(function(){
waitForMsg();
jq("#a_loader").show();
var url = "http://localhost/bid/auctions-ajax"; // the script where you handle the form input.
jq.ajax({
type: "POST",
url: url,
data: {au978 : true},
async:false, //to sem dodal za časovni zamik
success: function(data)
{
jq("#a_loader").hide();
jq("#show-category").html(data); // show response from the php script.
},
error: function(result) {
jq("#show-category").html("Sorry, something went wrong. Please try again later.");
}
});
});
function bid(id){
var url = "http://localhost/bid/comet/update-auction.php"; // the script where you handle the form input.
var user_id=<?php echo $user_id;?>; //user id from session
jq.ajax({
type: "POST",
url: url,
data: {"auct_id" : id, "user_id" : user_id}, // serializes the form's elements.
success: function(data)
{
//it updates in user table its remaining number of bids
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Something went wrong. Click OK to refresh.");
}
});
}
</script>
poll.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/include/DEFINES.php');
require_once(CLASS_AUCTION);
require_once(CLASS_DB);
$a=new Auction();
$old_timestamp = $_POST['old_timestamp'];
$bidded_id=0;
$db=DB::getInstance();
$sql="SELECT timestamp, id FROM auction ORDER BY timestamp DESC LIMIT 1"; //desno doda tabelo kategorija
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result2=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result2 as $rez){
$current_timestamp=$rez['timestamp'];
$bidded_id=$rez['id'];
}
$stmt->closeCursor();
while($current_timestamp <= $old_timestamp){
usleep(1000);
clearstatcache();
$db=DB::getInstance();
$sql="SELECT timestamp, id FROM auction ORDER BY timestamp DESC LIMIT 1";
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $rez){
$current_timestamp=$rez['timestamp'];
$bidded_id=$rez['id'];
}
$stmt->closeCursor();
}
$response = array();
$response['msg'] = 'BID na avkciji: '.$bidded_id;
$response['old_timestamp'] = $current_timestamp;
echo json_encode($response);
}else{
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/errors/404.html');
}
?>
and the update-auction.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/include/DEFINES.php');
require_once(CLASS_AUCTION);
require_once(CLASS_USER);
require_once(CLASS_DB);
$u=new User();
$a=new Auction();
$auction_id=$_POST['auct_id'];
$user_id=$_POST['user_id'];
$date = new DateTime();
$timestamp=$date->getTimestamp();
$a->updateAuction($auction_id,$user_id,$timestamp/*,$bid_price,$bids_spent,$total_paid*/);
$u->updateUserBids($user_id);
}else{
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/errors/404.html');
}
?>
Thank you for viewing my problem!
Consider switching to WebSockets. It was designed to fix the long polling issue.
Ok, I have find a solution which fixes this 17-22 seconds LAG-HANGING problem. Now it's almost instant, regardless how many times you click. But I'm still not sure, if this is the best solution of long polling.
I'm posting it, if someone would have the same problem.
I've changed LONG POLLING function in my poll.php to this:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/include/DEFINES.php');
require_once(CLASS_AUCTION);
require_once(CLASS_DB);
$a=new Auction();
$db=DB::getInstance();
$sql="SELECT timestamp, id, last_username FROM auction ORDER BY timestamp DESC LIMIT 1";
$response = array();
while(1)
{
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)){
$current_timestamp=$result['timestamp'];
$response['msg'] = 'New BID';
$response['old_timestamp'] = $current_timestamp;
echo json_encode($response);
break;
}
sleep(3000);
clearstatcache();
}
}else{
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/errors/404.html');
}
?>
and now i'm polling in my index.php like this:
<?php
$db=DB::getInstance();
$sql="SELECT timestamp FROM auction ORDER BY timestamp DESC LIMIT 1";
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result2=$stmt->fetch(PDO::FETCH_ASSOC);
$old_id=0;
$last_timestamp=$result2['timestamp'];
?>
<script type="text/javascript" charset="utf-8">
var last_timestamp = <?php echo $last_timestamp;?>;
var old_timestamp=0;
function waitForMsg(){
jq.ajax({
type: "POST",
url: "http://localhost/bid/comet/poll.php",
async: true,
cache: false,
success: function(data){
var json = eval('(' + data + ')');
if(old_timestamp==0 || last_timestamp==old_timestamp){
}else{
if(json['msg'] != "") {
jq('#comet_display').html(json['msg']);
}
}
old_timestamp = json['old_timestamp'];
setTimeout('waitForMsg()',500);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout('waitForMsg()',1000);
}
});
}
jq(window).load(function(){
waitForMsg();
});
function bid(id){
var url = "http://localhost/bid/comet/update-auction.php"; //here I update auction and user's bids
var user_id=<?php echo json_encode($user_id);?>;
var user_name=<?php echo json_encode($user_name); ?>;
jq.ajax({
type: "POST",
async: true,
cache: false,
url: url,
data: {"auct_id" : id, "user_id" : user_id, "username" : user_name}, // serializes the form's elements.
success: function(data)
{
setTimeout('waitForMsg()',100);
var cnt = parseInt(jq(".db_bids").text());
if (!isNaN(cnt))
{
cnt--;
jq(".db_bids").text(String(cnt));
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Something went wrong. Click OK to refresh.");
}
});
}
</script>
I'm still developing this on localhost & will see how this behaves on real server with 100+ users.
If anyone have better and faster solution with LONG POLLING from databases, please let me know :)
I'm trying to do a Jquery Ajax search with multiple conditions, and this is my first time. I did some research and found ways to send data to a php file, however it's only with one variable. I'm not sure how to implement all of my 6 variables into data: data.
here they are:
var FromDate
var ToDate
var MusicStyles
var Locations
var FromPrice
var ToPrice
Now here is where I got stuck, I should do a post with some data. When I have multiple variavbles, can I do data: dataFromDate, dataToDate, dataMusicStyles,?
$("#SearchButton").click(function() {
var dataFromDate = 'dataFromDate='+ FromDate;
var dataToDate = 'dataToDate='+ ToDate;
var dataMusicStyles = 'dataMusicStyles='+ MusicStyles;
var dataLocations = 'dataLocations='+ Locations;
var dataFromPrice = 'dataFromPrice='+ FromPrice;
var dataToPrice = 'dataToPrice='+ ToPrice;
$.ajax({
type: "POST",
url: "do_search.php",
data: dataFromDate, dataToDate, dataMusicStyles, dataLocations, dataFromPrice, dataToPrice,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
});
Where the MySQL would look like this:
<?php
//if we got something through $_POST
if (isset($_POST['dataFromDate'])) {
include('db.php');
$db = new db();
// never trust what user wrote! We must ALWAYS sanitize user input
$word = mysql_real_escape_string($_POST['search']);
$word = htmlentities($word);
// build your search query to the database
$sql = "SELECT
events.ID,
events.EVENT_NAME,
events.start_datetime,
events.end_datetime,
events.VENUE_LOCATION,
events.ENTRANCE_PRICE,
venues.VENUE_NAME,
GROUP_CONCAT(music_styles.MUSIC_STYLE_NAME) AS MUSIC_STYLE_NAME
FROM events
INNER JOIN venues
ON events.VENUE_LOCATION = venues.ID
INNER JOIN events_music_styles
ON events.ID = events_music_styles.event_id
INNER JOIN music_styles
ON events_music_styles.music_style_id = music_styles.id
WHERE start_datetime >= '$phpFromDate'
AND end_datetime <= '$phpToDate'
AND ENTRANCE_PRICE >= '$phpFromPrice'
AND ENTRANCE_PRICE <= '$phpToPrice'
GROUP BY events.ID";
// get results
$row = $db->select_list($sql);
if(count($row)) {
$end_result = '';
foreach($row as $r) {
$result = $r['title'];
// we will use this to bold the search word in result
$bold = '<span class="found">' . $word . '</span>';
$end_result .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';
}
echo $end_result;
} else {
echo '<li>No results found</li>';
}
}
?>
I am 100% certain that it doesn't work like this, but I think I got it almost right. I would love it if someone could at least please let me know what I could do to fix the code.
Thanks!
You send it as an object, like so:
$.ajax({
type: "POST",
url: "do_search.php",
data: {dataFromDate : FromDate,
dataToDate : ToDate,
dataMusicStyles : MusicStyles,
dataLocations : Locations,
dataFromPrice : FromPrice,
dataToPrice : ToPrice
},
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html) { // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
Where the firs value is the key, and the second is the value, so {key: value} would be accessed on the server as $_POST['key'], which your values would be accessed the way you seem to want :
$_POST['dataFromDate']
Also, you don't need all those variables at the start, just use them directly in the object.
Try to concatenate your strings with a "," and explode them on the server.
I am currently using the JQuery ajax function to call an exterior PHP file, in which I select and add data in a database. Once this is done, I run a success function in JavaScript. What's weird is that the database is updating successfully when ajax is called, however the success function is not running. Here is my code:
<!DOCTYPE html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
</head>
<body>
<div onclick="addtask();" style="width:400px; height:200px; background:#000000;"></div>
<script>
function addtask() {
var tid = (Math.floor(Math.random() * 3)) + 1;
var tsk = (Math.floor(Math.random() * 10)) + 1;
if(tsk !== 1) {
$.ajax({
type: "POST",
url: "taskcheck.php",
dataType: "json",
data: {taskid:tid},
success: function(task) {alert(task.name);}
});
}
}
</script>
</body>
</html>
And the PHP file:
session_start();
$connect = mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$task = $_REQUEST['taskid'];
$uid = $_SESSION['user_id'];
$q = "SELECT task_id, taskname FROM tasks WHERE task_id=" .$task. " LIMIT 1";
$gettask = mysql_fetch_assoc(mysql_query($q));
$q = "INSERT INTO user_tasks (ut_id, user_id, task_id, taskstatus, taskactive) VALUES (null, " .$uid. ", '{$gettask['task_id']}', 0, 1)";
$puttask = mysql_fetch_assoc(mysql_query($q));
$json = array(
"name" => $gettask['taskname']
);
$output = json_encode($json);
echo $output;
Let me know if you have any questions or comments, thanks.
Ibelieve it runs but alert wont show because of error -
success: function(task) {alert(task.name);}
You have to decode JSON first with jQuery.parseJSON(), task is just a string
it shoudld look somthing like this
function(m)
{
var task = jQuery.parseJSON( m );
alert(task['name']);
}
Edit:
Ok ...
Try to use developer tools in your browser and place breakpoint on your success function, if it doesnt even lunch try to add error callback for your ajax call
error: function(xhr, exc)
{
alert(xhr.status);
alert(exc);
}
Edit2:
and there is your problem - your ajax is not only returning json data, but php warning too, and now I see where is your problem - you are fetching data after insert, delete
$puttask = mysql_fetch_assoc(mysql_query($q));
Now I feel bad for not noticing it sooner...
I am making a notification system similar to the red notification on facebook. It should update the number of messages sent to a user in real time. When the message MYSQL table is updated, it should instantly notify the user, but it does not. There does not seem to be an error inserting into MYSQL because on page refresh the notifications update just fine.
I am essentially using code from this video tutorial: http://www.screenr.com/SNH (which updates in realtime if a data.txt file is changed, but it is not written for MYSQL like I am trying to do)
Is there something wrong with the below code:
**Javascript**
<script type="text/javascript">
$(document).ready(function(){
var timestamp = null;
function waitForMsg(){
$.ajax({
type: "GET",
url: "getData.php",
data: "userid=" + userid,
async: true,
cache: false,
success: function(data){
var json = eval('(' + data + ')');
if (json['msg'] != "") {
$('.notification').fadeIn().html(json['msg']);
}
setTimeout('waitForMsg()',30000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout('waitForMsg()',30000);
}
});
}
waitForMsg();
</script>
<body>
<div class="notification"></div>
**PHP***
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET' )
{
$userid = $_GET['userid'];
include("config.php");
$sql="SELECT MAX(time) FROM notification WHERE userid='$userid'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$currentmodif = $row['MAX(time)'];
$s="SELECT MAX(lasttimeread) FROM notificationsRead WHERE submittedby='$userid'";
$r = mysql_query($s);
$rows = mysql_fetch_assoc($r);
$lasttimeread = $rows['MAX(lasttimeread)'];
while ($currentmodif <= $lasttimeread) {
usleep(10000);
clearstatcache();
$currentmodif = $row['MAX(time)'];
}
$response = array();
$response['msg'] = You have new messages;
echo json_encode($response);
}
?>
there is a problem with your javascript line below
url: "getData.php",
data: "userid" + userid,
async: true,
remove the = sign and try again.
i have not read the whole code but found this is the cause test and feel free to reply if still got more issues.
You're not re-executing the SQL statement in the loop so the value in "$row['MAX(time)']" is never going to change.
If you re-execute the query in the loop this example may work--but executing a query every 10ms is not going to be a very efficient way to implement real-time notification.
Also, if the PHP script runs longer then the time configured in php.ini (max_execution_time, 30 secs by default), you'll get an error.