What I am trying to accomplish is to pass the correct value from php to a jquery function. What is the proper way to get that value to my jquery function so that I can use it.
Here is an example of how I tried to pass the php variable to the javascript function. Of course that does not give the desired effect.
index.php
User starts typing in username and live search displays matching usernames in dropdown
<input type="text" class="form-control" id="keywords" placeholder="Search..." autocomplete="off">
getUsername.php
Username gathered from database and displayed to user in dropdown. (when user clicks on a username it will send the username value to jquery function, then queries database and displays the specified info to user). Obviously sending a php variable directly through a jquery function is not going to work, but what other workaround is there in jquery to grab that $row['Username'] value to pass to the jquery function (searchFilterUsername). EDIT: Actually, sending the value through the jquery function is exactly what was needed. The Selected answer is the correct way to send the values through the jquery function
foreach($results as $row){
<td class="searchTerm" data-username-id="'.$row['userName'].'" onclick="searchFilterUsername();">
}
functions.js
Need to be able to get that specific username to this jquery function, so that it can be sent to the database function to display proper selection back to user
function searchFilterUsername(page_num, userName) { //Username needs to be sent to this function somehow, so that I can store the proper value inside the variable $keywords
page_num = page_num?page_num:0;
var keywords = $('.searchTerm').data("username-id"); //Adding this will only allow the first item in the dropdown to be grabbed for the query
var keywords = userName;
alert(keywords);
$.ajax({
type: 'POST',
url: 'getData.php',
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.screenLoader').show();
},
success: function (html) {
$('#displayPage').html(html);
}
});
}
Now if I remove the value from the onclick="searchFilterUsername()" then I am able to grab the first value, but of course that will not work since the data is dynamic. It is a live search, (user types username into input box and dropdown appears with queried usernames) and when the user clicks on the username, it displays values in display div based off of that username selection. The live search ties into the pagination class which allows user to search through returned values. Thanks.
getData.php
getData.php grabs those $_POST values and sends them to the database query and then the searchFilter function is sent to the pagination class
if(isset($_POST['keywords']) && !empty($_POST['keywords']) && $_POST['keywords'] !== 'null'){
$keywords = $filter->filter($_POST['keywords']);
$usersSQL .= "AND users.userName LIKE :keywords ";
}else{
$keywords = '';
$usersSQL .= "AND users.userName LIKE :keywords ";
}
$query= "SELECT * FROM users WHERE stuff = :stuff $usersSQL";
class.pagination.php
$_POST Values sent to this pagination class to create pagination links
$paginationConfig = array('link_func' => 'searchFilterUsername');
I would suggest you to pass the values via some data-* attribute of each td.
foreach($results as $row){
echo '<td class="searchTerm" data-pagenum="'.$row['something'].'" data-username="'.$row['userName'].'">blah blah blah</td>';
}
And use delegation for those dynamic elements.
$(document).on("click", ".searchTerm", function(){
// Get the values via the data-* attributes
var pagenum = $(this).data("pagenum");
var keywords = $(this).data("username");
alert(keywords);
$.ajax({
type: 'POST',
url: 'getData.php',
data:'page='+pagenum+'&keywords='+keywords,
beforeSend: function () {
$('.screenLoader').show();
},
success: function (html) {
$('#displayPage').html(html);
}
});
});
Pass userName with onclick event called in td.
foreach($results as $row){
<td class="searchTerm" data-username-id="'.$row['userName'].'" onclick="searchFilterUsername(null,\''.$row['userName'].'\')">
}
As searchFilterUsername has first parameter is page_num and second is userName.
Hope this will be useful
All Code is good but you need to echo this line in getUsername.php like this
foreach($results as $row){
echo '<td class="searchTerm" data-username-id="'.$row['userName'].'" onclick="searchFilterUsername();">';
}
Related
Before we start I am fairly new to jquery and do not know most of the functions and capability, so I do not know if there is an easy trick to do this that I am missing.
I am having an issue where I am using a search function to display a table of results using Jquery, ajax and PHP. Once the results table is displayed from the search, I have a clickable link on the final row of the table. This link should get the data from the row you clicked on and set it to a $_SESSION in PHP. I can get the correct data fine, I just cannot separate out each <td> field individually. I wish to do this by adding in a comma or a symbol that I could use to identify each separate field once in PHP. This is an issue as I wish to put it into an array to auto-fill some input on the next page that you get redirected too. Can anyone help or point me in the right direction for this.
Jquery + ajax
$('#resultviews').on("click",".buttonaslink",function(){
var tabler = $(this).closest("tr").text();
tabler = ('tabler=' + tabler);
alert(tabler);
$.ajax({
type: "POST",
url: "rowsession.php",
data: tabler,
cache: false,
success: function(html){
$('#resultviews').html(html).show();
}});
return false;
});
PHP how results are displayed in the table from first ajax POST
while ($row = mysqli_fetch_array($view)){
$id = $row['companyId'];
$company = $customers[$id];
$company = ucwords($company);
echo "<tr><td class='tabled'>". $row['ip']."</td><td class='table'>". $row['Subnet']."</td><td class='table'>".$row['hostName']."</td><td class='table'>". $row['owner']."</td><td class='table'>". $company ."</td><td class='table'>".$row['siteName']."</td><td class='table'><button id='rowbtn' class='buttonaslink'>Edit</button> / <button id='rowdel' class='btnaslink'>del</button><tr>";
}
You can try this approach:
var tabler = $(this).closest("tr").find("td")
.map(function() {
return $(this).text();
})
.get()
.join(",");
It takes a value from every td element of the row and joins them with a comma. If you need to remove a trailing comma, you can use this code:
if(tabler.length) {
tabler = tabler.substring(0, tabler.length - 1);
}
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)
}
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 }
});
Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/
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');
});