Sending two values to PHP via ajax POST to query SQL db - javascript

I'm trying to send two values from a form to another PHP using ajax post method. One value is the value that's already entered in an input box, and the other is a value that is being typed into another input box. It acts like a search box. I tried executing the SQL query in my SQL workbench and it returns the value properly. What am I doing wrong in my code?
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
$("#sbb").html(sbb);
//searchq7();
});
}
This is the input box where I search and get the value from:
<input type="text" name="region" list="state" value="<?php echo $region; ?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" list="sbb" value="<?php echo $suburb; ?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6" >
<option> </option>
</datalist>
This is the search-suburb.php file:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state="'.$st.'" AND `title` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$suburb = $row['title'];
?>
<option value="<?php echo $suburb; ?>"><?php echo $suburb; ?> </option>
<?php
} // while
} // else
} // main if

<input type="text" name="region" list="state" value="<?=(isset($_POST['region'])?$_POST['region']:'');?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" onkeyup="searchq6()" list="sbb" value="<?=(isset($_POST['suburb'])?$_POST['suburb']:'');?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6"></datalist>
Javascript:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
var decode = jQuery.parseJSON(sbb); // parse the json returned array
var str = ""; // initialize a stringbuilder
$.each(decode, function (x, y) {
str+="<option value='" + y.title +"'>";
});
$("#sbb").html(str);
}); // end of post
}// end of searchq6 function
Php:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='{$st}' AND `title` LIKE '%{$searchq}%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
} else{
$data = array();
while($row = mysqli_fetch_array($query))
$data[] = $row;
echo json_encode($data);
}
} // main if

Got the answer from small snippets gathered through the comments
Changed the query to:
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."' AND `title` LIKE '%".$searchq."%' LIMIT 10")or die("Could not search!");
And the ajax to:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
.done(function(sbb) {
$("#sbb").html(sbb);
});
//searchq7();
}
Thanks for all the comments guys

Related

Fetching data using onChange jquery ajax issue

here in my code i am trying to fetch and display the data after selecting a option from the dropdown using onChange, fetching data from a PHP file and via ajax displaying it in textarea in same select.php file but unfortunately it is not working out for me am quit confused were i made a mistake, please help me out on this.
select.php
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#channel").change(function(){
$.post("ajax.php", { channel: $(this).val() })
.success(function(data) {
$(".result").html(data);
});
});
});
</script>
</head>
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" id = 'channel' name="ProductCategoryID" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="1234">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group result"></div>
ajax.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode = '$channel' ";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
while($row = mysql_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
Try using:
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
May be it would help
replace,
$.post("ajax.php", { channel: $(this).val() })
with
$.post("ajax.php", { 'channel': $(this).val() })
$.post("ajax.php", { channel: $(this).val() },function(data) {
$(".result").html(data);
});
Please remove .success(function(data){ }) from the code and it will work :)
Try to initiate $msg first and use mysqli module.
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode =$channel";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
UPDATE
Update your post request with:
$.post("ajax.php",
{ channel: $(this).val() },
function(data) {
$(".result").html(data);
}
);
OR
$.post("ajax.php",
{ channel: $(this).val() },
successCallback
);
function successCallback(data){
//process data..
}
see https://api.jquery.com/jquery.post

Why isn't my ajax code updating my second dropdown?

I have no idea why my code isn't working. I basically have two dropdowns, the first is populated from an mssql database and I want the second dropdown to update dependant on the selection in the first.
Below is my code which populates a dropdown box:
<?php
session_start();
$serverName = "REDACTED";
$connectionInfo = array( "Database"=>"REDACTED", "UID"=>"REDACTED", "PWD"=>"REDACTED");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if (!isset($_SESSION['nID']))
{
header("Location: Login.php");
die();
}
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['region']."</option>";
}
return $output;
}
?>
I then use this to populate the first dropdown:
<p>Select a Region
<select name ="region" id ="region">
<option value ="">Select Region</option>
<?php echo loadRegion(); ?>
</select></p>
For the second dropdown box I have the following:
<p>Select a Territory
<select name="territory" id="territory">
<option value="">Select Territory</option>
</select></p>
I call my ajax via:
<script>
$(document).ready(function(){
alert("ready");
$('#region').change(function(){
var region_id = $(this).val();
$.ajax({
url:"getter.php",
method:"POST",
data:{regionId:region_id},
dataType:"text",
success:function(data){
$('#territory').html(data);
}
});
});
});
</script>
My getter page reads as follows:
<?php
session_start();
include 'config.php';
$output = '';
$sql = "SELECT distinct id,territory,rid FROM territoriesHaiss where RID = '".$_POST["regionId"]."' order by id";
$result = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$output = '<option value ="">Select Territory</option>';
while($row = sqlsrv_fetch_array($result))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['territory']."</option>";
}
echo $output;
?>
As pointed out by the 2 comments above (thanks again for the help!) the error was in the code that populates the first dropdown. It should have been a lowercase 'ID', like follows:
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['id'])."\">".$row['region']."</option>";
}
return $output;
}
?>

php search function dynamically show results with javascript

I have the following php script which works fine, it uses the search term and compares it with a few different fields, then prints out the each record that matches:
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
while ($row = mysql_fetch_array($sql)){
echo '<br/> Name: '.$row['name'];
echo '<br/> Barcode: '.$row['barcode'];
echo '<br/> Serial: '.$row['serial'];
}
?>
And this is the form that links to it:
<form action="http://localhost/test/search.php" method="post">
Search: <input type="text" name="search" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
I need to some how encode the results of the search so I can use them in a javascript function, then I can display them on the same html page below the form.
For that you have to use AJAX. You can send data back to the same page using JSON.
Advice - Don't use mysql_* functions since they are deprecated. Learn mysqli_* and try using that.
<script>
$(function(ev){
ev.preventDefault();
$("form").on('submit', function(){
var form = $(this);
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function(response){
if(response.success == TRUE)
{
// Search result found from json
// You have to loop through response.data to display it in your page
// Your single loop will have something like below -
var name = response.data.name;
var barcode = response.data.barcode;
var serial = response.data.serial;
$("#name").html(name);
$("#barcode").html(barcode);
$("#serial").html(serial);
}
else
{
// search result not found
}
});
});
});
</script>
On search.php
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
$num = mysql_rows_nums($sql);
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
while ($row = mysql_fetch_array($sql)){
$json['data']['name'] = $row['name'];
$json['data']['barcode'] = $row['barcode'];
$json['data']['serial'] = $row['serial'];
}
}
else
{
$json['success'] = FALSE;
}
return json_encode($json);
?>

Troubles sending textarea data to a database

I'm trying to create a php form that sends textarea data to database. The database table uploads has 3 data items that are needed:
user_id
category
content
HTML:
<form id="myform" action="php/savetext.php" method="POST" enctype="multipart/form-data">
<p><strong>Add your story here.</strong></p>
<input type="hidden" name="fbid" id="fbid">
<input type="hidden" name="category" id="category">
<textarea cols="50" rows="10" name="usertext" id="storyArea"></textarea>
<input type="submit" name="submit" value="Saada" />
<script type="text/javascript">
$( "#fbid" ).val( "sdf88d99sd" );
$( "#category" ).val( "texts" );
</script>
</form>
savetext.php:
include_once('config.php');
if (isset($_POST['user_id']) && isset($_POST['category']) && isset($_POST['usertext'])) {
$user_id = mysql_real_escape_string($_POST['fbid']);
$category = mysql_real_escape_string($_POST['category']);
$content = mysql_real_escape_string($_POST['usertext']);
addUser($user_id, $category, $content);
}
else {
echo 'Upload failed! Try again.';
}
function addUser($user_id, $category, $content) {
$query = "SELECT id FROM uploads WHERE user_id = '$fbid' LIMIT 1";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
if ($rows > 0) {
$query = "UPDATE uploads SET user_id = '$user_id', category = '$category' WHERE content = '$content'";
}
else {
$query = "INSERT INTO uploads (user_id, category, content) VALUES ('$user_id', '$category', '$content')";
}
mysql_query($query);
echo 'Upload was succesful. Thank you!';
}
But this doesn't work. Any ideas on how to correct this?
please review this code ,there is no field with name user_in in <form></form>
if (isset($_POST['fbid']) && isset($_POST['category']) && isset($_POST['usertext'])) {
$user_id = mysql_real_escape_string($_POST['fbid']);
$category = mysql_real_escape_string($_POST['category']);
$content = mysql_real_escape_string($_POST['usertext']);
addUser($user_id, $category, $content);
}

cant fillter characters in jcombo

Can someone help me with this? My sql code only works if I match only integers like 2=2 but if I change it to like this orange=orange it wont work...can anyone help me figure whats wrong with my code.
index.php:
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<form>
Caraga Region: <select name="region" id="region"></select>
Municipalities: <select name="town" id="town"></select>
Unique ID: <select name="uniq_id" id="uniq_id"></select> <br />
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#region").jCombo({ url: "getRegion.php" } );
$("#town").jCombo({ url: "getTown.php?townid=", parent: "#region", selected_value : '510' } );
$("#uniq_id").jCombo({ url: "getID.php?unqid=", parent: "#town", data: String, selected_value : '150' } );
});
</script>
getRegion.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Execute Query in the right order
//(value,text)
$query = "SELECT id, municipalities FROM regions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getTown.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$townid = !empty($_GET['townid'])
?intval($_GET['townid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT town FROM towns WHERE tcode = $townid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['town'], "value" => htmlentities($row['town']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
getID.php: The problem is in this code. It wont work if I match character to character it only works if its integer=integer.
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT uid, unq_pos_id FROM tb_uniqid WHERE tb_uniqid.uid = '$unqid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['uid'], "value" => htmlentities($row['unq_pos_id']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
(uid)field is stored with character values just like in the (town)field. I want to match it but it won't work.
Try to in getID.php replace:
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
with:
$unqid = !empty($_GET['unqid'])
?$_GET['unqid']:0;
if you want to be able to match strings as well as integers. You see, intval() returns only the integer value of the variable, thus you strip of the other characters when you send a string to that page, and therefore you can't match anything with the code you had before.

Categories