jQuery - autocomplete doesn't display results from database - php

I am working with jQuery autocomplete plugin and this is my index:
<script>
$(document).ready(function(){
$("#tag").autocomplete({source: "./search.php?q="+ $("#tag").val()});
});
</script>
<form action="search.php" method="post" class="form-inline search">
<input type="text" id="tag" name="tag">
<input type="submit" class="btn" value="Search" />
</form>
in search.php which is in the same folder as index.php is following:
include 'config.php';
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$sql="SELECT * FROM tags WHERE tag LIKE '%$my_data%'";
$result = mysql_query($sql) or die(mysql_error());
if($result)
{
while($row=mysql_fetch_array($result))
{
echo $row['tag']."\n";
}
}
When I start typing, autocomplete doesn't offer me any suggestions. Also no errors in JS console. In the code is just displayed No search results..
The paths are set up correctly, the database connection as well.
Thus, where could be a problem?
Thank you

You don't need to use a query string on the src url of autocomplete.
Just write your src file without query string:
$("#tag").autocomplete({source: "./search.php"});
And in your php file you have to capture the term parameter:
$q = $_GET['term'];

Solved this way - in PHP file must be data returned in JSON:
while($row=mysql_fetch_array($data))
{
$result[] = $row['tag'];
}
echo json_encode($result);

Related

Loading data from MySQL and populating dropdown select with jQuery Mobile, PHP

I am developing a PhoneGap application that gets some information from MySQL Database. I am struggling when I try to open a HTML page that contains two select input that need to be populated on page load, each one with data from two different tables. I don't why, but they are not getting populated. Please, any help will be very welcome.
HTML CODE
<div data-role="content">
<p></p>
<form id="cname" align="left" action="post" data-ajax="false" >
<label for "id">Employee's Name:</label><br/>
<select name="id" id="id"></select><br/>
<label for "job_id">Job's Name:</label><br/>
<select name="job_id" id="job_id"></select><br/>
<input type="hidden" name="latitued" id="latitued" value="">
<input type="hidden" name="longitude" id="longitude" value="" >
<input type="hidden" name="goo_map_api" id="goo_map_api" value="">
<input type="submit" value="Clock-In" id="enviar_in" data-inline="true">
</form>
</div
Jquery Script both SELECTS
<script type="text/javascript">
$(document).ready(function(e){
var items="";
$.getJSON("get_emp.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.fullName+"</option>";
});
$("#id").html(items);
});
});
</script>
<script type="text/javascript">
$(document).ready(function(e){
var items="";
$.getJSON("get_job.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.job_name+"</option>";
});
$("#job_id").html(items);
});
});
</script>
PHP file get_emp.php
<?php
$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database);
$q = "select id, fullName from employees";
$sql = $mysqli->query($q);
$data = array();
while($row = mysqli_fetch_array($sql, true)){
$data[] = $row;
};
echo json_encode($data);
?>
PHP file get_job.php
<?php
$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database);
$q = "select id, job_name from jobs";
$sql = $mysqli->query($q);
$data = array();
while($row = mysqli_fetch_array($sql, true)){
$data[] = $row;
};
echo json_encode($data);
?>
One more time, I appreciate your time taking a look at this code trying to give me a hand.
Thank you.
Code looks okay to me. Have you set the correct header?
header('Content-Type: application/json');
echo json_encode($data);
At first glimpse the code looks all right. What did you have in the console? Is all the json data there? Otherwise try
$.each(data,function(index,item)
{
$('<option>').val(item.id).html(item.job_name).appendTo("#job_id");
});
Updates:
can you please try adding
error_log(print_r($data,1));
before
echo json_encode($data);
in get_emp.php and check the php_error.log to see if the data is populated on the server side when you load the page
I think it has todo with timing between DOM ready and executing the Jquery script.
In this case your script executes before the DOM is ready. If some objects you are refering to, arent ready yet in the DOM, thus JQuery cant find the object, then JQuery simply stops executing.

Show echo inside a DIV

I'm having a very annoying issue and I have no idea what I'm doing wrong. It has (again) something to do with loading in a page into a DIV.
I have made a form which can be used to update information into a database. This form and PHP code is in one file and is being loaded in one DIV. When I visit the page which is loaded into the DIV itself, everything is working fine and the database is being updated as it should.
Though, when the page is loaded into the page. When I press submit nothing happens. What I want to happen is that the echo, which is either "Success!" or "Error!" is being displayed in the same DIV as the page is loaded into. This is my code, I hope someone can help! some variables are in Dutch, excuse me for that.
if(isset($_POST['submit'])) {
include "database.php";
session_start();
$id = $_POST['id'];
$titel = $_POST['titel'];
$text = $_POST['text'];
$categorie = $_POST['categorie'];
$auteur = $_SESSION['sess_loginnaam'];
$laatst_aangepast = date("Y-m-d H:i:s");
$sql="UPDATE paginas SET id='$id', titel='$titel', text='$text', categorie='$categorie', auteur='$auteur', laatst_aangepast='$laatst_aangepast' WHERE id='$id'";
$result=mysql_query($sql);
if($result){
echo "Success!";
?>
<META HTTP-EQUIV="refresh" content="2;URL=index.php">
<?php }
else {
echo "Mislukt!";
}
}
else {
include "database.php";
$id = $_GET['id'];
$sql="SELECT * FROM paginas WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
<form name="form1" method="post" action="">
ID:
<input name="id" type="text" id="id" value="<? echo $rows['ID']; ?>" size="2"></div> Titel:
<input name="titel" type="text" id="titel" value="<? echo $rows['titel']; ?>" size="50%"> Categorie: <select name="categorie"><option value="Paginas">Pagina's</option>
</select>
Tekst:
<textarea name="text" type="text" id="text" rows="31" cols="79"><? echo $rows['text']; ? ></textarea>
<button type="submit" name="submit">Edit!</button>
</form>
And here is the code I use to load this page into the DIV:
$("#edit").on('click',function(){
$('#content').load($(this).attr('href'));
});
So how can I manage to display the echo into the same DIV? :)
$.load is equivalent to $.get whereas your php code detect $_POST, that's way there is no response.
You can change your js code to
$("#edit").on('click',function(){
$.post($(this).attr('href'), YOUR_FORM_DATA_HERE, function(data){
//update your page here with response
});
});
See $.load - jQuery Doc

allocate text value submitted by a form to a variable after clicking submit button

I want to store the text value submitted by clicking the submit button of a form, in a variable, so that I can use that variable for further querying the DB.
My Code:
<?
if($submit)
{
mysql_connect("localhost:3036","root","root");//database connection
mysql_select_db("sync");
$order = "INSERT INTO country (id,country) VALUES ('44','$submit')";
$result = mysql_query($order);
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
}
?>
<html>
<title>form sumit</title>
<body>
<form method="post" action="">
<input type="text" name="id" value="<?=$submit;?>"/>
<input type="Submit" name="submit" value="Submit">
</form>
</body>
</html>
//In real case, the form has elements with radio button containing values from a DB QUERY,
I wanted to use the selected item from the form to process another DB query in the same page...
Thanks in Advance
Try this -
<?php
$submit = $_POST['id'];
if($submit)
{
//your code is here
echo $submit;
}
?>
<html>
<title>form sumit</title>
<body>
<form method="post" action="">
<input type="text" name="id" value="<?php echo $submit; ?>"/>
<input type="Submit" name="submit" value="Submit">
</form>
</body>
</html>
Submitted form data automatically gets allocated to a variable ($_POST, in your case). If you want longer-term storage, consider using the $_SESSION variable, otherwise the submitted data is discarded upon script termination.
Please clarify your question, as I'm not quite sure what you are trying to achieve here.
In a normal workflow, you would first check if your form has already been processed (see if $_POST has any data worth processing), then query the database for whatever data you need for your form, then render the actual form.
As promised, here's a hands-on sample:
<?php
if ($_POST['ajax']) {
// This is a very trivial way of detecting ajax, but we don't need anything more complex here.
$data = workYourSQLMagicHere(); //data should be filled with the new select's html code
print_r(json_encode($data));
die(); // Ajax done, stop here.
}
/* Your current form generation magic here. */
?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
// This should probably go into a separate JS file.
$('#select1').change( function() {
var url = ''; //Here we're accessing the page which originates the script. If you have a separate script, use that url here. Local only, single-origin policy does not allow cross-domain calls.
var opts = { ajax: true };
$.post(url, opts, function(data) {
$('#select2').replaceWith( $.parseJSON(data) ); //Replace the second select box with return results
});
});
</script>
<select id="select1"><?=$stuff;?></select>
<select id="select2"><?=$more_stuff;?></select>

Database Insertion using ajax , not working

I'm trying to insert data into a database using ajax and php , but this is not working. The connection with the database is working (tried it using only php). The ajax part of my code is posting and the values are valid (checked with firebug). I use postgresql for my data base
I don't know why it doesn't work.
When i press the comment button it works (i get no errors) , but the text in the fields doesn't go into the database
Here is the code:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(event) {
var name = $("#name").val();
var title= $('#title').val();
var comment= $('#comment').val();
$.post("comment.php", {name: name, title: title, comment: comment},
function (data) {
if (!data) {
$("#submit").append("Failed to reach server. Login Error.");
} else {
alert(data);
}
});
return false;
});
});
</script>
<div class='comments'>
<!--<form action="scripts/comment.php" method="POST"> -->
<form action="" method="POST">
<label>Name: </label><br /><input id="name"type="text" name="name" /><br /><br />
<label>Title: </label><br /><input id="title"type="text" name="title" /><br /><br />
<label>Comment: </label><br /><textarea id="comment" name="comment" cols="90" rows="7"> </textarea><br /><br /><br />
<input id="submit" type="submit" name="submit" value="Comment" /><br />
</form>
<hr width=auto size="5px" />
</div>
And the php for insertion:
<?php
if (isset($_POST['name'])) {
// attempt a connection
$conn_string = "host= port= dbname= user= password=";
$dbh = pg_connect($conn_string);
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
$name =pg_escape_string($_POST['name']);
$title= pg_escape_string($_POST['title']);
$comment =pg_escape_string($_POST['comment']);
$today=pg_escape_string(date('d-m-y'));
$sql = "INSERT INTO comments VALUES ('$name','$comment','$today','$title',nextval('comments_id_seq'::regclass))";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
pg_close($dbh);
// $page='../index.php';
//header('Location:'.$page);
}
?>
Any help would be appreciated :) . Thanks
Your $.post() call disregards the server's response which makes troubleshooting difficult. There are a few things you can to do correct this:
First, ensure that you have turned on PHP error reporting. If it is not turned on in your config, enable it near the beginning of your script like this:
error_reporting(E_ALL);
Next, find a way to see the output of your PHP script. You can modify your post call to receive and process the response, but an easier way is to temporarily post your HTML form directly to the script bypassing the AJAX call. See what output the script produces when you post the form directly to the script.

Using jquery to link characters in a form to images in mysql

Amateur novice here, so many thanks in advance for any help. I'm going crazy here.
I'm trying to develop a jquery script to search mysql via php for images stored in my database. User would type a word in an input field. Each character entered in that word returns a separate piece of artwork (e.g, type f-l-o-w-e-r and get six corresponding images). With some help, I got the php script working ok with a regular html form. But now that I've tried adding the jquery part, everything connects OK and seems to run the wayI want, but instead of images, I only get empty boxes with the 'broken image' icon.
I'm attaching the basic scripting of the find.php page below. After that, is the index.php page with the jquery. Any thoughts deeply appreciated...
$lettertype = str_split($lettertype);
$lettertype = "'" . implode("','", $lettertype) . "'";
$query = "SELECT * FROM Photos WHERE letter IN ($lettertype)";
$result = mysqli_query($cxn, $query)
or die ("No good");
$alpharray = array();
while($row = mysqli_fetch_assoc($result))
{
$alpharray[$row['search_term']][] = $row; //
}
foreach(str_split($_POST['search_term']) as $alpha)
{
echo "<a href='link.com'>
<img src='../delete/images/{$alpharray[$alpha][0]['imagePath']}' width='100' height='140'/></a>";
}
And then the index.php...
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("./find.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
</script>
<title>Welcome!</title>
</head>
<body>
<h1>Search here</h1>
<form id="searchform" method="post">
<div>
<label for="search_term">Search</label>
<input type="text" name="search_term" id="search_term" />
<input type="submit" value="search" id="search_button" />
</div>
</form>
<div id="search_results"></div>
</body>
</html>
The src attribute of <img> is always relative to the URL of the actual page the webbrowser sees.
Example:
www.example.com/test/index.php contains an <img> with src=../image.jpg means the webbrowser tries to load www.example.com/image.jpg
So if your index.php lies in / (e.g. www.example.com/index.php), it is likely that referring to an image in ../delete won't work as the server doesn't allow accessing thing outside its webroot.
In any case however, if you want to access the parent directory, you need to put in a ../ (not only ..)
For your script this would mean:
foreach(str_split($_POST['search_term']) as $alpha)
{
echo "<a href='link.com'>
<img src='../delete/images/{$alpharray[$alpha][0]['imagePath']}' width='100' height='140'/></a>";
}

Categories