Weird jQuery .post behavior - php

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!

Related

How can I select data from a json object in mysql/php?

I'm sending JSON to my server via jQuery's ajax method.
Here's my jquery, and im pretty sure this is fine:
function stuffs() {
this.fname = document.getElementById("fname").value;
this.lname = document.getElementById("lname").value;
this.email = document.getElementById("email").value;
}
$(function() {
function ajaxhelper(data){
//console.log(JSON.stringify(data));
//this returns "{"fname":"mike","lname":"smith","email":"a#a.a"}" which is what i expect
$.ajax({
url: 'postdb.php',
type: 'POST',
data: {data : JSON.stringify(data)},
success: function(data) {
console.log(JSON.stringify(data));
console.log("Success");
},
error: function(e) {
console.log(e);
}
});
}
$("form").on('submit', function(e){
e.preventDefault();
var data = new stuffs();
ajaxhelper(data);
//window.location = "postdb.php";
});
});
</script>
I get back an 500 server error. Here's my php code. (yes i'm only sending it an fname that i've preloading into my database, $con is valid i just didnt share the code to connect to my database)
$obj = json_decode($_POST['data']);
$sql = "SELECT * FROM testtable WHERE fname = \"$obj->{'fname'}\"";
$query = $con->query($sql);
I think my sql is incorrect due to the quotes? This is where im stuck.
Try using $obj->fname instead of $obj->{'fname'}.
Here is the correct syntax for your SQL Statement
$sql = "SELECT * FROM testtable WHERE fname = '".$obj->fname."'";

Post ajax to PHP - variable isn't being uploaded

I am trying to pass a variable from my ajax to my php script. I can't see to get it to work. It keeps on giving me NULL when I do a var_dump on the variable.
JQUERY:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: id
});
LinkUpload(id);
function LinkUpload(id){
$("#link-upload").dialog();
}
});
});
</script>
PHP:
$id = $_POST['id'];
$query = mysql_query("SELECT * FROM xcart_slideshow_slides where slideid='$id'")or die(mysql_error());
$sli = mysql_fetch_array($query);
$slide_id = $sli['slideid'];
$link = $sli['link'];
var_dump($id);
I need the $id variable to post so I can dynamically change the dialog box when the click function is activated.
EDIT:
So I have changed some of my coding:
Jquery:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.post(
"slide-show-link.php",
{ id: id },
function(data,status){alert("Data: " + data + "\nStatus: " + status); }
);
// alert(id);
LinkUpload(id);
});
function LinkUpload(id){
$("#link-upload").dialog();
}
});
I wanted to see if the data was in fact being passed so I threw an alert in the .post. This is the error I'm getting now:
I have tried passing plain text and echoing it back on the page but it fails. It is just not passing.
Try this -
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: { id : id }
});

Long polling with database data?

After a week of googling and search.I am hard to find even a single tutorial about long polling from a database table instead of from a flat text file named data.text. Currently, I write manually anything in data.text and it instantly appears in the browser.
This is the question: Long polling using database? is not answered properly even in StackOverflow. (I found a lot here but in vain.).Example of this is also here
filemtime alternative for MySQL
How can I modify getdata.php to make it enable for fetching data from database?
$sql=mysqli_query($database,"SELECT * FROM messages where time>=$curr_date ORDER by time DESC");
while($row=mysqli_fetch_array($sql)){
$messages=$row['messages'];
$id=$row['id'];
echo $messages;
}
Messages table is as follows
id fro to mesg time status last_modified
I am here listing an example.
In this example, three files are being used.
index.html
getdat.php
data.text
Is there any need to make a fourth file to get data from database(mysql)? if not, then what type of changes are necessary in the getdata.php or data.text to use dynamic data from database?
Here is my Javascript
<script type="text/javascript" charset="utf-8">
var timestamp = null;
function waitformsg() {
$.ajax({
type:"Post",
url:"getdata.php?timestamp="+timestamp,
async:true,
cache:false,
success:function(data) {
var json = eval('(' + data + ')');
if(json['msg'] != "") {
$("#messages").append(json['msg']);
}
timestamp = json["timestamp"];
setTimeout("waitformsg()", 1000);
},
error:function(XMLhttprequest, textstatus, errorthrown) {
alert("error:" + textstatus + "(" + errorthrown + ")");
setTimeout("waitformsg()", 15000);
}
});
}
$(document).ready(function() {
waitformsg();
});
</script>
Here is the getdata.php file
<?php
include("../model/includes/classes.php");
$filename='data.php';
$lastmodif=isset($_GET['timestamp'])?$_GET['timestamp']:0;
$currentmodif=filemtime($filename);
while($currentmodif<=$lastmodif){
usleep(10000);
clearstatcache();
$currentmodif=filemtime($filename);
}
$response=array();
$response['msg']=file_get_contents($filename);
$response['timestamp']=$currentmodif;
echo json_encode($response);
?>
I have done something very similar recently. I did use jQuery .ajax call instead of the generic XMLhttprequest but the idea is the same:
recentFunction(container, lastDate){
var lastDate = "";
return $.ajax({
type: "POST",
url: "getData.php",
cache: false,
data: { 'request': 'recent',
'param': lastDate },
dataType: "json",
success: function(data){
if(data != null){
$.each(data, function(key, value){
if(key == 0){
lastDate = value['date_added'];
}
var html = "some html here";
// append html to dom element here
// and delete any old items here if needed
});
}
},
complete: function(){
setTimeout(function(){recentFunction(container, lastDate)}, 7000);
}
});
}
in the getData.php file I have query with a where clause that gets any items from db that are more recent than last element. Default value for $lastDate is set to 0, so it returns all items if no date is submitted.
<?php
$lastDate = 0;
$recent = array();
$recentQuery = "SELECT id, date FROM someTable WHERE date > '" . $lastDate . "'";
$recentResults = $db->query($recentQuery);
while($r = $recentResults->fetch_array(MYSQLI_ASSOC)){
$recentMovies[] = $r;
}
echo json_encode($recentMovies);
?>

how to pass multiple values to a function in jquery to

I have this list of comments that i want to remove from database using AJAX, and fadeout from current view with Javascript.
I call this function removeComment() which sends ID of div to be removed to server ( ID is also row id in database )
The problem i have is, after i run the function first time, it stops working.
jquery code
function removeComment(PostId) {
var commentid = 'com' + PostId;
$(document).ready(function() {
$(commentid).fadeToggle('slow');
// send to php script
$.ajax({
type: 'POST',
cache: false,
url: 'actions/adminProcessor.php',
data: 'action=removeComment' + '&PostId=' + PostId,
success: function(done) {
alert(done);
}
});
}); // <-- Sorry, was missing a '}'
}
and below is the html of the comment list and how the functionis called
<div class="comments" id="com3">
<label><admin>UD</admin></label>Remove
<span>17/09/12</span>
<p>adfadfadfadf</p>
</div>
<div class="comments" id="com3">
<label><admin>UD</admin></label>Remove
<span>17/09/12</span>
<p>adfadfadfadf</p>
</div>
please i would like to know where i got it wrong
below is the php script
if($action == "removeComment"){
extract($_POST) ;
$query = "DELETE FROM comments WHERE id = '$cId'" ;
$result = mysql_query($query);
}
You should not wrap your behavior into a $(document).ready function. You should read more about what $(document).ready means. This code should work now:
function removeComment(PostId) {
var commentid = 'com' + cid;
var coms = document.getElementById(commentid);
$(coms).fadeToggle('slow');
$.ajax({
type: 'POST',
cache: false,
url: 'actions/adminProcessor.php',
data: 'action=removeComment' + '&PostId=' + PostId,
success: function (done) {
alert(done);
}
});
}

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