Can we put php in jquery code? - javascript

I want to use php script in jquery code. Here I put php script in my jquery but my jquery function is not working then. Is it right way to put php script in a jquery function.
<script type="text/javascript">
$(function() {
var count2=1;
$('a#addTelefono').click(function() {
count2 +=1;
$('<p><div style="float:left;width: 100%;"><select name="product_id[]" ><?php $sql=mysql_query("SELECT * FROM tbl_product"); while($res=mysql_fetch_array($sql)){ echo "<option value='".$res['id']."'>".$res['product_name']."</option>";}?></select><input type="text" name="discount[]" placeholder="discount ' + count2 + '" style="margin-left: 8px;" id="discount_' + count2 + '" />%<img src="images/cross.png"></div></p>').fadeIn("slow").appendTo('#extendTelefono');
i++;
return false;
});
//fadeout selected item and remove
$('.remove').live('click', function() {
$(this).parent().fadeOut(300, function(){
$(this).remove();
return false;
});
});
});
</script>

You have to make it in two steps and separate your php code from jQuery for readability :
$sql = mysql_query("SELECT * FROM tbl_product");
while($res=mysql_fetch_array($sql))
{
$contents .= "<option value='".$res['id']."'>".$res['product_name']."</option>";
}
$('<select name="product_id[]" ><?php echo($contents); ?></select> .....');
Also, be carreful of caracters you have in $res['product_name'] : It can fail if you have a quote in your product name (so you must escape it).
Moreover, mysql_* is deprecated, see mysqli_* or PDO.

Related

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

jQuery and JSON: loop json array

I have an array in database:
a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}
So I unserialize with php and then encode it with json, code looks like following:
$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r ($unwp);
echo json_encode($unwp);
I get this on the page:
Array ( [1] => 1993 [2] => 1994 [3] => 1995 [4] => 1996 ) {"1":"1993","2":"1994","3":"1995","4":"1996"}
I need to loop it somehow with jQuery? so i can get 1993,1994,1995,1996 and so on.
I was testing jQuery.getJSON(), but cant figure out how exactly to use it?
All code together on the page:
<?php
$array = $_POST['inputarray'];
$str = serialize($array);
print $str . "\n";
$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r ($unwp);
echo json_encode($unwp);
?>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
jQuery(function ($) {
// Add children input fields
var childBlock = $('.block');
var countChildren = $('div.block div.row').size() + 1;
$('#addChild').live('click', function (e) {
e.preventDefault;
$('<div class="row"><input type="text" name="inputarray['+countChildren+']" id="inputarray'+countChildren+'" placeholder="inputarray['+countChildren+']">Delete</div>').appendTo(childBlock);
countChildren++;
});
$('#deleteChild').live('click', function (e) {
e.preventDefault();
if (countChildren > 2) {
$(this).parents('div.row').remove();
countChildren--;
var counter = 1;
$('input[name^="inputarray"]').each(function () {
$(this).attr('name', 'inputarray[' + counter + ']');
$(this).attr('placeholder', 'inputarray[' + counter + ']');
$(this).attr('id', 'inputarray' + counter);
counter++;
});
}
});
})(jQuery);
</script>
<form action="" method="post">
<div class="block">
<div class="row"><input type="text" name="inputarray[1]" placeholder="inputarray[1]"></div>
<input type="hidden" value="<?php echo $str; ?>">
</div>
<input type="submit">
</form>
Add a child
Thank you!
This could be done easily in PHP. Since I don't see any handlers for submit() or click() or anything that could suggest an ajax request.
And you also have the php in the same file, so why not simply loop with PHP and produce what you need?
echo "<select name='year'>";
foreach($unwp as $year) {
echo "<option value='{$year}'>{$year}</option>";
}
echo "</select>";
The above snippet will product exactly what you need.
Example
Edit
You're trying to generate a <select> right? If not, let me know so I can modify as required.
I would change
echo json_encode($unwp);
to
echo "<script> var fromPhP = ".json_encode($unwp). "</script>;
in this way you get json in variable and I saw you are using jquery so i would use $.each to loop it:
$.each(fromPhP ,function(index,item){
console.log(index,item);
});
Use $.getJSON like this:
$.getJSON("scriptname.php", function(data) {
html = '';
$.each(data, function(i, el) {
html += '<div class="block">' +
'<div class="row"><input type="text" name="inputarray['+i+']" placeholder="inputarray['+i+']"></div>' +
'<input type="hidden" value="'+el+'">');
});
$("form > div").delete();
$("form").prepend(html);
});

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(){
}

Hide table row with value of option box in wordpress with jquery

I have a table with an input field in a table row and an option boxe and I want, that the <tr> with the input field only appears when a specific value in the option box are selected. So far I have the following coding, it hides my <tr> with the input field, but never displays it again.
$script = <<< EOF
<script type='text/javascript'>
jQuery(document).ready(function($) {
$('#row_sports').hide(); //works
if($('#sel_rugby').is(':selected') || $('#sel_climbing').is(':selected')){
$('#row_sports').show();
}else{
$('#row_sports').hide();
}
});
</script>
EOF;
echo $script;
echo '<table border="1">';
echo ' <tr>';
echo ' <td>';
echo ' <select name="sports">';
echo ' <option>Baseball</option>';
echo ' <option id="sel_rugby">Rugby</option>';
echo ' <option>Soccer</option>';
echo ' <option>Sailing</option>';
echo ' <option id="sel_climbing">Climbing</option>';
echo ' </select>';
echo ' </td>';
echo ' </tr>';
echo ' <tr id="row_sports">';
echo ' <td>';
echo ' <input name="sports_cl_rg" />';
echo ' </td>';
echo ' </tr>';
echo '</table>';
BR & thx,
mybecks
<script type='text/javascript'>
jQuery(document).ready(function($) {
$('#row_sports').hide(); //works
$('select').change(function() {
if($('#sel_rugby').is(':selected') || $('#sel_climbing').is(':selected')){
$('#row_sports').show();
}else{
$('#row_sports').hide();
}
});
});
</script>
use change function too.. here it works
Try this code:
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function($) {
$('#row_sports').hide(); //works
$('select[name="sports"]').change(function() {
var trig = ["Rugby", "Climbing"]; // set elements here
if (trig.indexOf($(this).val()) > -1) {
$('#row_sports').show();
} else {
$('#row_sports').hide();
}
});
});
</script>
It would be better if you put id in all options or compare them by the text instead of id it will be event better. I mean use Climbing instead of sel_climbing. Also give id to select to access it as you may have many selects on the page. I changed it to work as you code but you can follow my recommendation if you like. Demo available here JsFiddle
$('select').change(function() {
alert($('#sports option:selected').text());
$('#row_sports').hide(); //works
if($('#sports option:selected').attr('id') == "sel_rugby" || $('#sports option:selected').attr('id') == "sel_climbing"){
$('#row_sports').show();
}else{
$('#row_sports').hide();
}
});​

Categories