Can someone spot my error (autocomplete text box)? - javascript

So far I have HTML:
<div id="box" style="width:400; height:400; margin-left:auto; margin-right:auto; margin-top:100;">
<h2>Enter a word</h2>
<input type="text" id="input" ></input>
</div>
<div id="suggest">
</div>
Javascript:
<script type ="text/javascript">
$(document).ready(function(){
$("#input").keyup(function(){
var input = $("#input").val();
$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: "input"+input,
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});
});
});
</script>
PHP:
<?php
$dbh=mysql_connect ("localhost", "~", "~") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("~") or ("Database not found");
$input = $_REQUEST['input'];
$input = mysql_real_escape_string(trim($input));
$sql = "SELECT * FROM ~ WHERE ~ LIKE '%".$input."%'";
$data = mysql_query($sql);
$arrcnt = -1;
$dataArray = array();
while ($temp = mysql_fetch_assoc($data))
{
foreach($temp as $key=>$val) {
$temp[$key] = stripslashes($val);
$arrcnt++;
}
$dataarray[$arrcnt] = $temp;
}
$list = "<ul style='width:100;height:auto;'>";
foreach($dataArray as $val) {
$list .= "<li>".$val['DesiredColumnContainingDesiredData']."</li>";
}
$list .= "</ul>";
echo $list;
?>
Now, these codes are supposed to work together to autocomplete the div with id="suggest" then populate the text field with id="input" when selected ... I keep getting alert that reads: <ul style='width:100;height:auto;'></ul>

change ajax code like this,
$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: {"input":input},
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});

The issue is because in php your variable name is different . You added $dataarray instead of $dataArray
Additionally for ajax
You can pass data as a string or as an object
data:{"input":input}
or
data:"input="+input
add type: 'POST' in ajax

Related

How to debug my Ajax/jQuery app?

I am trying some things regarding Ajax, Jquery and PHP.
My JavaScript code (the pop.php is located correctly)
<script type="text/javascript">
$('.nameclick').click(function()) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id=$(this).data("formid")}
success: function(result){
alert(result);
} else {
alert("test");
}
});
});
</script>
Part of my html/php code in the same page (this code works fine to print out the table I am looking for):
<table class="data-table">
<thead>
<tr>
<th>Servicenummer</th>
<th>Kund</th>
<th>Uppgift</th>
<th>Status</th>
<th>Inlämnad</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td><div id="clickMe">'.$row['service'].'</div></td>
<td>'.$row['name'].'</td>
<td>'.$row['Drakt1'].'<br>'.$row['Drakt2'].'<br>'.$row['Drakt3'].'<br>'.$row['Drakt4'].'<br>'.$row['Drakt5'].'<br>'.$row['Drakt6'].'<br>'.$row['reg1'].'<br>'.$row['flaska1'].'<br>'.$row['dator1'].'</td>
<td>'.$row['Service_Status'].'</td>
<td>'.$row['date'].'</td>
</tr>';
$no++;
}?>
</tbody>
</table>
And my pop.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$telephone = $conn->real_escape_string($_POST['telephone']);
$sql = 'SELECT name, email, telephone FROM Service_Form WHERE id = "10"';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<?php
while ($row = mysqli_fetch_array($query))
{
echo $row['name'];
echo $row['email'];
echo $row['telephone'];
}
?>
At the moment when I click my link in my normal page I don't get anything, no alerts at all, but my pop.php prints out the values correctly, I hope... I know I have to change my id="10" to something but i am not certain to what, could it be formid?
What am I doing wrong here?
What I want:
a table with the values below from a table in the database
when I click the name in the table it should show an alert (or something similar) that shows the name, email and telephone number (these are stored as well in the database table but not on the website table).
your ajax function is having some errors
so use this
<script type="text/javascript">
$('.nameclick').click(function(ev) {
ev.preventDefault();
var id = $(this).data("formid");
$.ajax({
type: "POST",
url: "pop.php",
data: {
"id":id
},
success: function(result){
alert(result);
},
error:function (error) {
alert(error);
}
});
});
</script>
I am editing your jquery part please try
<script type="text/javascript">
$('.nameclick').click(function(ev)) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id:$(this).attr("data-formid")}
success: function(result){
if(result){
alert(result);
} else {
alert("test");
}
}
});
});
</script>

Onchange populate different dropdown based on value

I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?
Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.
I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>

how to pass checkbox value to text input using Ajax and PHP?

I'm trying to evaluate the values of all checked checkboxes and pass the result
to html text input I'm trying to do that using php and ajax but I have no good result please help
this is my code:
$(document).ready(function ()
{
$("#check").click(function ()
{
var data = $("#check").val();
//get selected parent option
$.ajax(
{
type: "GET",
data:data,
url: "total.php?val="+data,
cache: false,
success: function (data)
{
$("#tot").html(data);
}
});
});
});
</script>
</head>
<?php
$conn = mysqli_connect("localhost", "root", "", "voucher_test");
$result = mysqli_query($conn, "SELECT * FROM vouchers where cat_id = 1");
while ($row = mysqli_fetch_array($result)) {
$userSet[] = $row;
}
?>
<form action="index.php" method="post">
<?php
foreach ($userSet as $key=>$value){
echo $value['service_name']."<input type='checkbox' id='check' name='{$value['service_name']}' value='{$value['service_price']}'>";
}
?>
<br>
<div id="tot"></div>
</form>
and this is total.php
<?php
$itot = 5;
$itot+=$_GET['val'];
echo"<input type='text' value='$itot'>";
You can use this code to sent value to server y o n
var data = ($("#check").is(":checked") ? 'y' : 'n';
If you want send the value of checkbox, try this code:
var data = new FormData();//Create FormData
if($("#check").is(":checked")){//Verified if the input os checked
data.append('data-check',$("#check").val());//Add data of the checkbox to FormData
}
$.ajax(
{
type: "GET",
data: data,
url: "total.php",
cache: false,
success: function (data)
{
$("#tot").html(data);
}
});
In yur php
$_GET['data-check'];
I don't think you need to use the total.php file, but if you really want to use it I recommend to change your code to this:
<?php
$itot = 5;
$itot+=$_GET['val'];
echo"<input type='text' value='" . $itot . "'>";
The only change is the concatenation of the string you are printing

How do I output PHP/SQL results from HTML/AJAX

If I call the .php file directly it works great, so I believe the error is in how I am displaying the AJAX result. I am new to AJAX. I have a form that the user can select dates to search on, etc and I would like to results to be displayed when returned.
$("#searchForm").on("submit", function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "searchnow.php",
data: $('#searchForm').serialize(),
success : function (output) {
console.log(output);
}
});
});
searchnow.php
<div id="output">
<div class="container-fluid">
<div class='features'>
<?php
include ("config.php");
$con = mysql_connect($server, $user, $password) or die('Sorry, could not connect to database server');
mysql_select_db($database, $con) or die('Sorry, could not connect to database');
$query = "SELECT * FROM hsevents WHERE
CURDATE()<=enddate AND
verified='Y'
ORDER BY location";
$result = mysql_query($query) or die('Sorry, could not access the database at this time ');
$SPACES = "</br><b>Description:</b> ";
if (mysql_num_rows($result) == 0)
{
echo "<h3>Sorry, there are no classes or events that meet your criteria.</h3>";
}
else
{
$i = 1;
while($row=mysql_fetch_array($result, MYSQL_ASSOC))
{
$unique = 'unique' . $i;
$tempname=htmlentities($row[name]);
$tempcontact=htmlentities($row[contact]);
$tempbegdate = date("m-d-Y", strtotime($row[startdate]));
$tempenddate = date("m-d-Y", strtotime($row[enddate]));
ob_start();
if ( ($i%4) === 0) {
echo "<div class='row row-padded row-bordered row-centered'>";
}
echo "
<div class='col-md-3'>
<div class='panel'>
<div class='panel-heading'>
<img src='images/$row[category]' class='img-responsive img-thumbnail img-hsb'>
</div>
<div class='panel-body text-center'>
$tempname</br>
Start Date: $tempbegdate</br>
End Date: $tempenddate</br>
Location: $row[location]</br>
Age Range: $row[lowerage] - $row[upperage]</br>
Contact: <a href=$tempcontact>$tempcontact</a></br>
<div id='$unique' class='collapse collapse-hsb'>
$tempdescription
</div>
</div>
</div>
</div>
";
if ( ($i%4) === 0) {
echo "</div>";
}
$classdata = ob_get_contents();
ob_end_clean();
?>
<?php echo $classdata ?>
<?php
$i++;
}
$classdata = ob_get_contents();
ob_end_clean();
echo $classdata;
}
?>
</div>
</div>
</div>
You just need to provide the DIV or any Selector inside the success function, to replace the DIV or selector html with the AJAX success output. Here i used #MyDivId which should be your html element in which you need to print the AJAX output.
$("#searchForm").on("submit", function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "searchnow.php",
data: $('#searchForm').serialize(),
success : function (output) {
output = output.trim(); // Trim's unwanted white space around the output
if (output != "") {
$("#MyDivId").html(output); // This Adds the AJAX output inside #MyDivId
}
}
});
});

PHP Ajax not creating post variable

A while ago i made a search function with ajax and php. You could fill in a textbox with text and it would try to find a match among all countries stored in the database.
Now i am refining the code and making it PDO, but i broke something and i cant find out what.
this is my plain HTML
<head>
<title>Ajax</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/Javascript.js"></script>
</head>
<body>
<div id="main">
<h1 class="title">Enter your country please</h1>
<input type="text" id="search" autocomplete="off" onchange="">
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
</div>
</body>
here is my Jquery and javascript. note i have not changed anything to the HTML nor javascript so it can not by a type error.
$(document).ready(function() {
alert('asdf');
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
And here is my Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
else{
$search_string = '';
echo('Something went wrong, post query not set');
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
The problem:
the Post query is never created, for this i made a isset so for now when there is no Post Query created. It will create a Post Query with value "B".
Any help will be much appreciated. Please be gentle i am new to Ajax and i rather want to understand than have the solution. Thank you
You're not point the right URL! Look:
You have pointed your ajax request to search.php :
$.ajax({
type: "POST",
url: "search.php",
But you have just a class in search.php. A class don't do anything by itself. You have to Instantiate and call its methods/functions. Please compare these 2 pieces of code:
<?php
//server.php
//Doing nothing
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
?>
let's say you have this in server.php
<?php
//server.php
//It will print "I'm executing" in the screen
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
$search = new SearchEngine($conn);
?>
To solve your original problem You have to to point your ajax to the page having the INSTANTIATION code, not the class, like this:
//index.php
//Let's suppose you have this code in your index.php
$SearchEngine = new SearchEngine($conn);
So your JQuery ajax code should looks like that:
$.ajax({
type: "POST",
url: "index.php",
As Mentioned by Sean, in the comments, the $.live jquery method is deprecated in your version of jQuery.
Try utilizing $.keyup instead
$("input#search").keyup(function() {
// stuff
});

Categories

Resources