Sort using php and jquery - php

I'm trying to re-order a HTML table when the user clicks on the table header. Here is all I can do, but still doesn't work.
in the HTML:
// onClick on table header
var par='ASC';
sort(par);
from: ajax.js
function sort(orderByType)
{
$.ajax({
url: "sort.php",
type: "get",
data: "orderby="+orderByType,
success: function(data){
alert(data);
$("t1").text(data);
}
});
}
sort.php
$con = mysql_connect("localhost","root","root");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$orderBy = $_GET['orderby'];
mysql_select_db("icrisis", $con);
$result = mysql_query("SELECT * FROM messages,user
where user_id = from_user
ORDER BY user_name".$orderBy);
while($row = mysql_fetch_array($result))
{
echo "<tbody><tr><td>"."•"."</td><td>".
$row["Time_Date"]."</td><td>".
$row["player_name"]."</td><td></td><td></td><tr><td></td><td colspan='4'>".
$row["msg_desc"]."</td></tr></tbody>";
}
mysql_close($con);
It doesn't see the $orderBy. And then I want to add the new order to my page - how could that be done?
Could the variable sent to function sort be dynamic, i.e. to be ASC or DESC on click?

You should try: tablesorter its for sorting tables. And you don't even need to use php with this solution just jquery. Hope its usefull.
To reply to your comment on Daan's anwser you could update tablesorter with ajax as described here.

I'm not sure if that is the cause of your problem, but I believe you miss a space.
The last line of your query is now:
ORDER BY user_name".$orderBy);
But should be:
ORDER BY user_name ".$orderBy);

As Daan said you are missing the space and that is probably the cause, however I will add:
You should probably check the result of the mysql_query() call because currently you don't know whether that is failing or not, which could be the cause of your problem. For example:
$result = mysql_query('SELECT ...');
if (!$result) {
die(mysql_error());
}
while($row = mysql_fetch_array($result)) {
//etc.
Also you shouldn't really be building the SQL statement based on strings that have come from the browser, as these cannot be trusted, and someone could currently add malicious SQL into what you are executing. See SQL Injection.
You could validate the string first which would be far safer, and is easy because you only have two possible values, e.g.
if (isset($_GET['orderby']) && $_GET['orderby'] == 'DESC') {
$orderBy = 'DESC';
} else {
$orderBy = 'ASC';
}

Related

Ajax request dataType json

I'm having troubles displaying a value in an input field. I did this in the past, and I haven't got a clue where my code goes wrong.
I have an input field with id="input" and a button with id="button". This is my jquery code:
$("#button").click(function() {
var uid = <?php echo $user['uid']; ?>;
$.ajax({
url: "php/fetchUserData.php",
method: "POST",
data: {
uid: uid
},
dataType: "json",
success: function(text) {
$("#input).val(text.bedrijfsnaam);
}
});
});
And here is the code on of the php/fetchUserData.php file:
<?php
include_once 'dbc.php';
if($_POST){
$uid = $_POST['uid'];
$sql = "SELECT * FROM users WHERE uid = '$uid'";
$query = mysqli_query($dbc, $sql);
$result = mysqli_fetch_assoc($query);
echo json_encode($result);
}
?>
UPDATE:
var_dump($result) does displays the associative array.
console.log(text) gives no result.
if I change dataType to text and echo out $result['bedrijfsnaam'] instead of json_encode($result) all goed well. The problem is that I want to load more than just the bedrijfsnaam (= company name).
UPDATE 2:
If I use the very same code but with another table in the database it does works. I really don't have a clue what can be the problem here...
I've been searching what could be the matter with the users table, and I notice cardinality is 0, although there are 4 rows in the table. In the other tables of the database, the cardinality value represents the number of rows. Could that have anything to do with this problem?
UPDATE 3:
Instead of the query:
$sql = "SELECT * FROM users WHERE uid = '$uid'";
I tried:
$sql = "SELECT bedrijfsnaam FROM users WHERE uid = '$uid'";
And it worked! Then I started adding column names, and all went well until a certain column: land (meaning country) a varchar column just like many others in the table.
What could be the reason this particular column causes the error to happen?
I know this became a phpmyadmin question instead of a php or jquery question. Should the question be moved to the sql part of the forum?
Assuming this is your actual code, your issue is likely stemming from not actually referencing and updating a field.
Something like this should be what you need:
$("#input").val(text.bedrijfsnaam)
I don't know anything about PHP and I don't think it matters. I think you got most part right. In success of your ajax request, set the text value of the input field.
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$("id='button'").text(text.bedrijfsnaam);
}
});
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$('#input').val(text[0]);
}
});
hmtl maybe better works than .val
You're wrong with your jquery selection of your div: you're missing an " in your code.
hope it will work

Jquery - parsererror - Unexpected end of JSON input

I'm trying to retrieve info from my database and display the information in a table generated by JQuery. I had done this before, and with using the exact same code it doesn't work anymore. I've looked up several other questions about this, but none of them has given me an answer.
This is the situation: An user select a value from the select menu, by selecting a value, that value gets sent and used to retrieve the right key for the right data. Then, by pressing a button the data should appear in a table. In order to accomplish this, I am using 3 ajax calls, one for populating the select box, one to send the right value, and another one to retrieve the needed data. The first two work perfectly, but not the last one.
My browser receives the data (see below) but the table does not appear and I'm getting a 'Unexpected end of JSON input' error. Can anyone help me out with this?
HTML/Jquery of the Ajax with the error:
function BekijkGegevens() {
$.ajax({
type: 'GET'
, data: {}
, dataType: 'json'
, url: "https://projectmi3.000webhostapp.com/webservices/bekijk.php"
, success: function (rows) {
$('#output').append("<table><tr><th> datum</th><th>stand</th></tr>")
for (var i in rows) {
var row = rows[i];
var datum = row[1];
var stand = row[0];
$('#output').append("<tr><td>" + datum + "</td><td>" + stand + "</td></tr>");
}
$('#output').append("</table>");
}
, error: function (JQXHR, TextStatus, ErrorThrow) {
console.log(JQXHR);
console.log(TextStatus);
console.log(ErrorThrow);
}
})
}
PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo "{data:" .json_encode($data2). "}" ;
}
?>
Thanks for any help that you can provide.
EDIT: Forgot to put my browser network, here it is.
http://puu.sh/uzI4f/a9ed1e0be5.png
EDIT2: I've split the PHP script into two seperate files, and tries to use a session variable to pass the needed key as suggested in the comments. Yet I am still getting the same error. Hereby the two new PHP files:
This one is used to send the key from Jquery to PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$_SESSION['teller'] = $teller;
}
?>
This one is used to get the needed information:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$sql2='SELECT sta_stand,sta_datum FROM stand WHERE teller_id ="' .$_SESSION['teller'].'"' ;
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = $result-> fetch_row())
{
$data2[]=$row;
}
echo json_encode($data2);
}
?>
First, some warnings (in accordance with this link):
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?
You should test against the session variable in your second script, which should look like this:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$teller = $_SESSION['teller'];
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo json_encode(['data'=> $data2]);
}
?>
Please note that I am also appending the 'data' properly to the JSON instead of just trying to "glue" (as said by Denis Matafonov) the JSON string together.
Dont try to glue data to string, like this:
echo "{data:" .json_encode($data2). "}" ;
Use simple
echo json_encode(['data'=> $data2]);
It should produce the same result if everything goes right, but wouldnt break up json if your $data2 is null
Declare your $data2 in the begginng, before if statement:
$data2 = [];
if (isset($_POST['teller'])) {
//do stuff and redefine $data2 or fill it;
}
//always echo valid json, event if no $POST["teller"] has arrived
echo json_encode(['data' => $data2]);

How to load large bulk records in MySql using jquery autocomplete

I am having nearly 80,000 records in a single table in MYSQL, I wanna make it display in the Autocomplete control.
The table structure is given below
Table_name
-ID
-Code
-codeType
In client side, I have made that autocomplete script like given below
var Cds = "";
$.ajax({
type: "POST",
url:"cdList.php",
async: false,
data:{
value1 : '9'
},
success:function(result){
Cds = JSON.parse(result);
}
});
$("#prin").autocomplete({
minlength : 3,
source: Cds,
autoFocus:true,
width:500
});
cdList.php
<?php
$con = mysql_connect("localhost","***","***");
if(!$con){
die("Error : ".mysql_error());
}
mysql_select_db("ananth",$con);
$value1 = $_POST['value1'];
$cd9 = array();
$result = mysql_query("select * from Table_name where codeType = '9' AND Code LIKE '$value1%'");
while($row = mysql_fetch_array($result)){
$cd9[] = $row['Code'];
}
echo json_encode($cd9);
?>
Even i set minLength in autocomplete control, still i am feeling damn slowness on getting the data. It took around 30 seconds. So what will be the work around to make it fast?
Look at this post abot like operator.
For your case i reccomend using query_caching flag and select only one column instead *
select Code from Table_name where codeType = '9' AND Code LIKE '$value1%'
LIKE queries have a potential for taking a long time...
for autocomplete purposes you could use MySQL's LIMIT and return only a chunk of the relevant entries.
check out this link:
http://www.w3schools.com/php/php_mysql_select_limit.asp
also you should probably index codeType column for a faster search.
hope this helps

How to get jquery autocomplete to display only terms that begin with the typed query

Context
I am adding autocomplete function to the search engine at motherpipe.co.uk.
I want it to only suggest terms that begin with the letters typed in by the user. For example, if the user types "lon" the function should return ten suggestions that begin with "lon".
I have about 50,000 terms in a local database
I have managed to get the autocomplete up and running, working with a separate php script that calls the database (sql).
Problem
My problem is that to begin with the top ten listings in the database (based on id) are shown regardless of what the user is typing in. It is only after the user types a further letter that suggestions appear correctly.
Question
How can I modify either jquery or the php code to make sure that ONLY terms that begin with what is typed in are returned (and then only the top ten terms in that subset based on the id.)?
HTML
<script type="text/javascript" src="/scripts/autocomplete/autocomplete/jquery.js"></script>
<script type="text/javascript" src="/scripts/autocomplete/autocomplete/jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
$("#tag").autocomplete("/scripts/autocomplete/autocomplete/autocomplete.php", {
selectFirst: false,
minChars: 2
});
});
</script>
PHP
<?php
$q=$_GET['q'];
$mydata=mysql_real_escape_string($q);
$mysqli=mysqli_connect('localhost','username','password','languages') or die("Database Error");
$sql="SELECT searchterms FROM topterms WHERE searchterms LIKE '$mydata%' ORDER by id";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
if($result)
{
while($row=mysqli_fetch_array($result))
{
echo $row['searchterms']."\n";
}
}
?>
With the new version of jQuery autocomplete when you use a URL as a source (like you do):
You must return JSON data:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP).
The GET argument you receive is 'term', not 'q'
The Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results.
The proper way to use real escape with mySQL in PHP is to use it after the connection has been established, in your case:
$q = $_GET['term'];
$mysqli = mysqli_connect('localhost','username','password','languages');
if (!$mysqli or $mysqli->connect_error) die("Database Error");
$mydata = $mysqli->real_escape_string($q);
$sql = "SELECT searchterms FROM topterms WHERE searchterms LIKE '$mydata%' ORDER by id";
$result = mysqli_query($mysqli,$sql);
$json = array();
if ($result and $result->num_rows > 0) {
while($row=mysqli_fetch_array($result)) {
$json[] = $row['searchterms'];
}
}
header('Content-Type: application/json'); // You can skip that because IE doesn't really like it
echo json_encode($json);

Check if value exists In MySQL row

I have a php variable: $foo
My MySQL table called data has the following structure:
id var header
1 zj3 http://google.com
I would like to check if $foo is all ready in var row.
If it is I would like to echo header ("http://google.com")
How would you approach this?
Thanks in advance, please ask if any clarification is needed!
Your query should be:
SELECT `header` FROM `data` WHERE `var` = '$foo'
This will return all the headers with a var value of $foo.
$db = mysqli_connect('localhost', 'username', 'password', 'database');
if($query = mysqli_query($db, "SELECT `header` FROM `data` WHERE `var` = '$foo'")){
while($row = mysqli_fetch_assoc($query)){
echo $row['header'];
}
mysqli_free_result($query);
}
first connect to the db
$query = mysql_query("SELECT var, header FROM data WHERE id='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($query)){
if($foo == $row['var']){
echo $row['header'];
}
}
EDIT: changed equality statement based on your edit
It's not difficult at all, If I understand correctly then this should help you.
// Query Variable / Contains you database query information
$results = $query;
// Loop through like so if the results are returned as an array
foreach($results as $result)
{
if(!$result['var'])
echo $result['header'];
}
// Loop through like so if the results are returned as an object
foreach($results as $result)
{
if(!$result->var)
echo $result->header;
}
are you asking if $foo matches any of the fields in data, or if $foo=some_field? Here for if you want $foo==var.
$foo='somevalue';
$query="SELECT id, var, header FROM `data` WHERE var='$foo'";
$result=mysqli_query($query);
if($result->num_rows==0)
$loc= 'http://google.com';//default value for when there is no row that matches $foo
}else{
$row=$result->fetch_assoc(); //more than one row is useless since the first header('Location: x') command sends the browser to a new page and away from your script.
$loc=$row['header'];
}
header ("Location: $loc);
exit;
ETA: since you've edited your question, it appears that you want to echo the header column if your search value matches your var column. The above won't work for that.
You just want to know if $var's value is anywhere in that column (any row(s))?
SELECT COUNT(id) FROM data WHERE var = ?;
The result will be the number of rows for which the field var contains the value of $var.
Here's a template for all the "does it exist" questions.
This is the only thing that actually worked for me so far and is not deprecated.
if ($query = mysqli_query($link, "SELECT header FROM data WHERE var = '$foo'")) {
$header = mysqli_fetch_assoc($query);
if ($header) {
// The variable with value $foo exists.
}
else {
// The variable with value $foo doesn't exist.
}
}
else {
// The query didn't execute for some reason. (Dammit Obama!)
}
WARNING!
Even if the variable DOES NOT EXIST the comparison between $query and mysqli_query() will always return TRUE.
The only way --which happened to me-- for the comparison to return FALSE is because of a syntax error in your query.
I don't know why it worked for the guy who wrote the accepted answer, maybe it's an update or maybe he had a syntax error and was so confident that he didn't check if it could ever be TRUE.
Here's the comment someone made for correcting his syntax:
"Add another ) before the { in the first line"
So, the accepted answer is WRONG!

Categories