How to get ID value with jquery and send to PHP script? - php

I am trying to get an id value of a link with jquery then send that id to a php script (in this case sending it to a php sql query).
I have a link like this on the main page:
Category One
when this link is clicked, I would like jquery to grab the id value ('category1') and place it in a seperate php file that holds my db queries.
in other words the id value would be inserted into the query below once the link is clicked so I don't have to manually enter in the category part of the query:
SELECT * FROM maindb WHERE category="category1"
Any help on this would be great, thanks.

<a class='foo' id='category1'>Category One</a>
<a class='foo' id='category2'>Category Two</a>
<a class='foo' id='category3'>Category Three</a>
<script>
$(document).ready(function() {
$('.foo').click(function() {
// You might do:
window.location='somefile.php?id=' + this.id;
// or pass it as an argument to
$.getJSON('somefile', {id: this.id}, function(result) { alert('Success') });
});
});
</script>

Related

SQL Query creates buttons that one can click to 'hopefully' change DIV

I am failing hardcore with describing this but here it goes..
I have home.php, pretty much just:
<body>
<div id='leftColumn'>
<?php include ('includes/roomQuery.php')
</div>
</body>
Now,
roomQuery.php echos my sql column 'room_name' from table 'rooms' as follows:
echo "<td>$roomName</td>";
Any of the room links will take me to room.php and populate the page with more queries respective to $roomName via $_GET.
room.php is basically:
$get = $_GET['room'];
$query
while($row = $result->fetch_assoc()){
echo $query
This is working perfectly for what it is.
====================================
however, I am trying to make my site flow better, and have been trying out the jQuery .load function. So far I have changed roomQuery.php to:
echo "<td><button>$roomName</button></td>";
here is my jQuery to replace home.php #page with room.php #page:
$(document).ready(function(){
$("button").click(function(){
$("#page").load("room.php #page",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
});
When I click any of the buttons that roomQuery.php spits out, it replaces #page perfectly but I cannot grasp how/if I can send $_GET['room'] to room.php so that when #page is loaded, the information is still respective to the room I clicked on. If I change jQuery to
$("#page").load("room.php?room=CL%20124 #page"
Then #page is populated with the data specifically respective to room CL 124. Is it possible to post the button text that is output from roomsQuery.php to room.php #page when the button is clicked?
Yes, you can pass data into the .load() call as the second parameter.
Firstly, you need to work out how to get the room ID from the DOM into your jQuery call, maybe you could use a data attribute on the button element like this:
<button data-room-id="123">Click me</button>
Then use jQuery like this:
$("button").click(function(){
// define your room ID here, however you do it
var your_room = $(this).data('room-id');
$("#page").load(
"room.php #page",
{
room: your_room
},
function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
}
);
});
Edit: just noticed that you might actually be using the button's value as your room ID, if so, use this definition:
var your_room = $(this).val();
If you're expecting spaces or non-alpha numeric characters in this value, you might want to consider URL encoding it before you send it.

Passing a variable from within a while loop to a jquery

I have a web page that lists a number of companies from a MYSQL database, the listing just shows the name of the company. When user clicks on the company name a jquery accordion slider shows the rest of the information about that company.
When company name is clicked it also sends a request to a php script to log that a person has viewed that company's details.
My Problem
I want to send the ID for each record to the php script.
I have achieved this by including the accordion jquery code within the while loop that reads the output of the mysql query, but it generates a lot of unnecessary source code (i.e. for each company listed).
I need to include the jquery accordion code outside of the while statement.
How do I pass the id of each database record (i.e. company name) to the $.post in the jquery code, when it is outside of the while loop?
Accordion Jquery code
$(document).ready(function() { $('div.listing> div').hide(); $('div.listing> h4').click(function() {
$.post("/record.php", { id: "<?php echo $LM_row02[id]; ?>" } )
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
} }); });
Any idea most welcome.
When you create the HTML (I assume you do that in the loop as well), add a data-* attribute with the ID as value to the element and read that value with jQuery when the element is clicked on.
E.g. your resulting HTML will look like:
<h4 data-id="123">Some title</h4>
and your JavaScript:
$('div.listing > h4').click(function() {
$.post("/record.php", { id: $(this).attr('data-id') }, function() {
// ...
});
});
When you create the h4 element in html add a html5 data attribute like
<h4 data-companyid="<?php echo $LM_row02[id]; ?>">Company Name</h4>
Then use that companyid in your ajax call like
$.post("/record.php", { id: $(this).data('companyid') } );

Run PHP code when user clicks link and pass variables

I need to run a PHP code from external server when user clicks a link. Link can't lead directly to PHP file so I guess I need to use AJAX/jQuery to run the PHP? But how can I do it and how can I pass a variable to the link?
Something like this?
<a href="runcode.html?id=' + ID + '"> and then runcode.html will have an AJAX/jQuery code that will send that variable to PHP?
use something like this in you page with link
Some text
in the same page put this somewhere on top
<script language='javascript'>
$(function(){
$('.myClass').click(function(){
var data1 = 'someString';
var data2 = 5;//some integer
var data3 = "<?php echo $somephpVariable?>";
$.ajax({
url : "phpfile.php (where you want to pass datas or run some php code)",
data: "d1="+data1+"&d2="+data2+"&d3="+data3,
type : "post",//can be get or post
success: function(){
alert('success');//do something
}
});
return false;
});
});
</script>
on the url mentioned in url: in ajax submission
you can fetch those datas passed
for examlple
<?php
$data1 =$_POST['d1'];
$data2 =$_POST['d2'];
$data3 =$_POST['d3'];
//now you can perform actions as you wish
?>
hope that helps
You can do this with an ajax request too. The basic idea is:
Send ajax request to runcode.html
Configure another AJAX to trigger from that page
Considering, this as the markup
<a id="link" href="runcode.html'">Test</a>
JS
$("#link").on("click", function() {
$.get("runcode.html", { "id" : ID }, function(data) {
//on success
});
return false; //stop the navigation
});

Combine JQuery/PHP to log clicks into database?

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');
});

Php return data from database into a table which contains an onlclick button function

Basically i have php code which retrieves data from a database into a table, i have placed a button with an onclick function in each row of the table. the buttons aren't working cause its php(server side).
Could someone point me in the right direction to do this? retrieve data from Db put into a table with a button in each row with an onclick event.
thanks
Just use an anchor in each row and assign a class name for example :
<a class="delete_btn" href="index.php?action=fetchdta&id=1">Delete</a>
then use this jquery code on top of your page in a script tag :
<script>
jQuery(document).ready(function ($) {
$('.delete_btn').click(function(){
var urlt = $(this).attr('href');
$.ajax({
url: urlt,
success: function(data) {
//do Everything you want
}
});
return false;
});
</script>

Categories