Database filtering with javascript and AJAX - php

I've been reading and watching a lot of tutorials about javascript, jquery and AJAX but I can't seem to understand how to make a 'filter' like these guys from unlim500 have.
Their script allows you to just click on a brand and then the table gets filtered and refreshed (without reloading the page).
Live example on this page, click on Все марки:
http://www.unlim500.ru/results/
Can anyone lead me into the right direction?
How can I make such a filter?
index.php =
<a id="bugatti_link" href="#" database_id="Bugatti">Bugatti</a>
<script>
$("#bugatti_link").click(load_ajax);
function load_ajax(e) {
var link = $(e.target);
var vehicle_database_id = link.attr("database_id");
var ajax_params = {"brand": vehicle_database_id};
$.getJSON("query2.php", ajax_params, success_handler)
}
function success_handler(data) {
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
}
</script>
query2.php =
<?php
$host = "xx";
$user = "xx";
$db = "xx";
$pass = "xx";
$pdo = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$rows = array();
if(isset($_GET['brand'])) {
$stmt = $pdo->prepare("SELECT brand FROM cars WHERE brand = ? ");
$stmt->execute(array($_GET['brand']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>

The actual page you linked uses an anchor to create a link to some javascript. The way I have done this in the past (and imo a simpler way) is to make a link without href pointing to the same page (to avoid reload), and attach a click event to the link which will trigger your ajax call.
eg - HTML - the link to click
<a id="bugatti_link" href="#" database_id="2">Bugatti</a>
then in jquery
$("#bugatti_link").click(load_ajax);
function load_ajax(e) {
var link = $(e.target);
var vehicle_database_id = link.attr("database_id");
var ajax_params = {"id": vehicle_database_id};
$.getJSON("the/url/to/the/database/view", ajax_params, success_handler)
}
function success_handler(data) {
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
}
On the server you'll receive a GET request to the/url/to/the/database/view which will have a parameter called "id" with the value of "2" so you can fetch vehicle at row 2 and return whatever data you wanted from that vehicle.
Hopefully that gives some insight into how to turn a regular link into an ajax loader, which can be used to update the page without reloading it.
Some useful links about this sort of thing:
jQuery ajax calls
and more useful for this sort of usage, jQuery getJSON

You can use a jquery plugin for the sorting functionality. One of which is the tablesorter plugin
All you have to do is to download jquery and tablesorter.js then include them in your page. The code below assumes that you have jquery and tablesorter on the same folder where you have the file that you're running:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="tablesorter.js"></script>
Add an id to your table:
<table id="myTable">
Then use the tablesorter on document load:
<script>
$(function(){
$("#myTable").tablesorter();
});
</script>

Related

Trying to print a PHP mysql row with jquery .load into a div based on specific input into a form

I know the title is a bit long, here's what I am trying to do.
I have a div with the class .draggable2, I am trying to load a page named productLookup.php into it when the user submits a form. The form takes the "product name" then checks it in the database and returns certain information on that product. However, I am awfully confused as to where exactly my problem is, I don't know if I am not calling the function where .load() is correctly, or if I am not inputting the value into my productLookup.php page.
Here are the full details:
I have a script tag right after <body>, in it I have the declaration of:
function getR(id) {
$( document ).ready(function() {
$('.draggable2').load('productLookup.php?valueName=' + id);
});
}
Then right after it, I have:
$(document).ready(function() {
$('#submitProduct').click(function() {
var valueR = $('#nameValue').val();
getR(valueR);
});
});
Here I am declaring a function that will load productLookup.php with a value of whatever is inputted into the form before the button is clicked. I am new to these languages when it comes to this so I understand I may be wrong. The button has an ID of #submitProduct, the input area has an ID of nameValue. If I am correct, the .click() is supposed to call the getR function. So, why is it not working?
Here is the form I am using:
<form method = "POST">
<p>Product name: <input type="text" name="valueName" id = "nameValue" /></p>
<p><button type="submit" id = "submitProduct" >Input</button></p>
</form>
Now, here is my productLookup.php page:
<?php
$user = 'xxxx';
$pass = 'xxxx';
$db = new PDO( 'mysql:host=localhost;dbname=dbname', $user, $pass );
$productName = $_POST['valueName'];
$sql = "SELECT * FROM `products` WHERE `name` LIKE :valueName ";
$query = $db->prepare( $sql );
$query->execute(array(':valueName'=>$productName));
$info = $query->fetch(PDO::FETCH_OBJ);
$theName = $info->name;
print $theName;
?>
Please help me if you can, I am extremely confused as to what I am doing wrong, everything seems right. It's not making any sense to me why the value is not being inputted.
Another thing that leads me to believe that perhaps the error is in my productLookup.php is that when I input the url manually myself, for example: mywebsite.com/productLookup.php?valueName=ProductName it shows a blank page, technically it should show the info I am printing right?
.load() uses a GET query, not POST. So change:
$productName = $_POST['valueName'];
to:
$productName = $_GET['valueName'];
Also, you need to prevent normal submission of the form. Use preventDefault() in the click handler:
$(document).ready(function() {
$('#submitProduct').click(function(e) {
e.preventDefault();
var valueR = $('#nameValue').val();
getR(valueR);
});
});

jquery AJAX requests not updating php variable

I have a comics website, Hitting Trees with Sticks, that allows a user to get next, previous, or random comic id by pressing next or simply pressing arrow keys.
Since images are stored in a database, the only way for me cycle through these images on the client side was to store them in a javascript array, and store the php $imgid in a javascript variable as imgIndex. Then I could alter that index on the client side when they press keyboard keys.
When the user presses a key, I'm using pushstate to alter the imgid in the URL, but that's not actually updating the server side $imgid. I need to update the server side $imgid because I'm associating a liking function with each specific ID... but currently, the total likes associated with an img ID won't refresh/update when I press a key to get a new image.
My solution was to not only use the PushState to update the URL, but when a key is pressed, I use a $.post, and send the updated imgIndex to the php script.
Here are snippets:
KeyInput.php: This is the client-side javascript:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($site)) ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
$(document).keydown(function (e) {
var key = e.which;
var rightarrow = 39;
var leftarrow = 37;
var random = 82;
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
window.history.pushState(null, null, '.?action=viewimage&site=comics&id=' + imgIndex);
$.post('./templates/viewimage.php', { _newImgId : imgIndex },
function(data) {
//alert(data);
}
);
}
viewimage.php This is the file that originally gets the $imgid, then it calls the keyInput.php script to accept key input... that alters the javascript imgid. For testing purposes, I've tried using $.post and $.get AJAX to send the updated imgid, as you can see below, that's $newID = $_POST['_newImgId];. When I echo out $newID, it says it's not defined.
<?php
/*
Controls display of comic on the viewComic template
*/
include 'include/header.php';
global $site, $imgid;
$cat = (isset($_GET['cat']) ? ($_GET['cat']) : null);
$site = (isset($_GET['site']) ? ($_GET['site']) : null);
$title = (isset($_GET['title']) ? ($_GET['title']) : null);
$imgid = $_GET['id'];
include './scripts/keyinput.php';
$newID = $_POST['_newImgId];
echo $newID; //THIS SHOULD ECHO THE UPDATED ID, but it says it is not defined
Any thoughts?
Thanks!
I think the problem with your code is that you are using your Ajax code after the page has already loaded, while trying to change the $_get variables for the initial page load. AFAIK, you need to update the entire page for the "Facebook like" button to change it's ID. Another option would be to use an Iframe. From what I can see, the button's data-href attributes always leads to http://hittingtreeswithsticks.com/ - and that can only be changed by reloading the page using a different attribute.
If you don't mind loading a page for each picture, this can work out for you:
<!-- This is the Like button code -->
<div [...] data-href="http://www.hittingtreeswithsticks.com/<?php echo $_get['id']; ?>"></div>
and the address for this page would be: http://www.hittingtreeswithsticks.com/?id=PAGE_ID
EDIT
Using AJAX, you are calling for data from the backend to be used in the client side, without having to reload the entire page. This data can then be used to alter the code in the client side. In your code, the data is being sent back to you but you are not using it at all, that's why it doesn't work:
$.get('./templates/viewimage.php', { _newImgId : imgIndex },
function(data) {
// This is where you should make use of the data received
}
);
EDIT #2
If you want to dynamically change the Like button's url, take a look at this answer.
Here is a fiddle of the working example:
http://jsfiddle.net/TkFma/4/

Display data from database without refreshing (Javascript)

I'm trying to get the following code to work that is supposed to display data from my database when the following link is clicked: (without refreshing the page)
<a id="bugatti_link" href="#" database_id="Bugatti">Bugatti</a>
Unfortunately it's not working, it's not displaying anything and not giving an error.
index.php =
<a id="bugatti_link" href="#" database_id="Bugatti">Bugatti</a>
<script>
$("#bugatti_link").click(load_ajax);
function load_ajax(e) {
var link = $(e.target);
var vehicle_database_id = link.attr("database_id");
var ajax_params = {"brand": vehicle_database_id};
$.getJSON("query2.php", ajax_params, success_handler)
}
function success_handler(data) {
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
}
</script>
query2.php =
<?php
$host = "xx";
$user = "xx";
$db = "xx";
$pass = "xx";
$pdo = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$rows = array();
if(isset($_GET['brand'])) {
$stmt = $pdo->prepare("SELECT brand FROM cars WHERE brand = ? ");
$stmt->execute(array($_GET['brand']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>
you pass your json data to 'success_handler', but the data is not processed within that function
Note the addition of .error to your $.getJSON code. Should the request fail, this will tell you why. A response was received, but it might have an issue and this will tell you. See the note below as to why it might be failing silently.
Also, adding a $(document).ready wrapper around your code is best as it ensures the page has fully loaded before running the javascript inside. Depending on the browser and how nested the element is, it may or may not be ready for attaching events. In any regard, it's best to put it in the document ready to always be sure.
$(document).ready( function(){
$("#bugatti_link").click(function(e){
e.preventDefault();
var vehicle_database_id = $(this).attr("database_id");
var ajax_params = {"brand": vehicle_database_id};
$.getJSON("query2.php", ajax_params, function(data){
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
})
.error(function(data,msg,error){
alert( msg );
});
});
})
Important: As of jQuery 1.4, if the JSON file contains a syntax error,
the request will usually fail silently. Avoid frequent hand-editing of
JSON data for this reason. JSON is a data-interchange format with
syntax rules that are stricter than those of JavaScript's object
literal notation. For example, all strings represented in JSON,
whether they are properties or values, must be enclosed in
double-quotes. For details on the JSON format, see http://json.org/.

PHP No Reload Submit Value into MySQL Database (no return)

So what I am doing is trying to create a 'favorite' system. I want the user to click a button and the code on the page will submit a value into a MySQL Database. Does this need to the page need to reload if the only thing I am doing is submit and value. I am not pulling any information from the database on the button's click. Thank you:)
A great way to avoid the complexities of Ajax and cross-browser compatibility is to use Jquery!
In your non-reloading page, you can put this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script text="text/javascript">
$(function() {
$('#button_id').click(function() { //in place of "button_id" you need to put your button's id
submitInformation("some information you want to send");
});
});
function submitInformation(data1)
{
$.post(
"handle.php", //this is the name and location of your php page
{
"input_var_one":data1,
}
);
}
</script>
and in your handler php page (in this case called "handle.php")
<?php
$inData1 = $_POST['input_var_one'];
//after your mysql_connect and mysql_select_db
$query = "INSERT INTO `yourtablename` VALUES ('var1 whatever you want', '$inData1')";
mysql_query($query);
?>
Jquery handles the Ajax request for you!
If you do not use AJAX, the information must be sent to the server in order to get to a mysql database table and processed by php and that surely requires page reload.
you can use:
<script type="text/javascript">
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
function onthatbuttonclick(something)
{
window.xhr.open('GET', "somephp.php?click="+something, false);
window.xhr.send(null);
alert(window.xhr.responseText);
}
var somevar = "user 01";
</script>
<input type="button" onclick="onthatbuttonclick(somevar);" />
and in php:
<?php
// some query required code
// and yes... i does require some safety measures:
$val = mysql_real_escape_string($_GET['click']);
mysql_query("INSERT INTO `tabel` (`click`) VALUES ('".$val."')");
echo 'you cliked a button.';
?>
you should now see an alert box with the text: "you clicked a button.".

How do I use externalInterface to allow Flash to call javascript to update a value on the screen?

I have a Flash movie that is embeded in a PHP page. The PHP page displays a value to the user (the number of images they have uploaded). When the user uploads a new image I want the value on the PHP page to reflect the change without refreshing the page.
This value is retrieved from database using MySQL. So heres what Ive done so far -
On the PHP page where I want to show the value I have a div
<div id="content_info"><script type="text/javascript" src="getInfo.php?group= <?php echo($groupid); ?> "></script></div>
This calls an external PHP file that queries the database and outputs the result like this
Header("content-type: application/x-javascript");
//do the query with PHP and get $number and then output
echo "document.write(\" (".$number.")\")";
When the page loads for the first time the correct number shows in the div and so all works fine. The next step is to call something to update the contents of this div when the value changes. So I will set up externalInterface in flash to call a javascript function to do this.
This is where Im stuck, I want to be able to do something like this -
function ReplaceContentInContainer(id) {
var container = document.getElementById(id);
container.innerHTML = getInfo.php?type=new&group= <?php echo($groupid) ?>;
}
and call this by
ReplaceContentInContainer(content_info)
I realise this isnt going to work but can anyone show me how to get this result?
many thanks
group= <?php echo($groupid); ?> will be executed only when PHP creates the page. You should store that value inside a variable in the javascript. See if this works.
<div id="scriptDiv">
<script type="text/javascript">
<!-- store the group id -->
var groupID = <?php echo($groupid); ?>;
function getGroupID()
{
return groupID;
}
function updateValue(value)
{
document.getElementById("content_info").innerHTML = value;
}
</script>
<div id="content_info">
<!-- for initial value -->
<script type="text/javascript"
src="getInfo.php?group= <?php echo($groupid); ?> ">
</script>
</div>
</div>
Now you can use flash's URLLoader:
var ldr:URLLoader = new URLLoader();
var gid:String = ExternalInterface.call("getGroupID");
var req:URLRequest = new URLRequest("getInfo.php");
req.data = {type:"new", group:gid};
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.addEventListener(IOErrorEvent.IO_ERROR, onError);
ldr.load(req);
private function onLoad(e:Event):void
{
var data:String = URLLoader(e.target).data;
ExternalInterface.call("updateValue", data);
}
private function onError(e:IOErrorEvent):void
{
trace("ioError");
}

Categories