Cannot integrate jQuery variable into php - javascript

I try to make a query from database to get the list of users based on their country using php/mysql and jquery.
I have a mysql query that extracts the countries form database in a select options field. After this, i put a jquery code to automatically get the table with users based on the selected country. This is how jquery code looks like:
<script>
$( "#tara" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += "<table class='table table-bordered table-striped'>" +
"<thead><tr><th><p><?php echo _('Tara');?></p></th></tr></thead>" +
"<tbody>" +
"<?php
$variabilatara = 182;
$test = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") ?>" +
"<?php while($row=mysql_fetch_object($test))
{
echo "<tr>";
echo "<td><p>$row->nume</p></td>";
echo "</tr>";
}
?>" + $( this ).val() + " ";
});
$( "#testare" ).html( str );
})
.change();
</script>
My question is: How to put the $( this ).val() into php instead of $variabilatara, so it will looks something like: $variabilatara = $( this ).val(); and the sql query will modify on change of selected country. Thank you!

What you are trying to do is called AJAX. Sounds complicated, but it really isn't. See these examples for a simplistic explanation. Do not just look at them -- copy/paste to your server and make them work. Change the values. See how it works - really very simple.
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Your code is a bit difficult for me to follow, but should be refactored something like this. (I am unsure where strTara figures in the code, but I'm sure you will be able to figure it out from here).
javascript/jQuery:
var strTara = <?php echo _('Tara');?>
$( "#tara" ).change(function () {
selVal = $(this).val();
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'variabilatara=' + selVal,
success: function(data){
var tblHead = "
<table class='table table-bordered table-striped'>
<thead><tr><th><p>strTara</p></th></tr></thead><tbody>
";
$( "#testare" ).html( tblHead + data );
}
});
});
another_php_file.php: (your PHP AJAX processor file)
<?php
$var = $_POST['variabilatara'];
$out = '';
$result = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") or die(mysql_error());
while($row=mysql_fetch_object($result)){
$out .= "<tr>";
$out .= "<td><p>" .$row->nume. "</p></td>"; //<== fixed
$out .= "</tr>";
}
$out .= '</tbody></table>'; //<== fixed
echo $out;
?>

Related

load same data with jquery tooltip

is that posible to load same data with jquery tooltip?
for example i have a data like this.
<div class="content"><span id="user_801130021">text1</span></div>
<div class="content"><span id="user_801130021">text2</span></div>
<div class="content"><span id="user_1301193710">text3</span></div>
the tooltip only showing for text1 and text3 but not showing data for text2, i think that because same id there.
here my js code
$(document).ready(function(){
// initialize tooltip
$( " span" ).tooltip({
track:true,
open: function( event, ui ) {
ui.tooltip.css("max-width", "100%");
var id = this.id;
var split_id = id.split('_');
var userid = split_id[1];
$.ajax({
url:'fetch_details.php',
type:'post',
data:{userid:userid},
success: function(response){
// Setting content option
$("#"+id).tooltip('option','content',response);
}
});
}
});
$(" span").mouseout(function(){
// re-initializing tooltip
$(this).tooltip();
$('.ui-tooltip').hide();
});
});
my fetch_details.php
<?php
$userid = $_POST['userid'];
$query = $db->prepare ("SELECT * FROM master_post WHERE id_master_post =".$userid);
$query->execute();
$html = '<div>';
while ($value = $query->fetch()) {
$information = html_entity_decode ($value['information']);
$dom = new DOMDocument();
#$dom->loadHTML($information);
$image = $dom->getElementsByTagName('img')->item(0)->getAttribute('src');
$html .= "<img src='".$image."' height='300px' width='250px'>";
}
$html .= '</div>';
echo $html;
?>
If they are not going to be unique as in your code, you can do different things.
Class
You can use class instead of id.
Use <span class="user_801130021"> instead of <span id="user_801130021">
You can access them by using basic jQuery selectors : $('.user_801130021')
HTML5 Data Attributes
Another option is using them as HTML5 data attributes which is so much better in my opinion. Their format is data-*.
<span data-user="user_801130021">
You can get data-user value by $('span').data('user') and change it by $('span').data('user', value)
For example, if you changed id to data-user, you must change var id = this.id; to var id = this.data('user');. Then everything will be work as it must.
i found the trick.
use looping number to create unique id.
here my code.
$np = 0;
while ($value = $query->fetch()) {
<div class="content"><span id="user<?php echo np++ ?>_801130021">text1</span></div>
}

Trying to set up mailto: link

I have a webpage that has a form to insert vendor data, once inserted the company name is the placed into a select box. when the company is selected a table is called with all the vendor information.
My problem is the
the vendor_email is called from a php script, is there a way to make the value of the id insert into a mailto: function.
<tbody id="records">
<td id="vendor_company"></td>
<td id="vendor_rep"></td>
<td id="vendor_email"></td>
</tbody>
<div class="row" id="no_records"><div class="col-sm-4">Plese select vendor name to view details</div></div>
here is my php and js code
<?php
include_once("Database/db_connect.php");
if($_REQUEST['empid']) {
$sql = "SELECT id, companyName, repName, venderEmail FROM vender_contact
WHERE id='".$_REQUEST['empid']."'";
$resultset = mysqli_query($conn, $sql) or die("database error:".
mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
my js code
$(document).ready(function(){
// code to get all records from table via select box
$("#vendors_data").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url:"getVendor.php",
dataType: "json",
data: dataString,
cache: false,
success: function(vendorData) {
if(vendorData) {
$("#heading").show();
$("#no_records").hide();
$("#vendor_company").text(vendorData.companyName);
$("#vendor_rep").text(vendorData.repName);
$("#vendor_email").text(vendorData.venderEmail);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
It's absolutely possible! You simply need to use .html() instead of .text().
Note that the mailto comes on the href attribute, which is unique to the <a> tag. As such, you'll want to place your inside of your <td id="vendor_email"></td>:
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
Which will render as something like:
vendorData = {};
vendorData.vendorEmail = 'test#test.com';
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="vendor_email"></div>
In addition to this, please be aware that your MySQLi is vulnerable to SQL injection. You should use prepared statements, and also ensure that your database user only has the required privileges in order to prevent this.
You can refer to this post for further information on how to prevent SQL injection in PHP :)
Hope this helps!
By using jQuery's .html() method you can insert html like so:
$( '#vendor_email' ).html( '' + vendorData.vendorEmail + '' );
By the way, I couldn't help but notice that you've spelled vendor as "vender" in venderEmail.

How to get value of checkbox from PHP and DOM

i need to know how on earth to get my checkbox value from PHP that is in a loop and also might be in DOM. I have to put that checkbox inside the loop to make it being shown on each row of databases. I tried to call it back using different method but none success. The last part is javascript but i don't have any clue how to do that.
My code for javascript index.php.
function ajaxSearchUpdater(p){
$("#result").show();
var x = $("#search").val();
var y = $("#edulevel").val();
var pagelim = $("#pagefpe").val();
var pagenumber = p;
var checkb = $(".sBorrow").val()
$.ajax({
type:'POST',
url:'userres.php',
data:'q='+x+'&e='+y+'&pagelim='+pagelim+'&pageno='+pagenumber+'&checkb='+checkb,
cache:false,
success:function(data){
$("#result").html(data)
}
});
}
$(document).ready(function(e) {
ajaxSearchUpdater(1); // fires on document.ready
$("#search").keyup(function() {
ajaxSearchUpdater(1); // your function call
});
$("#edulevel").click(function() {
ajaxSearchUpdater(1); // your function call
});
$("#pagefpe").click(function() {
ajaxSearchUpdater(1); // your function call
});
$('.sBorrow').on('change', function(){
var checkBorrow = $(event.target);
var isChecked = $(checkBorrow).is(':checked');
alert("test");
alert(isChecked);
alert('checkbox'+checkborrow.attr('id')+'is checked:'+isChecked);
});
});
$(document).ready(function() {
$('.sBorrow').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
});
});
My code for the checkbox in PHP userres.php
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter-blackice' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr>";
echo "<th>No.</th>";
echo "<th>No.Matric</th>";
echo "<th>Name</th>";
echo "<th>Programme</th>";
echo "<th>Title</th>";
echo "<th>Thesis Level</th>";
echo "<th>Serial Number</th>";
echo "<th>Availability</th>";
echo "<th>Select book (Max 3)</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
foreach($r as $row){
$sBorrow = $_SESSION['sBorrow'];
echo "<tr align='center'><td>". ($startrow+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['thesis_level'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td>
<form method='post'>
<input type='checkbox' name='sBorrow' id='sBorrow' class='sBorrow' value='". $row['serialno'] ."'>
</form></td></tr>";
$startrow++;
//echo $row['education_level'];
}
echo "</tbody>";
echo "</table>";
I don't know what to do since i'm calling that page from ajax and uhh how should i explain this.
You know index.php -> userres.php -> index.php using ajax.
for javascript on the bottom part is what i have done and i dont think its right. I tried to create one other document ready for this checkbox but still even alert not showing up. I'm confused. please help T_T

AJAX reload DIV

I want to reload my div names shoutbox:
echo '<div id="shoutbox"><ul>';
$results = $db->query($sql);
foreach ($db->query($sql) as $row) {
echo '<li>';
echo '<span class="date">'.date("d/m/Y H:i", strtotime($row['date_time'])).' </span>';
echo '<span class="name">'.$row['name'].' - </span>';
echo '<span class="message">'.$row['message'].'</span>';
echo '</li>';
}
echo '</div></ul>';
But i don't know how to do that with AJAX... sow the div has to reload when you klik the submit button and every 60 mili-seconds.
if someone can help me, it will be fine.
Michel is on the right track. You should get the data from php, and return json formatted data so that the client can update in javascript. Check out the jquery getJSON function: http://api.jquery.com/jquery.getjson/. Then you set that in a javascript "setInterval" function, like this:
setInterval(function(){
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "#shoutbox ul", {
html: items.join( "" )
}).appendTo( "body" );
});
}, 100);
This would reload the array of data every 100 miliseconds.

Ajax script loading/Displaying only once

This script displaying the dynamic content for once thereafter its not working
Here is the code:
$(document).ready(function(){
$('.getmore').on('click',function(){
var last_id = $(this).attr('id');
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/getmore.php',
data: 'last_id='+last_id,
beforeSend: function(){
$('.getmore').html('<img src="../images/loader.gif" alt="Loading..." />');
},
success: function(data){
$('.getmore').remove();
$('#comments').append(data);
}
});
});
});
Here is the complete php code:
<?php
mysql_connect('localhost','root','') or die('Error... Couldnt connect..');
mysql_select_db('mydb') or die('Error... Couldnt select the Db..');
$records = mysql_query(' SELECT * FROM `compare_post_comments` WHERE `post_id`=37 limit 5 ');
if(mysql_num_rows($records)){
echo '<div id="ajax_comment">';
echo '<ul id="comments">';
while($data = #mysql_fetch_array($records) ){
echo '<li>'.$data['comments'].'</li>';
$last_record = $data['sno'];
}
echo '<li class="getmore" id="'.$last_record.'">Get More</li>';
echo '</ul>';
echo "<span id='cmmnts'></span>";
echo '</div>';
}
?>
getmore.php code
<?php
if( ( isset($_POST['last_id'])!=null ) && $_POST['last_id']!="" ){
$last_id = $_POST['last_id'];
//echo "::".$last_id;
$qry = " SELECT * FROM `compare_post_comments` WHERE `post_id`=37 and sno > ".$last_id." limit 5 ";
//echo "::".$qry;
$comments = mysql_query($qry) or die('Error..');
if( mysql_num_rows($comments) ){
while( $data = mysql_fetch_array($comments) ){
echo "<li>".$data['comments']."</li>";
$last_id=$data['sno'];
}
echo "<li class='getmore' id='".$last_id."'>Get More</li>";
}else{
echo "<li class='nomore'>No More</li>";
}
}else{
echo "<li class='nomore'>No More</li>";
}
?>
ajax call working for once, thereafter its not clickable.
I dont have much knowledge about ajax and javascript, explanation is appreciated.
Try the deferred syntax of on instead:
$(document).on('click', '.getmore', function...
This will survive DOM changes. This answer presumes that your loaded data contains an object with class="getmore", as you are removing it from the DOM on success. If not you need to remove the remove as suggested by NewInTheBusiness, but probably replace it with empty() instead to remove the loading progress.
Note I have recently found problems with the version of on that only takes the event and function. In jQuery 1.10.3 it seems to not be firing when it should.
It's because you remove the getmore class after success.
Remove this line of code:
$('.getmore').remove();
Check your firebug console for any error
Remove this line $('.getmore').remove();
Delegate the click event to the element's static parent or to the document.
Try,
$(document).on("click",'.getmore', function( event ) {
});
Just try live or bind in-place of "on" :
$('.getmore').live('click',function(){
}
or
$('.getmore').bind('click',function(){
}

Categories