jQuery - ajax return unknown numbers - javascript

I have problem with ajax results when trying to search some id for example: 0205P, 04066H etc, it give me result correctly but when I click it, in input is some other number like 616, 7,13... So everything working perfect except when my search starting with 0 (zero).
My ID in database(MYSQL) is Varchar(8).
Here is my code:
dob.php
<input type="text" name="konto1" id="konto" class="form-control konto" value="<?php if(isset($_POST['konto1'])) echo $_POST['konto1']; ?><?php if(isset($_GET['konto1'])) echo $_GET['konto1'];?>" />
<div class="boja"><div style="margin-top: 0px" id="selectKonto" class="list-group"></div></div>
<script>
// ajax call
$('#konto').keyup(function() {
var konto = $(this).val();
$.ajax({
type: 'POST',
url: 'konto.php',
data: {
search: konto
},
beforeSend: function() {
$('#konto').css("background", "#FFF url(LoaderIcon.gif) no-repeat 165px");
},
success: function(data) {
if (!data.error) {
// var reply = data.replace(/\s+/, "");
$('#selectKonto').show();
$('#selectKonto').html(data);
$("#konto").css("background", "#FFF");
}
}
});
});
function selectKonto(val) {
$("#konto1").text(val);
$("#selectKonto").hide();
}
</script>
konto.php
if(!empty($konto)) {
$q = "SELECT * FROM konto WHERE ... LIMIT 10";
$result = $db->query($q);
if(!$result){
die('QUERY FAILED' . $db->error);
}
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<div><font size="2em"><a href="#" class="list-group-item konto" style="width: 555px;border: 1px solid grey;"
onclick="selectKonto(\''.trim($row['kp_sif']).'\')">...
<script>
$('.konto').click(function() {
var text = $(this).html();
$('.ime-konto').html(text);
$("#selectKonto").hide();
});
</script>
P.S. Field type in database must stay varchar, I can not change it to INT.

So, it works fine with quotes in php.
onclick="selectKonto(\''.trim($row['kp_sif']).'\')">
Obviously I had other problem in syntax.

Related

Laravel JS autocomplete

I can't figure out what's going on here. I'm trying to make a pretty simple ajax post to do an autocomplete in laravel.
I have an input box and a spot for the results:
<div class="form-group">
<input type="text" name="tag_name" id="tag_name" class="form-control input-lg" placeholder="Enter Country Name" />
<div id="tagList">
</div>
</div>
and my JS
$('#tag_name').keyup(function(){
var query = $(this).val();
if(query != '')
{
//var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('campaigns.search') }}",
method:"POST",
data:{query:query, _token: '{{ csrf_token() }}'},
success:function(data){
$('#tagList').fadeIn();
$('#tagList').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#tag_name').val($(this).text());
$('#tagList').fadeOut();
});
});
The route points to my controller function:
public function searchTags(Request $request)
{
if($request->get('query'))
{
$query = "%" . $request->get('query') . "%";
$data = CampaignTags::where('TAG_DATA', 'LIKE', $query)->get();
$output = '<ul>';
foreach ($data as $row) {
$output .= '<li>' .$row->TAG_DATA. '</li>';
}
}
return json_encode($data);
}
When I inspect as I type, I get 200 codes on the search but I'm not getting actual results to show from the database, the response seems to be null
I did this using typeahead. and answered it in another thread. before
heres the link. Auto Complete Laravel

How to pass the radio button value to other program and insert value into database using php and jquery

I have a form with multiple radio buttons. What i want to store the radio button values in database like 1 for "Yes" and 0 for "No". I am using couple of script a.php, b.php for the same, a.php will get the radio button values and pass to b.php as parameter. Then b.php insert into the database. The problem here is database field for button value always updating with 0. I tried to implement with javascript and some other php logic. But no luck. Also I have created other small script to test the radio value is printing properly which is working fine. The problem is I am not aware how to get proper value in "recommend" in b.php
I really appreciate your help.
a.php is like below:
<div id="result">
<label for="sel1">Would You recomend</label>
<div class="pull-left">
<input name='recommend' type='radio' value=1>Yes
<input name='recommend' type='radio' value=0>No
<button class="btn btn-primary btn-sm" id="submit" type="submit" value="submit">submit</button>
b.php
<?php
require_once './config.php';
$pid = intval($_POST["pid"]);
$uid = intval($_POST["uid"]);
$score = intval($_POST["score"]);
$recommend = intval($_POST["recommend"]);
$aResponse['error'] = FALSE;
$aResponse['message'] = '';
$aResponse['updated_rating'] = '';
$return_message = "";
$success = FALSE;
$sql = "INSERT INTO `tbl_product_rating` (`product_id`, `user_id`, `ratings_score`, `recommend_score`) VALUES "
. "( :pid, :uid, :score, :recommend)";
$stmt = $DB->prepare($sql);
try {
$stmt->bindValue(":pid", $pid);
$stmt->bindValue(":uid", $uid);
$stmt->bindValue(":score", $score);
$stmt->bindValue(":recommend", $recommend);
//$stmt->execute(':pid' => $pid, ':uid' => $uid, ':score' => $score, ':recommend' => $recommend));
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
$aResponse['message'] = "Your rating has been added successfully";
} else {
$aResponse['error'] = TRUE;
$aResponse['message'] = "There was a problem updating your rating. Try again later";
}
} catch (Exception $ex) {
$aResponse['error'] = TRUE;
$aResponse['message'] = $ex->getMessage();
}
if ($aResponse['error'] === FALSE) {
// now fetch the latest ratings for the product.
$sql = "SELECT count(*) as count, AVG(ratings_score) as score FROM `tbl_products_ratings` WHERE 1 AND product_id = :pid";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":pid", $pid);
$stmt->execute();
$products = $stmt->fetchAll();
if ($products[0]["count"] > 0) {
// update ratings
$aResponse['updated_rating'] = "Average rating <strong>" . round($products[0]["score"], 2) . "</strong> based on <strong>" . $products[0]["count"] . "</strong> users";
} else {
$aResponse['updated_rating'] = '<strong>Ratings: </strong>No ratings for this product';
}
} catch (Exception $ex) {
#echo $ex->getMessage();
}
}
echo json_encode($aResponse);
?>
Jquery which I am using in a.php to send radio button value to b.php:
<script>
$document.ready(function(){
$('input[type="radio"]').click(function(){
var recommend = $(this).val();
$.ajax({
url:"b.php",
method:"POST",
data:{recommend:recommend},
// data:{recommend:$('#recommend').val($("[type='radio'] :checked").val())},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
jquery to fetch pid,uid,score..
<script>
$(document).on('click', '#submit', function() {
<?php
if (!isset($USER_ID)) {
?>
alert("You need to have a account to rate?");
return false;
<?php } else { ?>
var score = $("#score").val();
if (score.length > 0) {
$("#rating_zone").html('processing...');
$.post("update_ratings.php", {
pid: "<?php echo $_GET["pid"]; ?>",
uid: "<?php echo $USER_ID; ?>",
score: score
}, function(data) {
if (!data.error) {
// success message
$("#avg_ratings").html(data.updated_rating);
$("#rating_zone").html(data.message).show();
} else {
// failure message
$("#rating_zone").html(data.message).show();
}
}, 'json'
);
} else {
alert("select the ratings.");
}
<?php } ?>
});
</script>
I can insert the value 1 if "YES" for radio button with the mentioned jquery but it's inserting 0 for other fields like product_id..etc.I want just one entry to be inserted in db with proper value of radio button along with other fields.I have provided the full code for insert (b.php) with ajax which passing value to b.php from a.php. Kindly suggest.
I want output in mysql like below:
ratings_id product_id user_id ratings_score recommend_score
1 17637 1 4 0
2 17638 2 2 1
How it's happening now:
ratings_id product_id user_id ratings_score recommend_score
3 0 0 0 1
6 17639 2 4 0
In your ajax that fires once a user clicks on a radio-button you are not sending the other values needed for insert (pid, uid, score). I suppose they are included in the half-shown form.
Assuming you have those inputs in your form
<input name="pid" id="pid">
<input name="uid" id="uid">
<input name="score" id="score">
EDIT: since you've now shown more code I updated the code below (to match how you send pid & uid in the normal form-submit).
you can add them to the data object with something like this:
data:{
recommend:recommend,
pid: "<?php echo $_GET["pid"]; ?>",
uid: "<?php echo $USER_ID; ?>",
score: $('#score').val(),
},
Also change the double-ids of #newsletter as the others have suggested.
Change id to class attribute.
<script type="text/javascript">
$(document).ready(function() {
$("input[type=radio]").click(function () {
var recommend = $(this).val();
console.log(recommend);
$.ajax({
url:"b.php",
method:"POST",
data:{
recommend:recommend
},
success: function(data){
//your code here
},
error: function (error) {
console.log(error);
}
});
});
});
</script>
<input name="recommend" class='newsletter' type='radio' value=1>Yes
<input name="recommend" class='newsletter' type='radio' value=0>No
Sample HTML:
<input type="radio" name="color" id="rdoColor" value="green" />Green<br />
<input type="radio" name="color" id="rdoColor" value="Blue" />Blue<br />
Sample JQuery Code:
$(document).on("click", "input[id=rdoColor]", function(){
$.post(serverPath+"/colorHandler.php", {action: "saveColor", color: $(this).val()}, function(data){
var response = $.parseJSON(data);
// use this response as u need
});
});
Sample PHP (colorHandler.php):
$jsonStr = "";
define('DB_SERVER', 'DBserver:port');
define('DB_NAME', 'DBName');
define('DB_USER', 'dbUser');
define('DB_PASS', 'dbPass');
try {
$dbCon = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASS);
$dbCon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO colorTable (colorName) VALUES (?)";
$stmt= $dbCon->prepare($sql);
$stmt->execute(array($_POST["color"]));
if( $dbCon->lastInsertId() ){
$jsonStr = '{
"status":"Success",
"Message":"Color Saved"
}';
echo $jsonStr;
}else{
$jsonStr = '{
"status":"Failure",
"Message":"Color was not Saved"
}';
echo $jsonStr;
}
}catch(PDOException $e){
$jsonStr = '{
"status":"Failure",
"Message":"Database server not found!"
}';
echo $jsonStr;
}

Unable to identify value of HTML form element using AJAX

I am trying to implement a message system in my project by using AJAX, but I have got some problems because I am new to AJAX.
The code below is able to send input data from the MsgMain.php file to MsgInsert.php perfectly. But when I try to get $_POST['msgSend'] from MsgMain.php on MsgInsert.php it fails.
AJAX Code is on MsgMain.php
$(document).ready(function(){
$("#chatBtn").click(function(){
$("#msgBtn").val("chat");
});
$("#pmBtn").click(function(){
$("#msgBtn").val("pm");
});
});
$(function() {
$("#msgBtn").click(function() {
var textcontent = $("#msgInput").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#msgInput").focus();
}
else
{
$.ajax({
type: "POST",
url: "msg/MsgInsert.php",
data: dataString,
cache: true,
success: function(response){
document.getElementById('content').value='';
$("#msgBtn").focus();
}
});
}
return false;
});
});
MsgMain.php file code just for the HTML form
<form action="MsgInsert.php" id="frmBox" name="msgSend" method="POST" onsubmit="return formSubmit();">
<div class="input-group ">
<input type="text" class="form-control" name="msgBox" id="msgInput" title="Enter your message" required>
<div class="input-group-btn">
<button class="btn btn-success w3-hover-white w3-hover-text-green" type="submit" id="msgBtn" title="Send your message" value="chat"><i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
</form>
MsgInsert.php file code, which works well when I remove the if statement of $_POST['msgSend']
<?php
if(!isset($_SESSION['login_user'])){
header("location: ../index.php"); // Redirecting To Home Page
}
if (isset($_POST['content'])) {
if (isset($_POST['msgSend'])) {
$conn = mysqli_connect("localhost", "root", "", "msg");
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$content=$_POST['content'];
mysqli_query($conn, "INSERT INTO `msgpm`(`id`, `msgFrom`, `msgTo`, `msg`) VALUES ('','bob','ram','$content')");
}
}
?>
Sorry if this type of question has already been asked.
You are not sending the msgSent attribute, according to this line in your JS:
var dataString = 'content='+ textcontent;
I can see only the content which you will be able to use via $_POST['content'].
Try this:
var dataString = 'content='+ textcontent + '&msgSent' + '<?php echo $_POST['msgSent']; ?>';
You have to pass the msgSend Parameter according to your implementation of MsgInsert.php like so:
$("#msgBtn").click(function () {
var textcontent = $("#msgInput").val();
if (textcontent == '') {
alert("Enter some text..");
$("#msgInput").focus();
}
else {
var dataString = 'content=' + textcontent + '&msgSend=1';
$.ajax({...});
}
});
Always think of escaping your content via i.e. prepared statements when saving user generated content into your database to avoid sql injection!

Ajax live search results not shown on my page

I got a simple ajax live search script that works fine when I type the keyword in my url and visit the php file. But for some reason when I type the keyword in my input field, nothing happens.
What am I doing wrong?
My input field on products.php:
<input type="search" name="keyword" class="producten-icon divider" placeholder="Zoeken..." id="s_search">
And further down the page I got my result div:
<div id="results"></div>
My ajax script:
<script>
$(document).ready(function () {
$("#s_search").on('keyup',function () {
var key = $(this).val();
$.ajax({
url:'includes/fetch_results.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
}
});
});
});
</script>
My fetch_results.php:
<?php
include 'connection.php';
$conn = new Connection;
if($_GET['keyword'] && !empty($_GET['keyword']))
{
// Results names
$results = "SELECT `naam` FROM `producten` WHERE `naam` LIKE '%".$_GET['keyword']."%'";
$resultscon = $conn->query($results);
$resultscr = array();
while ($resultscr[] = $resultscon->fetch_assoc());
$eend = #array_map('current', $resultscr);
// echo '<pre>';
// print_r($eend);
// echo '</pre>';
$resultsoverzicht .= '<div style="height:100%;border:10px solid red;">';
foreach($eend as $result){
$resultsoverzicht .= '
<p>'.$result.'</p>';
}
$resultsoverzicht .= '</div>';
echo $resultsoverzicht;
};
?>
When I use the network inspector I don't see anything posted when typing in the input field. Which should be the case with keyup right?

How to filter data using an input box and dropdown menus

Hey So I have an issue with my code where I am trying to filter the data coming from the database and display it in a table. I am using AJAX to send the request to the PHP page. I have not had any luck in searching for a solution. (It will be similar to your common real estate website, or retail, etc. where the user can input a location in the search box, search for it, and then filter the displayed data using the 2 dropdown menus).
My index.php page has 3 inputs (a textbox and 2 dropdowns)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off">
<div id="here"></div>
<select class="orderType" name="type" id="orderByType" data-toggle="dropdown" onchange="displaySelection(this.value)">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" id="orderBy" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable">
Then my ajax calls on the index.php page (The AJAX will be another question later, as I'm sure there is a better way than what I have, to send the data)
function fill(Value)
{
$('#search').val(Value);
$('#here').hide();
}
$(document).ready(function(){
$("#search").keyup(function(){
var x = $('#search').val();
if(x==""){
$("#here").html("");
$('#searchTable').html("");
}
else{
$.ajax({
type:'POST',
url:'test.php',
data:'q='+x,
success:function(html){
$("#here").html(html).show();
}
});
}
});
$('.searchForm').change(function(){
var type = $('#search').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { search : type, city : city },
success: function(response){
$("#searchTable").html(response);
$('#search').live("keypress",function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
e.preventDefault();
e.stopPropagation();
$('#searchTable').show();
}
});
}
});
});
$('.orderClass').change(function(){
var order = $('#orderBy').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderBy : order, city : city },
success: function(response){
$("#searchTable").html(response);
}
});
});
$('.orderType').change(function(){
var type = $('#orderByType').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderByType : type, city : city},
success: function(response){
$("#searchTable").html(response);
}
});
});
});
And then on test.php
(I can filter the data with the 2 dropdown menus and that will work fine, but i'm not sure how to filter the data that is displayed from the search input box.)
$stmt = "SELECT * FROM places";
if(isset($_POST['search'])){
$search = htmlspecialchars($_POST['search']);
$stmt .= " WHERE name = :search";
}
if(isset($_POST['orderByType'])){
$selection = $_POST['orderByType'];
$stmt .= " AND type = :selection";
}
if(isset($_POST['orderBy'])){
$order = $_POST['orderBy'];
$selection = $_SESSION['id'];
$stmt .= " ORDER BY".$order;
}
$stmt = $conn->prepare($stmt);
$search = "%".$search."%";
$stmt->bindValue(':search', $search, PDO::PARAM_STR);
$stmt->bindParam(":selection", $selection);
if($stmt->rowCount() > 0){
$result = $stmt->fetchAll();
foreach($result as $row){
echo $row['data'];
}
}
//Search input live search
if(!empty($_POST['q'])){
$name = $_POST['q'];
$name = htmlspecialchars($name);
$liveSearch = $conn->prepare("SELECT name, city FROM places WHERE name LIKE :name OR city LIKE :name");
$name = "%".$name."%";
$liveSearch->bindValue(':name', $name, PDO::PARAM_STR);
$result = $liveSearch->fetchAll();
if($liveSearch->rowCount() > 0){
foreach($result as $row){
echo $row['name'];
}
}
else{
echo "No results found";
}
}
(If there is a great system in place that can search using user input and then filter it using dropdown menus, then please let me know)
Thanks in advance.
If I was going to do this, I would probably make an ajax object for reuse reasons and a php object to handle queries:
/defines.php
You may or may not have defines for your db credentials. I use these in the class below.
define("DB_USER",'root');
define("DB_PASS",'password');
define("DB_HOST",'localhost');
define("DB_NAME",'dbname');
/classes/Query.php
This is a stripped-down query engine which makes basic queries. I use it to save on rewriting a bunch of prepares and executes, but you can do whatever you like there.
class Query
{
private static $singleton,
$con;
private $rquery,
$bind;
public function __construct()
{
if(self::$singleton instanceof Query)
return self::$singleton;
self::$singleton = $this;
}
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
self::$con = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
return self::$con;
}
public function query($sql,$bind = false)
{
$this->bind = false;
try {
if(empty($bind)) {
$this->rquery = $this->connect()->query($sql);
}
else {
foreach($bind as $key => $value) {
$bkey = ":{$key}";
$this->bind[$bkey] = $value;
}
$this->rquery = $this->connect()->prepare($sql);
$this->rquery->execute($this->bind);
}
}
catch (PDOException $e){
die('An application error occurred.');
}
return $this;
}
public function getResults()
{
while($results = $this->rquery->fetch(PDO::FETCH_ASSOC)) {
$row[] = $results;
}
return (!empty($row))? $row : 0;
}
}
/functions/searchPlaces.php
function searchPlaces($search,$type = false,$orderby = false)
{
$sVal = "%".$search."%";
array();
$sql[] = 'SELECT * FROM places WHERE `name` LIKE :0 or `city` LIKE :1';
$bind = array_fill(0,2,$sVal);
if(!empty($type)) {
$bind[] = $type;
$sql[] = 'AND `type` = :2';
}
if(!empty($orderby)) {
$order = ($orderby == 'lowest')? 'ASC' : 'DESC';
$sql[] = "order by `ID` {$order}";
}
// Here is where I use the query to send back results from DB
// you can just use a regular prepare/bind/execute if you like
$qEngine = new Query();
return $qEngine->query(implode(' ',$sql),$bind)->getResults();
}
/test.php
<?php
// Put our db credentials
require_once(__DIR__.'/defines.php');
if(!empty($_POST)) {
// Needs the search function and the query class
// (disregard class if you don't use it)
require_once(__DIR__.'/functions/searchPlaces.php');
require_once(__DIR__.'/classes/Query.php');
// I am just sending an array back, but you can format it as you please
print_r(searchPlaces($_POST['search'],$_POST['type'],$_POST['order']));
exit;
}
/index.php
<script>
// I like to make an ajax engine, it saves on rewriting all the same stuff
// on later ajax calls
var AjaxEngine = function($)
{
this.send = function(data,func)
{
$.ajax({
url: '/test.php',
data: data,
type: 'post',
success: function(response){
func(response);
}
});
return this;
};
}
// You only need one document ready
$(document).ready(function(){
// Make an ajax engine
var Ajax = new AjaxEngine($);
// If form changes or key up in text field
$('.searchForm,.ajaxer>select').on('keyup change',function(e) {
e.preventDefault();
// Serialize the form
var formData = $('.ajaxer').serialize();
// Send the ajax and return results
Ajax.send(formData,function(response) {
$('#searchTable').html(response);
});
});
});
</script>
<!-- Note changes to the form for classes and ids -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="ajaxer">
<input name="search" type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off" />
<div id="here"></div>
<select class="orderType" name="type" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable"></div>

Categories