redirect not working in PHP - php

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.

Related

display the information of the person once selected autocomplete jquery

I am using jQuery autocomplete plugin to provide suggestions of names from the database. What I am trying to do is to display the information of the person once selected. Can someone give me an idea on how and where will I pass and get the id (primary key) of the selected person?
js
$('input[name="name"]').autoComplete({
minChars: 1,
source: function(term, response){
$.getJSON('names.php', { name: term }, function(data){
var arr = $.map(data, function(el) { return el });
response(arr);
});
},
onSelect: function(){
//get id -> show info
}
});
names.php
require 'con.php';
$term = $_GET['name'];
$arr = array();
$query = mysqli_query($connection,
"SELECT
id,
firstname,
middlename,
lastname
FROM mytbl
WHERE firstname LIKE '%$term%' ||
middlename LIKE '%term%' ||
lastname LIKE '%term%'");
while($row = mysqli_fetch_array($query)){
$arr[] = $row['firstname'] . " " . $row['middlename'] . " " . $row['lastname'];
}
echo json_encode($arr);
Thank you!
What you need to do is return multidimensional array from PHP script and handle it in jQuery script.
So your PHP snippet should look like this.
<?php
$arr = array();
while ($row = mysqli_fetch_array($query)) {
$name = $row['firstname'] . " " . $row['middlename'] . " " . $row['lastname'] . " " . $row['extension_name'];
$ar = array();
$ar['label'] = $name;
$ar['value'] = $name;
$ar['id'] = $row['id'];
$arr[] = $ar;
}
echo json_encode($arr);
Now jQuery code look something like this,
$('input[name="official_name"]').autoComplete({
minChars: 1,
source: function(term, response) {
$.getJSON('names.php', {
official_name: term
}, function(data) {
var arr = $.map(data, function(el) {
return el
});
response(arr);
});
},
select: function(event, ui) {
var id=ui.item.id;
console.log("Selected item ID => "+ id);
}
});
Above code returns multidimensional array with Name and ID. jQuery autocomplete expect label and/or value as key from returned array to display it in drop-down.
The label property is displayed in the suggestion listand the value will
be added into the textbox after the user selected something
from the list.
When you select any item you just have to use ui.item.id for accessing the id of the selected the item.

JQuery Sortable PHP to Database

So I've got 2 boxes. On the left I have a list of items pulling from the database which I can drag and drop to the right. This works great. I can't for the life of me work out how to get it to post the data for the list on the right and I think I've tried every example Google has to offer this week.
When I do a print_r($_POST); on the page this submits to, I get Array ( ) with nothing in it. It doesn't seem to be grabbing the ID's and serializing them.
Does anyone have experience with this see anything I'm missing?
<script>
$(function() {
$( "ul.droptrue" ).sortable({
connectWith: "ul"
});
$( "ul.dropfalse" ).sortable({
connectWith: "ul",
dropOnEmpty: true
});
$( "#sortable1, #sortable2" ).disableSelection();
});
$( "#sortable2" ).sortable({
axis: 'y',
handle : '.handle',
update: function (event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: 'setlists-edit-process.php'
});
}
});
</script>
<ul id="sortable1" class="droptrue">
<?php
$_GET['setlist_id'];
$sql = "SELECT material_id, material_name FROM material WHERE user_id=$session_id";
$result = mysqli_query($conn, $sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
?>
</ul>
<ul id="sortable2" class="dropfalse">
</ul>
Replace this:
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
with:
while($row = mysqli_fetch_array($result))
{
echo '<li id="material_' . $row['material_id'] . '">' . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
Sortable expects the ID to be in the format setname_number.
Moreover, your code outputs in the format id=abc (no quotations), and rather it should be id="abc" with surrounding quotes.

Jquery get from mysql works only first time

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

Imported Links don't work (AJAX)

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

.click jquery doesn't work if I wait without clicking on anything on the page

The weirdest thing. If I upload my files and start clicking on the link it works just fine. However if I go surf on another tab and then come back to it and click the link the .post or .click jquery doesn't seem to work. I only included excerpts of the code. Let me know if you need to see more code. Thanks!!
likeOnClick.php file
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="includes/js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".like").click(function() {
var data = $(this).attr('data-id');
$.post("updateLikes.php", {'id': data});
});
return false;
});
</script>
...
displayDBUsers.php
while($row = mysql_fetch_array($result))
{
?>
<?php $id = $row['uniqueid'];?>
<?php $finalID = "showdata" . $id ;?>
<?php echo "<br>FinalID: " . $finalID;?>
<?php echo "<br>ID: " . $row['uniqueid'];?>
<?php echo "<br>Name: " . $row['surname']; ?>
<?php echo "<br><a href class=like data-id=" . $id . ">Like (" . $row['likes'] . ")</a>"; ?>
<?php echo "<br><br>"; ?>
<?php
}
...
updateLike.php
if( $_POST['id'])
{
$unique_id = mysql_real_escape_string($_POST['id']);
$sql = "
UPDATE atable
SET likes=likes + 1
WHERE uniqueid=$unique_id;";
$result = mysql_query($sql);
if(!$result)
{
echo "Failed to retrieve record";
}
Please pay attention. return false; placed in different position:
<script type="text/javascript">
$(document).ready(function() {
$(".like").click(function() {
var data = $(this).attr('data-id');
$.post("updateLikes.php", {'id': data});
return false;
});
});
</script>
Put quotes around your attribute values:
echo "<br>Like";

Categories