I have a problem with updating the data I display from my db. Initially, when the page opens I display the date corresponding to the current date but then the user can change the date by entering it in a text box and when he clicks update all the data displayed should be deleted and the data corresponding to the new date should be displayed. Right now I have a javascript function which deleted all the data in the div when the button is clicked. The div holds the data I want to change. But I don't know how to add new data into the div. I tried to add php code to look up the database for the data in the javascript function but I don't know how to add it to the text box.
function changedate()
{
document.getElementById("label1").innerText=document.getElementById("datepicker").valu e;
document.getElementById("selecteddate").innerText=document.getElementById("datepicker" ).value;
document.getElementById("teammembers").innerHTML = "";//empties the div(teammembers)
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
}
}
?>
}
You can use a combination of jQuery and AJAX to do this. Much simpler than it sounds. To see that this is the right answer for you, just view this example.
In the below example, there are two .PHP files: test86a.php and test86b.php.
The first file, 86A, has a simple selection (dropdown) box and some jQuery code that watches for that selection box to change. To trigger the jQuery code, you could use the jQuery .blur() function to watch for the user to leave the date field, or you could use the jQueryUI API:
$('#date_start').datepicker({
onSelect: function(dateText, instance) {
// Split date_finish into 3 input fields
var arrSplit = dateText.split("-");
$('#date_start-y').val(arrSplit[0]);
$('#date_start-m').val(arrSplit[1]);
$('#date_start-d').val(arrSplit[2]);
// Populate date_start field (adds 14 days and plunks result in date_finish field)
var nextDayDate = $('#date_start').datepicker('getDate', '+14d');
nextDayDate.setDate(nextDayDate.getDate() + 14);
$('#date_finish').datepicker('setDate', nextDayDate);
splitDateStart($("#date_finish").val());
},
onClose: function() {
//$("#date_finish").datepicker("show");
}
});
At any rate, when the jQuery is triggered, an AJAX request is sent to the second file, 86B. This file automatically looks stuff up from the database, gets the answers, creates some formatted HTML content, and echo's it back to the first file. This is all happening through Javascript, initiated on the browser - just like you want.
These two files are an independent, fully working example. Just replace the MYSQL logins and content with your own fieldnames, etc and watch the magic happen.
TEST86A.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "test86b.php", // "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
TEST86B.PHP
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'abcd1234';
$pword = 'verySecret';
$dbname = 'abcd1234_mydb';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE `first_name` = '$selStudent' AND `user_type` = 'staff'";
$result = mysql_query($query) or die('Fn test86.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<ul style="list-style-type:disc;">
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<li> ' . $row['first_name'] . ' ' . $row['last_name'] . ' -- UserID [' .$row['user_id']. ']</li>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</ul><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
Here is a more simple AJAX example and yet another example for you to check out.
In all examples, note how the user supplies the HTML content (whether by typing something or selecting a new date value or choosing a dropdown selection). The user-supplied data is:
1) GRABBED via jQuery: var sel_stud = $('#stSelect').val();
2) then SENT via AJAX to the second script. (The $.ajax({}) stuff)
The second script uses the values it receives to look up the answer, then ECHOES that answer back to the first script: echo $r;
The first script RECEIVES the answer in the AJAX success function, and then (still inside the success function) INJECTS the answer onto the page: $('#LaDIV').html(whatigot);
Please experiment with these simple examples -- the first (simpler) linked example doesn't require a database lookup, so it should run with no changes.
You want to output a literal JS statement with whatever you get back from php, basically:
document.getElementById("teammembers").innerHTML = // notice no erasing, we just
// overwrite it directly with the result
"<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
// so just show it!
echo $email_users; // think about this for a second though
// what are you trying to achieve?
}
}
?>"
This is a vast question, not very specific. Checkout more about AJAX requests - basically from javascript you will have a call to the server that retrieves your data.
This is a snippet from the javascript library jQuery :
$.ajax({
type: "POST",
url: "emails.php",
data: { user: "John" }
}).done(function( msg ) {
$('teammembers').html(msg);
});
hope this will give you a starting point
Related
I'm developing a kind of question search engine based on Course wise, Subject wise by entering the keyword or question.
Here I am querying the database based on search term against 3 tables namely table_one, table_two, and table_three. Code as follows
<?php
if(isset($_GET['submit']))
{
$query = $_GET['query'];
$query = htmlspecialchars($query);
$query = mysqli_escape_string($link,$query);
$searchTerms = explode(' ', $query);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "question LIKE '%$term%'";
}
}
$subject_id = $_GET['subject'];
$course_id = $_GET['course'];
$min_length = 1;
if(strlen($query) >= $min_length)
{
$res = "SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_one
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')
UNION ALL
SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_two
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')
UNION ALL
SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_three
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')";
$raw_results = mysqli_query($link,$res) or die (mysqli_error());
if(mysqli_num_rows($raw_results) > 0)
{
echo "<h3 style='text-align:center;color:#3366CC'><span style='color:#000000'>Search Results For : </span> $query </h3>";
while($results = mysqli_fetch_array($raw_results))
{
echo "<div class='content'>";
echo"<h4 id=".$results['id'].">" .preg_replace("/".preg_quote($query, "/")."/i", "<span class=\"highlight\">$query</span>", $results['question']) . "</h4>";
echo"<p id=".$results['id']."><span style='padding-left:20px'>option A : " .$results['option_a']."</span> <br><span style='padding-left:20px'> option B : ".$results['option_b']."</span><br/><span style='padding-left:20px'>option C : ".$results['option_c'].
"</span><br><span style='padding-left:20px'>option D : ".$results['option_d']."</span><br><span style='padding-left:20px'> option E : ".$results['option_e']."</span><br><span style='color:#253E66;font-weight:bold;padding-left:20px'>Correct Ans : ".$results['correct_ans'].
"</span><br><span style='padding-left:20px'>Question Year : ".$results['question_year']."</span><br><span style='padding-left:20px'>Contributor : ".$results['contributor']."</span><br />
<a onclick=addQuestion('".$results['id']."') href='#'><span class='button'>Add to Question Bank</span></a></p>";
echo "</div>";
}
}
else{
echo "<span style='height:21px;syle=background-color: #F1F0FF;font-size:25px;color:#CC0000'>Your search - $query - did not match any queries.</span> ";
}
}
}
?>
I'm Calling the following addQuestion() function when i click the Add to Question Bank link.
<script>
function addQuestion(val)
{
var conf=confirm("Are you sure you want to add this question to Question Bank")
if(conf){
//Here I Want some code to update my database.
}
}
</script>
The script above displaying confirmation box when i click the button,
My Question is,
After confirmation I want to insert my question into the new table in the database and display message like "Question added" in front of the question permanently as i know i can't write PHP inside Jquery function Any help may appreciated.
You can achieve this by including the ajax.
put the ajax code which may looks like the following:
if(conf){
$.ajax({
type: "POST",
url: "$$phpfilepath",
data: {param:'$$value'},
success: function(data) {
// do the message display code
}
});
}
Don't forget to include the jquery cdn link in the head tag of the html page.
you need to send an ajax request.
you need to send it either by a post or get method to a php script that will return json so you can be updated on the page with results.
the answer above has an example ajax script sent with a post method:
data needs to be sielized if you are submitting it via form or an array.
this should help you
http://www.w3schools.com/php/php_ajax_database.asp
https://api.jquery.com/serialize/
Onclick - You need to do that with ajax. So basically, you need PHP plus javascript involved. You can use Jquery of similar JS library for easy ajax support.
Just and example with jquery library version 1.11.2 how to include:
<head>
<script src="jquery-1.11.2.min.js"></script>
</head>
For example, if this is your input field you want to save and button for submitting:
<input id="title" name="title" />
<input type="submit" value="Save">
Change it to button and give it javascript save() function (can be any name you give).
<input type="button" onclick="save($('#title').val());" value="Save">
In this example, I added 1 param to that save function, which is supposed to grab a value from html input filed with id "title".
On this page, there that html is, you need to include mentioned jquery(or similar) library and also include piece of javascript function for generating ajax request, which is named "save" here.
If you included jquery library, you must call javascript function for saving your data before your tag:
<script type"text/javascript">
function save(){
$.ajax({
type: "POST",
url: "yourpath/yourfile.php",
data: {title: title},
success: function(data) {
alert("Ajax save executed!");
}
});
}
</script>
When javascript function you named save() will execute, it will send POST request to yourpath/yourfile.php
There, you can easily get your POST data by in yourpath/yourfile.php:
if(isset($_POST['title'])){
// do something with POST data, save in db.. (make sure to include security when inserting to db)
}
If you want to send it with GET, you easily replace POST with GET:
function save(){
$.ajax({
type: "GET",
and also in .php file you write:
if(isset($_GET['title'])){
// do something with POST data, save in db.. (make sure to include security when inserting to db)
}
I have a database table which I am trying to retrieve data from using JQUERY AJAX. When my first page loads it does a php call to a table and populates a select form element. - This works
I then want to select one of the options submit the form and have the row returned via Ajax.
Previously I had the script working with just PHP files but am having trouble getting it to work. When submitting the form my URL is changing:
http://localhost/FINTAN/testertester.php?name=Specifics.
I am not getting anything back. In addition when looking at my console I get a jquery not defined
factory (jquery). I can find the line in question in my jquery ui.js. Not sure if this is the issue or my code has caused the issue. I have cleard the firefox cache and due to the fact I have not had a successful AJAX call via jquery method am guessing it my code.
To get the code below I have mixed and matched a book and an online tutorial and many other sources and this is not my first attempt. Ideally I would like to output table row. However just getting a request working and knowing its not a conflict or compatability issue would makeme feel better and not hindered before I start
<script src="jquery/jquery-ui-1.11.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val;
}
}
$.post("addithandle1.php",
{
name:vname};
function(response,status){
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
}
}
</script>
</head>
<body>
<?php
include "config.php";
if (mysqli_connect_errno($con))
{
}
else
{
$result = mysqli_query($con, "SELECT * FROM script ");
echo " <Form method='post'> <label>Script :</label> <select id='name' name='name' >";
}
while($row = mysqli_fetch_array($result))
{
echo "<option value = '".$row['scriptname']."'>".$row['scriptname']."</option>";
}
echo "</select>";
echo "<button id='btn' class='btn-search'>Load Script </button></form>";
?>
</body></html>
This is my PHP file that I am trying to retrieve from
<?php
include 'config.php';
$batchtype2 = $_POST['name'];
$batchtype2 = mysqli_real_escape_string($con,$batchtype2);
$sql = "SELECT * FROM script WHERE scriptname = '".$batchtype2."' ";
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo '<tr><td>'.$row['scriptname'].'</td></tr>';
echo '<tr><td>'.$row['scripthours'].'</td></tr>';
echo '<tr><td>'.$row['scripttotal'].'</td></tr>';
}
}
mysqli_close($con);
?>
Thanks in advance for any help
By making the following corrections (you have some syntax issues as well as usage issues which should be revealed in your browser's console when you load this page) in your JavaScript/jQuery this will work like you expect -
Make sure to change this line -
var vname = $("#name").val;
to this -
var vname = $("#name").val(); // note the parentheses
in your function -
$(document).ready(function(){
$("#btn").click(function(e){
e.preventDefault(); // prevent the default action of the click
var vname = $("#name").val();
$.post("addithandle1.php", {name:vname}, function(response, status) { // POST instead of GET
// never use alert() for troubleshooting
// output for AJAX must be in the callback for the AJAX function
console.log("recieved data-------*\n\nResponse : " + response +"\n\nStatus : " + status);
$('#table').html(response); // put response in div
});
});
});
Now $_POST['name'] should get populated properly.
To get the table to appear in your requesting page first make sure that your PHP forms the table completely.
Add a div to your requesting page and modify the AJAX call above as shown.
<div id="table"></div>
Now, when you make a request the div on the requesting page will be updated with whatever comes back from the PHP script.
There are a couple of things about your script.
First make sure you write well structured code and that it is nothing in the wrongplace / broken.
You have in the $(document).ready(function(){ only the .click event of the button, but you left the ajax request outside, I imagine you did that so it will also make the ajax request in the first page load
The problem is that now it will only make it in the first page load, but not when you click the button, on clicking button you are only getting the value of name.
I recommend you to try something like this:
<script>
$(document).ready(function() {
// bind button click and load data
$("#btn").click(function(){
loadData();
return false; // prevent browser behaviour of the button that would submit the form
}
// load data for the first time
loadData();
};
function loadData() {
var vname = $("#name").val;
$.post("addithandle1.php", { name:vname }, function(response, status) {
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
});
}
</script>
A few notes:
I would recommend always putting jquery code inside $(document).ready since that guarantees that jquery was loaded before running it
By default a form that has a submit button that you click, will get the form submitted by the browser, if you use ajax, you should prevent that behaviour, either on the button click event or on form with onsubmit="return false".
I'm using jquery autocomplete on an input form 'city' but i would like the query in my 'autocity.php' file to only suggest cities in the pre selected country i.e. WHERE City LIKE '%$term%'" AND CountryID = '%$country%'. The form action submit uses a separate PHP file (create-business.php) for inserting the form data to the database so the usual $_POST['Countries_CountryId'] wouldn't work in the autocity.php. that's why i'm now using AJAX to post 'country' to autocity.php. Also it would be great to have a way to echo/alert/print_r from the the autocity.php file so i can confirm that the $_POST['$country'] from the ajax post reaches the autocity.php file.
I have two input boxes in the form
<pre>`
<form id="input" action="php/create-business.php" method="post">
<select name="Countries_CountryId" id="country">
<input type="text" id="city" name="City">`
</pre>
Here is the script from the form
<script>
$(function () {
var country = $("#country").val();
$.ajax({
type:"POST", url:"autocomplete/autocity.php", data:"country",
beforeSend:function () {
// alert(country);
}, complete:function () { // is there any need for this?
}, success:function (html) { // is there any need for this too?
}
});
$("#city").autocomplete(
{
source:'autocomplete/autocity.php'
})
});
</script>
And here is autocity.php
`
//database connection works fine and autocomplete
//suggestion works without the AND CountryID = '%$country%' part.
$country = "";
if (isset($_POST['country'])) {
$country = trim($_POST['country']);}
echo "window.alert($country);"; //This did nothing no alert
$term = $_REQUEST['term'];
$req = "SELECT City
FROM cities
WHERE City LIKE '%$term%' AND CountryID = '%$country%'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = array('label' => $row['City']);
}
echo json_encode($results);
?>`
So the question is basically:
1 - how can i use a text input from a form using AJAX in a .php file that queries a MySQL db that is not the submit form action .php file
2 - how can i alert the post variable from the PHP file when ajax is used to show that the php file recieves my ajax post. In my brief experience echo and print_r only work on form submit when the web page changes showing the result of my form submit ont the form action.
3- how is my syntax?
Thank you very much in advance for helping this novice out :D
Ok here is my update on things i've tried. I think i'm close. i'm using Jquery UI -
//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js
here is the script method 1:
$(document).ready(function () {
var country = $('#country').value();
alert(country + " complete");
$("#city").autocomplete(
{
source:'autocomplete/autocity.php?country='+country,
minLength:1
});
});
here is the script method 2:
$(document).ready(function () {
$('#city').autocomplete({
// source: function() { return "GetState.php?country=" + $('#Country').val();},
source:function (request, response) {
$.ajax({
url:"autocomplete/autocity.php",
//dataType:"json",
data:{
term:request.term,
country:$('#country').val()
},
success:function (data) {
response(data);
}
});
},
minLength:2
});
});
I like method 2 more since it will allow me to add more than one parameter.
Finally here is my latest autocity.php code
<?php
$term = $_REQUEST['term'];
$country = $_REQUEST['country'];
$req = "SELECT City
FROM cities
WHERE City LIKE '%$term%' AND CountryID = '%$country%' ";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = array('label' => $row['City']);
}
echo json_encode($results);
?>
I'm still totally stuck though. can anybody see the problem with the code? Ive looked everywhere online for the right syntax. Thanks again
For the first problem, your approach is essentially correct. You can bind to the blur event for a particular field and use your function to get that field's value and submit to the php script much in the manner that you are doing so. $.blur() is what you're looking for.
For the second problem the error_log function will write stuff to php's error log. IF you use print_r to dump variables to this log, make sure to set print_r's second argument to true to output the result as the return value.
So, here's the deal. I have an html table that I want to populate. Specificaly the first row is the one that is filled with elements from a mysql database. To be exact, the table is a questionnaire about mobile phones. The first row is the header where the cellphone names are loaded from the database. There is also a select tag that has company names as options in it. I need to trigger an onChange event on the select tag to reload the page and refill the first row with the new names of mobiles from the company that is currently selected in the dropdown list. This is what my select almost looks like:
<select name="select" class="companies" onChange="reloadPageWithNewElements()">
<?php
$sql = "SELECT cname FROM companies;";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)) {
echo "<option value=\"".$row['cname']."\">".$row['cname']."</option>\n ";
}
?>
</select>
So... is there a way to refresh this page with onChange and pass the selected value to the same page again and assign it in a new php variable so i can do the query i need to fill my table?
<?php
//$mobileCompanies = $_GET["selectedValue"];
$sql = "SELECT mname FROM ".$mobileCompanies.";";
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
echo "<td><div class=\"q1\">".$row['mname']."</div></td>";
}
?>
something like this. (The reloadPageWithNewElements() and selectedValue are just an idea for now)
Save the value in a hidden input :
<input type='hidden' value='<?php echo $row['cname'] ?>' id='someId' />
in your JavaScript function use the value from this hidden input field:
function reloadPageWithNewElements() {
var selectedValue = document.getElementById('someId').value;
// refresh page and send value as param
window.location.href = window.location + '?someVal='+ selectedValue;
}
Now again in your PHP file retrieve this value from url for use as:
$someVal = null;
if (isset($_GET['someVal']) {
$someVal = $_GET['someVal'];
}
see if this works!!!
The best option would be using AJAX.
reloadPageWithNewElements() is a function which calls a page of your own site which will return the data you would like to put in your table.
If you are using JQuery, AJAX is very easy to implement:
$.ajax({
url: '/yourPage',
data: { selectedCompany: $('.companies').val() },
success: function(result) {
//delete your tablerows
$(".classOfTable tr").remove();
//put the result in your html table e.g.
$('.classOfTable').append(result);
},
dataType: html
});
The browser will send a request to "/yourPage?selectedCompany=Google" or something
All you have to do is let this page print out only html (maybe even easier is to print only the tablerow (<tr>).
If you have any further questions, please ask.
I would use jQuery to do it.
first You need to add 'id' attribute to every option tag
<option id="option1">
<option id="option2">
and so on...
then with jQuery:
$('<option>').change(function() {
var id=$(this).attr('id');
...save data here (i.e: with ajax $.post(url, { selected_id: id}, callback }
});
The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston"
success: function(data){
alert('done');
});