$.get can't pass the data to the php file - php

When I used page=1 ,everything is OK.BUT if I changed
$.get("getajax.php","page=1" ,function(data){ }
to
$.get("getajax.php","page="+pageno ,function(data){ }
then the program return a false and "fatal error: Call to a member function fetch_assoc() on a non-object", I think this means the $result has problems.Thus , the $query has a problem?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<div id="showdata"></div>
<input type="hidden" id="currentresult" value="1" />
<button id="show">Load</button>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#show',function(e){
var pageno = $('#currentresult').val();
$.get("getajax.php","page="+pageno ,function(data){
pageno++;
$('#currentresult').val(pageno);
$('#showdata').append(data);
});
});
});
</script>
</body>
</html>
And the getajax.php
<!-- This is ajax data. -->
<?php
$con = mysqli_connect("localhost", "root", "", "maroon5");
$page=isset($_GET["page"])?$_GET["page"]:0;
$pageNo = $page;
$startLimit = ($pageNo-1)*2;
$query = "SELECT * from tour LIMIT $startLimit,2 ";
$result = mysqli_query($con,$query);
var_dump($result);
while($row = $result -> fetch_assoc()){
?>
<div>
<h4>
month:<?php echo $row["month"]; ?>day:<?php echo $row["day"]; ?>
</h4>
</div>
<?php
}
?>

The reason why $.get("getajax.php","page=1" ,function(data){ works is because it always sends 1 to your php, thus creating the sql query of SELECT * from tour LIMIT 0,2
However if you were to change to $.get("getajax.php","page="+pageno ,function(data){, page will get assigned pageno which increases dynamically every time the button is clicked thus creating different queries to the DB like:
first click: "SELECT * from tour LIMIT 0,2"
second click: "SELECT * from tour LIMIT 2,2"
third click: "SELECT * from tour LIMIT 4,2"
As you can see the second, or third click would be different. Not completely sure but this is most likely your case. One of these queries is not finding any results, thus throwing the error at fetch_assoc()

Try mysqli_error function to get real error
$result = mysqli_query($con,$query)or die (mysqli_error($con));

If your page if 0 then startLimit would be -2
Add a bit of logic here
$startLimit = ($pageNo-1)*2;
if($startLimit < 0)
{
$startLimit = 0;
}
Should work! Though not the perfect solution but would work

Related

How do I implement a like counter using PHP, jQuery and AJAX?

I am working on creating a like counter for quotes. I am trying to increment the like counter when the user clicks on the like button and display the number of likes.
Problems I encountered:
Like counter gets incremented when I refresh the page (Not because I am actually hit the like button).
I tried implementing jQuery for the updation of the like counter in real time but failed :(
I referred to all the QnA related to this couldn't find the desired solution. I went through this [question]PHP/MySQL Like Button, and made the necessary changes but now there is no updation in the database when I click the button.
This is the code for one quote.
<div class="testimonial text-sm is-revealing">
<div class="testimonial-inner">
<div class="testimonial-main">
<div class="testimonial-body">
<p id="q1">
<?php
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?></p>
</div>
</div>
<div class="testimonial-footer">
<div class="testimonial-name">
<button method="POST" action='' name="like" type="submit" class="like"><b>Like</b></button>
<?php
if(isset($_POST['like'])){
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
<label>
<?php
$link = mysqli_connect("localhost","root","","success");
$sql = "SELECT likes from voted WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?>
</label>
<button class="btn" id="clipboard" onclick="copyFunction('#q1')"></button>
</div>
</div>
</div>
How do I make the like counter implement when I click on the like button?
How do I implement jQuery and AJAX to this, so that the counter is updated without a page refresh?
Please pardon my poor code structure.
Thanks for any help.
P.S This how a single quote will look like
You need three things for an asynchronous setup like this to work:
Your back-end script to handle ajax requests
Your front-end page
Your JQuery script to send ajax requests and receive data
Your back-end PHP script would look something like this (async.php):
<?php
if(isset($_POST['get_quotes'])) {
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
}
if(isset($_POST['like'])) {
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
Your front-end page will include an element with an ID to hook onto with the JQuery, and a button with a class or ID to capture the click event (page.html):
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="core.js"></script>
<body>
<button id="increment-like" value="Like" type="button" />
<p id="like-count">
</p>
</body>
<html>
Finally, your JavaScript file should look something like this, for a basic ajax request using JQuery (core.js):
$(document).ready(function() {
// initially grab the database value and present it to the view
$('#like-count').text(getDatabaseValue());
$('#increment-like').on('click', function() {
incrementDatabaseValue();
});
});
function getDatabaseValue() {
$.post("async.php",
{
get_quotes: true
},
function (data, status) {
// check status here
//return value
return data;
});
}
function incrementDatabaseValue() {
$.post("async.php",
{
like: true
},
function (data, status) {
// check status here
// update view
$('#like-count').text(getDatabaseValue());
});
}
I haven't tested this code but it should be clear and detailed enough to get you on the right track.

How do I make my random MySQL query automatically refresh every 5 seconds

I have creating a little section on my webpage that changes randomly everytime the webpage opens. The code looks like this.
<div id ="quote-text">
<?php
mysql_connect("localhost", "xxxxxxx", "xxxxxxx") or die(mysql_error());
mysql_select_db("xxxxxxx") or die(mysql_error());
$result = mysql_query("SELECT * FROM quotes WHERE approved=1 ORDER BY RAND () LIMIT 1")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
echo "<img src=http://www.xxxxxxxxxx.com/images/".$row['image'] ." width=280px ><br>";
echo '<span class="style2">'.$row['quote'].'</span class>';
echo "<tr><td><br>";
echo "<tr><td>";
}
echo "</table>";
?>
</div>
What do I need to do to make this change every 5 seconds randomly withoutrefreshing the whole page?
thank you
You will need to make an AJAX call to change content on the page without refreshing.
Check out the W3Schools tutorial here: http://www.w3schools.com/ajax/ajax_intro.asp
Or even better use the mozilla tutorial:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
I'd say the most optimized solution would be to use a solution that makes use of both PHP, and javascript/Jquery.
First off it I would avoid to make an AJAX call to a PHP script every 5 seconds..
Instead you could make one call every X number of minutes and get a set of 12X images.
I would then use javascript, with setInterval to have the client change the image.
Halfway through, you can make another call to the PHP script to add new elements to your set of images, and remove the previous.
An approach like this would reduce overhead both clientside and serverside.
Update: Below a rough implementation of this method
Javascript:
<?php
if(isset($_GET['getBanners']))
{
header('Content-Type: application/json');
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("stackoverflow2") or die(mysql_error());
$json_rows = array();
$result = mysql_query("SELECT * FROM quotes WHERE approved=1 ORDER BY RAND () LIMIT 12;")
or die(mysql_error());
$element = 0;
while($row = mysql_fetch_array( $result )) {
$json_rows[$element] = $row['image'];
$element++;
}
print '{"dataVal":'.json_encode($json_rows).'}';
return;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
//alert('test1');
var randomBanners = new Array ( );
var currentBannerIndex = 0;
function readNewBanners(startElement, numElements)
{
$.getJSON('http://127.0.0.1/stackoverflow/Banner.php?getBanners=1', function(data) {
for (var i = startElement; i < data.dataVal.length && i<startElement + numElements ; i++) {
randomBanners[i] = data.dataVal[i];
}
});
}
function refreshBannerImage()
{
if(document.getElementById('banner') == undefined) return;
document.getElementById('banner').innerHTML = ("<img src='"+randomBanners[currentBannerIndex]+"'/>");
currentBannerIndex = (currentBannerIndex+1)%12;
}
$( document ).ready(function() {
readNewBanners(0, 12);
setInterval(function() {
readNewBanners(0, 12);
}, 60000);
setInterval(function() {
refreshBannerImage();
}, 500);
});
</script>
</head>
<body>
<div id="banner">
Banner Here
</div>
</body>
</html>
SQL:
create table quotes
(
image varchar(10),
approved int
);
insert into quotes values ('http://dummyimage.com/600x400/000/fff&text=1',1);
insert into quotes values ('http://dummyimage.com/600x400/000/fff&text=2',1);
insert into quotes values ('http://dummyimage.com/600x400/000/fff&text=3',1);
etc...
You need to use AJAX for that. I suggest you to use the jQuery or a similar framework. Here is a nice example of what you want How to update a specific div with ajax and jquery. Add a setInterval() call like in this post http://forum.jquery.com/topic/jquery-setinterval-function and you are done.

Creating an onChange select drop down with javascript and php but it's not working

What I am trying to do is create a drop down container of 32 different locations in Scotland and when one of the selections is selected, for example, Glasgow it should go to a URL which displays content such as heading, text, for each article in a div WHERE location = Glasgow.
I have no error messages or any sort of recognition that my code has worked as when I select one of the four on the drop down it does absolutely nothing.
Can come clean up and put right what I've done so far? I would be extremely greatful!
Here is my files which are being used:
header.php
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#location').change(function(){
//Retrieve Content from the back-end PHP page, and pass the ID selected
var url = 'location.php?location=' + $(this).val();
$('#txtHint').load(url);
});
});
</script>
</head>
<body>
<div id="header">
<div class="headerLeftContent">
<select id='location'>
<option href="Link to a dynamic page with all the content from glasgow" value="Glasgow">Glasgow</option>
<option href="Link to a dynamic page with all the content from x" value="x">x</option>
<option href="Link to a dynamic page with all the content from test" value="test">test</option>
<option href="Link to a dynamic page with all the content from edinburgh" value="Edinburgh">Edinburgh</option>
</select>
<div id='txtHint'></div>
</div>
</div>
</body>
</html>
location.php
<?php
$connect = mysql_connect('xxxxxx', 'xxxxxx', 'xxxxxx');
$select_db = mysql_select_db('xxxxxx');
$location = $_REQUEST['location'];
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
while($row = mysql_fetch_array($query))
{
echo $row['text'];
}
mysql_close($connect);
?>
And please any comments regarding 'SQL injection' or how 'mysql' should be 'PDO' are unwanted as I do understand this but I am simply testing at the moment and will amend this.
Thanks.
You seem to have a mistake concatenating your location name inside your MySQL query, and it's not matching anything (so nothing is echoed back). Change this:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
to
$query = "SELECT * FROM podContent WHERE location = '$location'";
(Unless you have stuff like .Glasgow. in your database...)
Then you have to call mysql_query($query) as Alon suggested.
You need to use mysql_query and pass the resource to the mysql_fetch_array function:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}

Cannot get my javascript/php onchange function to work

I have already made a post regarding this issue no longer than 2hours ago but I really need to get this finished ASAP.
What I am trying to do is create a drop down container of 32 different locations in Scotland and when one of the selections is selected, for example, Glasgow it should go to a URL which displays content such as heading, text, for each article in a div WHERE location = Glasgow.
Currently I do not have URL's for each location.
I the following message when I select a new option: "Load Result: success ||| 200 OK"
Can someone be so kind to provide me with the last piece to this frustrating puzzle?
Here is my files which are being used:
header.php
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#location').change(function(){
//Retrieve Content from the back-end PHP page, and pass the ID selected
var url = 'location.php?location=' + $(this).val();
$('#txtHint').load(url, function (response, status, xhr) { alert("Load result: " + status + " ||| " + xhr.status + " " + xhr.statusText);
});
});
});
</script>
</head>
<body>
<div id="header">
<div class="headerLeftContent">
<select id="location">
<option value="Glasgow">Glasgow</option>
<option value="x">x</option>
<option value="test">test</option>
<option value="Edinburgh">Edinburgh</option>
</select>
<div id='txtHint'></div>
</div>
</div>
</body>
</html>
location.php
<?php
$connect = mysql_connect('xxx', 'xxx', 'xxx');
$select_db = mysql_select_db('xxx');
$location = $_REQUEST['location'];
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
$result = mysql_query( $query, $connect );
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}
?>
Thanks.
Correct this
$query = "SELECT * FROM podContent WHERE location = ".$location;
Two things:
$query = "SELECT * FROM podContent WHERE location = '.$location.'"; has two additional dots. It should be $query = "SELECT * FROM podContent WHERE location = '$location'";.
Before using the value $location from the user, you should escape it with mysql_real_escape_string(). Note this function is deprecated, and will be removed on future versions of PHP. You should take a look into PDO and prepared statements.

refresh single select box on click with jquery

I've a select populated by a php query, that loads the nicknames of the users logged in a specific div, called “UserList”.
<div id=”UserList” name=”UserList”>
</div>
This select is placed in a php page, “userlist.php”, loaded by jquery. The php query works fine, so I've avoided writing here the db connection.
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>
</select>
My problem is that I need to reload only the select and refreshing it when a user clicks the select itself, so new users that enter the page are added by the php query and those that changed page are removed from the list. But whit every event that I tried the jquery loops, instead of activating the reload only once every time a user clicks the form and the first click event not even reload properly the php query.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#UserList").load('userlist.php');
$("#UserList").click(function() {
$("#UserList").load('userlist.php');
evt.preventDefault();
});
});
</script>
Thanks for your help.
I would suggest using AJAX to do this. AJAX allows you to query the web-server with out refreshing the entire page. This example
seems like almost exactly what you want to do.
Edit:
Put this inside your template:
<div id=”UserList” name=”UserList”>
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result))
{
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result);
?>
</select>
</div>
Then Change the Javascript
<script type="text/javascript">
$(document).ready(function() {
$("#User").click(function() {
$("#User").load('userlist.php');
});
});
</script>
And finally change the userlist.php file:
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>

Categories