Can anyone help me fixing my issue?
How can I make my links work, which come by ajax?
I tried to write some links directly into the document and they worked pretty well, but the "imported" ones don't.
JSFiddle
-> res/ajax/search.php
<?php
$search = $_POST['search'];
if( $search != "" ) {
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('invoice');
$query = "SELECT * FROM profile";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for( $a=1; $a <= $rows; $a++ ) {
$query = "SELECT * FROM profile WHERE full_name LIKE '%$search%' AND id='$a'";
$result = mysql_query($query);
$array = mysql_fetch_array($result);
if($array != "") {
echo "<a href='#' class='address'>" . $array['full_name'] . "</a><br />";
}
}
}
echo "<a href='#' class='address'>currywurst</a><br />";
echo "<a href='#' class='address'>bratwurst</a><br />";
?>
Use:
$(document).on('click', '.address', function(){
alert('something');
});
Instead of:
$('.address').click(function(){
alert('something');
});
You should try binding handlers to ajax loaded content in your ajax callback. Try this:
$(document).ready(function(){
$('input[name="search"]').keyup(function(){
$.post('res/ajax/search.php',
{
search: $('input[name="search"]').val()
},
function(data) {
$('#search-preview').html(data);
// onclick moved to ajax callback function
$('.address').click(function(){
alert('something');
});
});
});
});
Related
as the title states I am trying to write a code that will update a boolean data in column (I called 'status') for a specific row. I used while loop in table to display the rows of new registered and where the status is NULL, I've put two buttons (accept, reject) each in td so they'll be displayed to each name, What I want is when the accept button clicked, it sets the status of its row in the table to 1, and when reject is clicked, same thing but sets 0 instead of 1.
I've did a lot of research over this but hit a road block after road block, so I really hope your help in this, many thanks!
Here is my code:
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc".$i."'>Accept</button></td>";
echo "<td><button name='sRej".$i."'>Reject</button></td>";
echo "</tr>";
$i++;
}
if (isset($_POST['sAcc'.$i])) {
$row['status'] = 1;
}
}
getStudent();
?>
</table>
First of all, you miss <form> element. Your form inputs are useless without it, or without ajax.
Secondly, your $_POST check will only check last item. Since after you exit loop $i is set to last value in the loop. So your example will only work on last item.
<button> will now send $_POST with one of indexes sAcc or sRej. And it's value will be ID of your entry.
<table id="sHold" style="border:none;">
<form method="post" action="">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>{$sId}</td>";
echo "<td>{$sName}</td>";
echo "<td><button type='submit' name='sAcc' value='{$sId}'>Accept</button></td>";
echo "<td><button type='submit' name='sRej' value='{$sId}'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
if (isset($_POST['sAcc']) && intval($_POST['sAcc'])) {
$user_id = (int) $_POST['sAcc'];
// Do the database update code to set Accept
}
if (isset($_POST['sRej']) && intval($_POST['sRej'])) {
$user_id = (int) $_POST['sRej'];
// Do the database update code to set Reject
}
getStudent();
?>
</form>
</table>
Tip: I assume you're beginner. I remade your code. But you dont need to put this code into function. Use functions to handle data retrieval for example. Dont use it to display html.
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table where status='NULL'";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['name'];
echo "<tr id='".$sId."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc' id='acc-".$sId."' onclick='approveuser(this.id)'>Accept</button></td>";
echo "<td><button name='sRej' id='rec-".$sId."' onclick='approveuser(this.id)'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
getStudent();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function approveuser(id){
trid=id.split('-')[1];
//alert(trid);
$.ajax({
url: "update.php",
type:"post",
data:{ val : id },
success: function(result){
//alert(result);
$('table#sHold tr#'+trid).remove();
alert('Updated');
}
});
}
</script>
//The code give below this update.php pge(ajax page)
<?php
$data=$_POST['val'];
$status =explode('-',$data);
$user_id=$status[1];
if($status[0]=='acc'){
$value=1;
}
elseif($status[0]=='rec'){
$value=0;
}
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
mysqli_query($conn,"update student_table set status='$value' where student_id=$user_id");
?>
I'm using jQuery autocomplete and trying to get it to go directly to the link when I click on suggestion or press enter. Here's the code I used:
<script>
$(function() {
$( "#search" ).autocomplete({
source: 'search.php',
select: function(event, ui) {
$(this).val(ui.item.value);
$(this).parents("form").submit(); // this will submit the form.
}
});
});
</script>
Then I have my php code for search: '
if ($_POST['search'] != null) {
//die("asdf: " . $_POST['search']);
$search = $_POST['search'];
$result = mysqli_query($con,"SELECT * FROM question WHERE text LIKE '%$search%'");
while($row = mysqli_fetch_array($result)) {
$text = $row['text'];
$question_id = $row['question_id'];
//die($search . " " . $text);
if ($search == $text){
header("Location: http://localhost/showstats.php?question_id=$question_id");
die();
}
echo "<br>";
echo " <a href=\"showstats.php?question_id=" . $question_id;
echo "\">$text</a> ";
//echo "<br>";
}}
The problem is when I click on suggestion it doesn't redirect to "showstats.php?question_id=$question_id", insted give me a blank result page.
And when I insert die($search . " " . $text); inside if statement it's showing me text 2 times, so I know it enters the body of it statement.
also worth escaping your sql...
$search = $_POST['search'];
$search = mysqli_real_escape_string($search);
$result = mysqli_query($con, "SELECT * FROM question WHERE text LIKE '%$search%'") or die(mysqli_error($con));
When you select a suggestion, the event occurs in the client so this code in your PHP is not really necessary:
if ($search == $text) {
header("Location: http://localhost/showstats.php?question_id=$question_id");
die();
}
Instead, when you select a suggestion, try triggering the redirection from jQuery:
<script>
$(function() {
$( "#search" ).autocomplete({
source: 'search.php',
select: function(event, ui) {
// This will redirect you to whatever URL is in ui.item.value:
window.location = ui.item.value;
}
});
});
</script>
It is because your headers are already sent, you have started your output, hence the redirect will not work.
Try buffering your output.
I have the following jquery script
$("li").click(function(){
var id = $(this).attr("id");
$.get("getData.php", {id: id}, function(data){
$("ul").after(data);
});
$(this).css("color","red");
});
and the getData.php file
<?php
include("db_config.php");
$ctgID = $_GET["id"];
if(isset($ctgID))
{
getData($dbh, $ctgID);
}
function getData($dbh, $ctgID)
{
try{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $dbh->prepare("select ctgid, ctgdescription from categories where ctgparentid = $ctgID");
$sql->execute();
$result = $sql->rowCount();
if($result >0)
{
echo "<ul>";
while($row = $sql->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
echo "<li class=\"subCtg\" id=\"". $row[0] . "\">" . $row[1] . "</li>";
}
echo "</ul>";
}
else
{
echo "1";
}
}
catch(PDOException $e){
die($e);
}
}
?>
Even if the above is working perfectly for the top level categories its not working when i am clicking on the subCtg class that is created. Can you help me please?
Use click event like this, that trigger on your existing and dynamic lists as well:
$('ul').on('click', 'ul li', function(){
.....
});
Take a look on this example
HTML:
<ul>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
JS:
$(document).on('click', 'li', function(e){
e.preventDefault();
e.stopPropagation();
$(this).parent('ul').after('<ul><li>new item click here </li></ul>');
});
Live demo: http://jsfiddle.net/jogesh_pi/YdByT/
Use Jquery Bind instead of click event ..
$( ".subCtg" ).bind( "click", function() {
alert( "User clicked " );
});
Jquery Bind
As you load new ul/li elements, you have to bind the "click"
event on them.
Try this:
PHP
...
while($row = $sql->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
echo "<li class=\"subCtg\" onclick=\"myFunc(".$row[0].");\" id=\"". $row[0] . "\">" . $row[1] . "</li>";
}
...
Javascript
$("li").click(function(){
var id = $(this).attr("id");
myfunc(id);
});
function myFunc(id){
$.get("getData.php", {id: id}, function(data){
$("#"+id).parent(ul).after(data);
});
$("#"+id).css("color","red");
}
An only-javascript approach could be:
function myFunc(id){
$.get("getData.php", {id: id}, function(data){
$("#"+id).parent(ul).after(data);
});
$("#"+id).css("color","red");
//create onclick event on new elements
$("li").each(function(){
$(this).click(myFunc($(this).attr("id")));
});
}
I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?
Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??
Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo
I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}
If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php
i have a auto suggest textbox witch generates li tags with a onclick event with a function but i have to pass a php variable to the function as parameter but i only want the variable value of the li the user clicked on and now i always get the last variable in the loop.
And i want the var test to be the value of $test = $row['t_product']; of the li the user clicks on
here is the code im using now:
if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false){
$search_term = $_POST['search_term'];
$customerid = $_SESSION['userdata']['t_customer_id'];
$conn = connect();
$sql = "SELECT * FROM Licenses WHERE customer_id = '$customerid' AND t_name LIKE '$search_term%'";
$query = sqlsrv_query($conn, $sql);
while(($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) != false){
$test = $row['t_product'];
?>
<script type="text/javascript">
var test = <?php echo json_encode($test); ?>;
</script>
<?php
echo '<li onclick="show(test)">', $row['t_name'], '</li>';
}
}
i hope i explained my problem well and hope that some wane can help me :)
Well, maybe you should do :
while(($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) != false){
$test = $row['t_product'];
?>
<?php
echo '<li onclick="show("'.$test.'")">', $row['t_name'], '</li>';
}
or
if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false){
$index = 0;
$search_term = $_POST['search_term'];
$customerid = $_SESSION['userdata']['t_customer_id'];
$conn = connect();
$sql = "SELECT * FROM Licenses WHERE customer_id = '$customerid' AND t_name LIKE '$search_term%'";
$query = sqlsrv_query($conn, $sql);
while(($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) != false){
$test = $row['t_product'];
?>
<script type="text/javascript">
var test<?php echo $index++ ?> = "<?php echo $test; ?>";
</script>
<?php
echo '<li onclick="show(test'.$index++.')">', $row['t_name'], '</li>';
}
}
Edit: removed json_encode and replaced it with quotes
solved it by passing the $test value as id to each li and in the js get it with
$test = $row['t_product'];
echo '<li onclick="show(this)" id="'.$test.'">', $row['t_name'], '</li>'
function show(id){
alert($(id).attr("id"));}