I'm having a problem with bootstrap 3 and typeahead.js from github https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#datasets
I'm trying to get my data from ajax to appear to suggest to a user when he types in my input field.
My console keeps giving me a message that says "Uncaught TypeError: Cannot read property 'replace' of undefined "
any help?
<html>
<head>
<!-- Bootstrap framework -->
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css" />
</head>
<body>
<div class="well">
<input type="text" class="span3 typeahead form-control" id="players" data-provide="typeahead">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- main bootstrap js -->
<script src="../bootstrap/js/bootstrap.min.js"></script>
<!-- bootstrap plugins -->
<script src="../js/bootstrap.plugins.min.js"></script>
<!-- typeahead-->
<script src="../lib/typeahead/typeahead.min.js"></script>
<script type="text/javascript">
$(function(){
$('#players').typeahead({
name: 'players',
remote: function(query, cb){
$.ajax({
url: 'ajax/search.php',
type: 'POST',
data: 'query='+query,
dataType: 'JSON',
async: true,
success: function(data){
cb(data);
}
})
}
})
});
</script>
Ajax data file (PHP):
<?
if(isset($_POST['query'])){
include 'connect.php';
$query = $_POST['query'];
$sql = mysql_query("SELECT * FROM players WHERE name LIKE '%{$query}%'");
$array = array();
while($row = mysql_fetch_assoc($sql)){
$array[] = $row['name'];
}
echo json_encode($array);
}
?>
not 100% sure this is the issue, but perhaps try changing
data: 'query='+query,
to
data: {"query" : query},
I was having this issue and it fixed my problem
Related
I am trying to get the current code to take the on or off value from the form and put it into an SQL database using a function call to a JS function that contains an AJAX request that then posts it to a PHP page that runs the actual query. I am not sure what I have done wrong and the API has been more confusing than helpful. I appreciate any help!
Current Page Code:
<?php require('../php/validation.php');?>
<?php require('../php/background.php');?>
<?php
if(isset($_POST['selectonoff'])){
$_SESSION['onoff'] = $_POST['selectonoff'];
$query = 'UPDATE onoff SET onoroff = $_POST["selectonoff"] WHERE ID = 1;';
$update = mysqli_query($db, $query);
}
?>
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>User Settings Dropdown Menu</title>
<link rel="stylesheet" href="../css/settings.css">
<script type="text/javascript">
function load() {
document.getElementById("selectonoff").value = '<?php echo $_SESSION['onoff'];?>';
}
</script>
<script src="jquery.js"></script>
<script>
function rel(id)
{
jQuery.ajax({
type: "POST",
data: 'id='+id,
url: "../php/update.php",
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
</head>
<body onload="load();">
<!-- <div id="wrap"> -->
<br><br><br><br>
<h1>Admin Settings Menu</h1>
<form method="post" action="adminconfig.php">
<p>Toggle BBQ Form</p>
<select id="selectonoff" name="selectonoff" onchange="this.form.submit(); rel();">
<option value="NONE">Select</option>
<option value="ON">Toggle ON</option>
<option value="OFF">Toggle OFF</option>
</select>
</form>
<form action="../index.php">
<input type="submit" value="Home" />
</form>
<script type="text/javascript">
</script>
</body>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="../js/index.js"></script>
</html>
Current PHP Code:
<?php
require ('php/server.php');
$db = mysqli_connect('localhost', 'root', '', 'dedricks');
if(!$db){
die("Connection Failed: ".mysqli_connect_error());
}
$var = #$_POST['id'] ;
$query = 'UPDATE onoff SET onoroff = $var WHERE ID = 1;';
mysqli_query($db, $query);
?>
Few corrections needed here.
ERRORS
You are not reading the value of the select control anywhere in your code that needs to be sent in the ajax call
onchange for the selectonoff list is trying to submit the form and at the same time calling rel function (without any parameter). It seems like it needs to trigger the ajax call when the selectonoff selection is changed.
The jquery needs to be added once either via cdn or from local directory
It needs to be added before the script tag in the head.
TODO
Remove this.form.submit(); and rel from onchange. Rather remove the entire onchange
A code based on your page that is working and submitting the data to the php page is as below. You can make the changes according to your needs.
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>User Settings Dropdown Menu</title>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function rel(id){
var formData = {"id": id};
$.ajax({
type: "POST",
data: formData,
url: "../app/update.php",
cache: false,
success: function(response){
console.log("response", response);
alert("Record successfully updated");
},
error: function(error){
console.log("error", error);
}
});
}
$(document).ready(function(){
$("#selectonoff").change(function(){
var val = $("#selectonoff option:selected").val();
rel(val);
});
});
</script>
</head>
<body>
<!-- <div id="wrap"> -->
<br><br><br><br>
<h1>Admin Settings Menu</h1>
<form method="post" action="adminconfig.php">
<p>Toggle BBQ Form</p>
<select id="selectonoff" name="selectonoff">
<option value="NONE">Select</option>
<option value="ON">Toggle ON</option>
<option value="OFF">Toggle OFF</option>
</select>
</form>
<form action="../index.php">
<input type="submit" value="Home" />
</form>
</body>
</html>
NOTE
I have now tested the above code to be working and submitting the ajax request to a php script.
So I've got this form for adding comments under a post. The methods utilized here are MYSQL(holds the submitted form data in a database) PHP(communicating with the database) and JavaScript, more specifically AJAX (for hooking up the submit button and handling events).
Typing in your comment into the form and pressing submit is supposed to print the comment onto the screen.
When I click submit, it doesn't print anything. Then, when I type another comment and click submit once more, it prints the contents of that comment. Other times, it successfully prints the contents of the comment instead of failing to submit.
I checked it out in inspect element and in the console log, whenever it misses, it still sends some blank <p> tags through with the class of the comment that should be submitted.
The PHP page for the comment form:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="Forums.css">
</head>
<body>
<?php
$result = mysqli_query($link, $displayPost); ?>
<?php $row = mysqli_fetch_assoc($result);?>
<p> <?php echo $row["title"];?> </p>
<br>
<p> <?php echo $row["body"];?> </p>
<form action="<?php echo $url ?>" method="post" id="form-group">
<div class="forum col-md-12">
<textarea type="text" style="overflow: auto; resize: none;" name="body" class="txtBody"></textarea>
<input type="submit" name="submit" class="btnCreate" style="margin-bottom: 4px;">
</div>
</form>
</body>
<script>
function refreshData() {
$.ajax({
type:'GET',
url: 'getcomments.php?id=<?php echo $id ?>',
dataType: 'html',
success: function(result){
console.log(result);
$('#comments').html(result);
}
});
}
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData
});
refreshData();
event.preventDefault();
});
});
</script>
<div id="comments"></div>
The PHP page for getting previously submitted comments and printing them on the screen
<?php
$link = mysqli_connect("localhost", "root", "WassPord64", "forum");
$id = $_GET["id"];
$displayPost = "SELECT * FROM comments WHERE post_id='$id'";
$link->query($displayPost);
$result = mysqli_query($link, $displayPost);
if (mysqli_num_rows($result) > 0) :
// output data of each row
while($row = mysqli_fetch_assoc($result)) :
$row = mysqli_fetch_assoc($result);?>
<p class="postBody"><?php echo $row['body'];?></p>
<?php endwhile; ?>
<?php endif; ?>
You are calling refreshData() when the Ajax is not done. You can make a callback function by using $.ajax.success
Try this:
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData,
success: function(){
refreshData();
}
});
event.preventDefault();
});
});
I am newbie in php and javascript.
I want to know about the working of this function.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
echo ('I am in Send Push Nottification');
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
Q) My question is how this fuction sending the data php file
Like(http://uitdevelopers.site40.net/ClientServer/?name=qasim)
EDIT
Here is send_message.php
<?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once 'gcm.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
This is my php file and i want to execute it but i cannot understand this function
Edit
This is my index.html. Where i want to call this function
But it cannot working.
It is working staticaly but when I send data dynamically can't work
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
echo ('I am in Send Push Nottification');
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
require_once('db_functions.php');
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post"
onsubmit="return sendPushNotification( $row["id"])">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message"
placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send"
onclick="sendPushNotification( $row["id"])"/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
$.ajax means, call method ajax from the object $
this method will use http GET method, this means that array data will be appended to URL send_message.php after question mark ?
as soon as url does not start with / or protocol (like http://), current protocol, hostname and path will be used, so final string will be PROTOCOL://HOST[:PORT]/PATH/send_message.php?form_field_name=form_field_value&form_field_name2=form_field_value2
after forming full URL, this method will use browser-dependent method (for example XMLHTTPRequest) to call this url and call your JS function success with result
It gathers the data from your form in client side by using $('selector').serialize(); of jquery and get's all the data inside your php then if your server side has no errors it throws back to your client side to show all data's by using success if it is success or error if it fails. Ajax is for querying your result without reloading your page.
I have a weird problem. I have a form that populates with a button click event. This all works fine, except that once the form populates, it clears itself. Even Firebug gets cleared. I have stripped everything down to its most basic level, and cannot figure out what the issue is.
HTML:
<?php
require_once('../hyperlink.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Shipment Assignment</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<link rel="stylesheet" href="book.css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
<link rel="stylesheet" href="../css/tabletheme/style.css" type="text/css" id="" media="print, projection, screen" />
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>
<script type="text/javascript" src="../barcode/jquery-barcode.js"></script>
<script type="text/javascript" src="../js/tablesorter.min.js"></script>
<script src="book.js"></script>
</head>
<body>
<div id="header">
<?php display_user_hyperlinks(); ?>
<?php include ('../version.php'); ?> | Tip: Shipping Info</p>
</div>
<form>
<fieldset>
<legend>Shipping Assignments</legend>
Enter the PO that you would like to review: <input id="po"/><input type="submit" id="getPo" value="Retrieve"/>
</fieldset></form>
<form id="result">
<div id="hide">
<div id="cl" class="width border">
CL<input id="cl"/>
</div>
<div id="recv" class="width border">
REC<input id="rec"/>
</div>
<div id="pricePd" class="width border">
<input id="price" placeholder="Price Paid"/>
</div>
<div id="box" class="border">
<input id="title" style="width: 445px;" placeholder="Title"/><br>
<input id="isbn10" style="width: 445px;" placeholder="ISBN10"/><br>
<input id="isbn13" style="width: 445px;" placeholder="ISBN13"/><br>
</div>
</div></form>
<div id="remain"class="border">
Qty Rem: <input type="text" id="qtyRem"/>
</div>
</body>
</html>
book.js
$(document).ready(function() {
$("#getPo").click(function() {
$.ajax ({
type: "POST",
url: "poInfo.php",
async:false,
dataType: "json",
data: ({po: $('#po').val()}),
success: function(data){
console.log(data);
$("#isbn13").val(data.isbn);
$("#isbn10").val(data.isbn10);
$("#title").val(data.title);
}
}); //END OF AJAX
}); // END OF GETPO FUNCTION
});
poInfo.php:
<?php
ini_set('display_errors',"1");
require_once ('../db.php');
$conn = db_connect();
$i=0;
$po = 'JJD090969';
$result = $conn->query("select * from ship_assign where po = '$po'");
while ($row = $result->fetch_assoc()) {
$isbn10 = $row['isbn10'];
$isbn = $row['isbn13'];
$azLow = $row['azLow'];
$buyback101 = $row['Buyback101'];
$textRecycle = $row['textBookRecycle'];
$textRush = $row['textBookRush'];
$bookStores = $row['bookStores'];
$textBooks = $row['textBooks'];
$bookJingle = $row['bookJingle'];
$cash4Books = $row['cash4Books'];
$bookbyte = $row['bookbyte'];
$sellBack = $row['sellBack'];
$cheggBs = $row['chegg'];
$valore = $row['valore'];
$powell = $row['powell'];
$amzBuyBack = $row['amazonBuyBack'];
$collegeBooksDir = $row['collegeBooksDirect'];
$result2 = $conn->query("select title from book where isbn13 = '$isbn'");
$row1 = $result2->fetch_assoc();
$title = $row1['title'];
} //END OF WHILE STATEMENT
$guides= array('isbn10'=>$isbn10,'isbn'=>$isbn,'title'=>$title);
$conn->close();
echo json_encode($guides);
?>
Everything works as it should, except that the form clears once populated. I am hard coding in the po that I want to use instead of having to type it in every time, but the result is the same either way. Any ideas on how to fix this??
Try this:
$(document).ready(function() {
$("#getPo").click(function(event) {
event.preventDefault();
$.ajax ({
type: "POST",
url: "poInfo.php",
// async:false, deprecated
dataType: "json",
data: ({po: $('#po').val()}),
success: function(data){
console.log(data);
$("#isbn13").val(data.isbn);
$("#isbn10").val(data.isbn10);
$("#title").val(data.title);
}
}); //END OF AJAX
}); // END OF GETPO FUNCTION
});
I am using ajax to run a test id, but it does not work with code: 200 error.
And since ajax is not returning a value, it keeps getting error and prints "failed"
The id of add_user.html is checked in real time through the ajax of id_check.js.
However, memid_check.php, which sends data from id_check.js, does not seem to run.
to confirm
memid_check.php
echo "<script> alert('test!!!'); </script>";
.....
But did not run.
All files are in one folder, so the path seems to be fine
id_check.js
$(function(){
var id = $('.id_tbox');
var pwd =$('.pwd_tbox');
var name =$('.name_tbox');
var email =$('.email_tbox');
var idCheck = $('.idCheck');
$(".memcheck_button").click(function(){
console.log(id.val());
$.ajax({
type: 'post',
dataType: 'json',
url: "memid_check.php",
data:{id:id.val()},
success: function(json){
if(json.res == 'good'){
console.log(json.res);
alert("사용가능한 아이디");
idCheck.val('1');
}
else{
alert("다른 아이디 입력");
id.focus();
}
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
console.log("failed");
}
});
});
});
memid_check.php
<?php
echo "<script> alert('test!!!'); </script>";
include "db_c.php";
$id = $_POST['id'];
$sql = "SELECT * FROM add_user WHERE id = '{$id}'";
$res = $database -> query($sql);
if( res->num_rows >= 1){
echo json_encode(array('res'=>'bad'));
}
else{
echo json_encode(array('res'=>'good'));
}
?>
add_user.html
<?php
include "database.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=medium-dpi">
<link rel="stylesheet" href="add_user_style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/default.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nothing+You+Could+Do&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Cinzel|Permanent+Marker|Rajdhani&display=swap" rel="stylesheet">
<script type="text/javascript" src="id_check.js"></script>
</head>
<body>
<div class="aus_portrait"></div>
<div class ="aus_form" align ="center">
<div class="aus_box">Sign Up</div>
<form action="loginP.php" method="post">
<p class = "id">ID</p><input type="text" name="id" class="id_tbox">
<p class = "pwd">PASSWORD</p><input type="text" name="pwd" class="pwd_tbox">
<p class = "name">MAIL</p><input type="text" name="email" class="email_tbox">
<p class = "email">NAME</p><input type="text" name="name" class="name_tbox">
<input type="submit" class="sub_button" value="Submit">
<input type="button" class="exit_button" value="Cancel">
<input type="hidden" name="idCheck" class="idCheck">
<div class="memcheck_button">중복확인</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() { $(".exit_button").on("click", function(){ location.href="login.html"});}); </script>