I've trying to set up a Question/Answer system and I've encountered with a couple of errors while setting up dependent select boxes
I wanna send the information of masters select box (Maters'id) to PHP file (DB.PHP) to handle a group of actions.
HTML Page
<?php
require_once "DB.php";
require_once "functions.php";
require_once "stuQuestion.php";
if(! isset($_SESSION['student'])){
redirect("stulogin/login.php");
die;
}
$date = userGets($connection , "students_questions" , $_SESSION['students_id']);
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#masters').on('change',function() {
var mid = $('#masters').val();
$.ajax({
url: 'DB.php',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: 'mid=' + mid
}).done(function(user){
console.log(user);
user = JSON.parse(user);
$('#topics').empty();
user.forEach(function(topic) {
$('#topics').append('<option>' + topic.topic + '</option>')
})
})
})
})
</script>
</head>
<select class="form-control" id="masters" name="masters" >
<option selected disabled>Choose Master</option>
<?php
//id='".$master['id']."' value = '".$master['id']."'
foreach($date as $master)
{
echo "<option id='".$master['id']."' value = '".$master['id']."'> ".$master['master']."</option>";
}
?>
</select>
<select class="form-control" id="topics" name="topics">
</select>
DB.php
function connectToDB() {
try {
$connect = new PDO("mysql:host=127.0.0.1;dbname=university","root","");
$connect->exec("set character set utf8");
$connect->exec("set names utf8");
$connect->setAttribute(PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION);
return $connect;
}
catch (PDOException $e)
{
die($e->getMessage());
} }
$connection = connectToDB();
if(isset($_POST['mid'])){
$statment = $connection->prepare("SELECT topic FROM students_questions
WHERE user_id = " . $_POST['mid']);
$statment->execute();
$user = $statment->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($user) ;
}
else
var_dump("No Request");
function userGets($conn , $table , $user_id = null) {
$statment = $conn->prepare("SELECT DISTINCT master FROM {$table} WHERE
user_id = :user_id");
$statment->bindParam("user_id" , $user_id );
$statment->execute();
$master = $statment->fetchAll(PDO::FETCH_ASSOC);
return $master ? $master : false;
}
When I log in and redirect to stuIndex.php (The page which contains select boxes)I will encounter with "No Request"! and after 3 days hunting around for probable correct answers, I couldn't solve it so far:(
Thanks in advance for any help you are able to provide.
PS: if someone needs more information, please tell me I will send the complete source code or sharing more information.
Too many jQuery and bootstrap libraries and they are HTTPS and HTTP versions from different CDNs
Syntax error in data :
No need for parsing the JSON since it is default
No error handling for the request. If you do not want error handling do this
$(function() {
$('#masters').on('change', function() {
var mid = this.value;
if (val) {
$.post('DB.php', {"mid": mid}, function(user) {
$('#topics').empty();
$.each(user,function(topic) {
$('#topics').append('<option>' + topic.topic + '</option>')
})
})
}
})
})
using
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/popper.min.js"></script>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
User inputs his phone number in an HTML form and then fills the google recaptcha, and presses a button. If the phone number section and recaptcha section are successfully completed, then a function named "sendOTP" is called from a javascript file, which uses the phone number to send an OTP to that number. Everything seems to be working, [except that I get this error]. I believe the phone number(which is represented as $_SESSION['Telephone'] is not passed successfully on to the javascript file to be used.
In this case, how can I pass on the variable to the javascript so that it can successfully send an OTP to the number?
Here is the validate-captcha.php code which validates the captcha, and if successful, it sends calls the sendOTP():
<?php
session_start();
$ph_number = '';
if (isset($_POST['g-recaptcha-response']))
{
$secret = "key1";
$ip = $_SERVER['REMOTE_ADDR'];
//echo $ip;
$response = $_POST['g-recaptcha-response'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$ip";
$fire = file_get_contents($url);
//echo $fire;
$numero = $_SESSION['Telephone'];
$data = json_decode($fire);
if ($data->success == true)
{
echo '<script type="text/javascript">
var $("#mobile").val() = "<?php echo"$numero"?>";
</script>';
echo '<script src="jquery-3.2.1.min.js" type="text/javascript"></script>';
echo '<script src="verification.js">
</script>';
echo '<script>sendOTP()</script>';
return 1;
}
else
{
echo "Please fill captcha";
echo $numero;
}
}
?>
Here's the javascript (verification.js) code:
function sendOTP() {
$(".error").html("").hide();
var number = $("#mobile").val();
if (number.length == 8 && number != null && (number.indexOf(5)==0 || number.indexOf(6)==0 || number.indexOf(9)==0)) {
var input = {
"mobile_number" : number,
"action" : "send_otp"
};
$.ajax({
url : 'controller.php',
type : 'POST',
data : input,
success : function(response) {
$(".container").html(response);
}
});
} else {
$(".error").html('Please enter a valid Hong Kong number!')
$(".error").show();
}
}
async function verifyOTP() {
var that = this;
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#mobileOtp").val();
var input = {
"otp" : otp,
"action" : "verify_otp"
};
if (otp.length == 6 && otp != null) {
const handlerA = async function() {
var res = false
try {
await $.ajax({
url : 'controller.php',
type : 'POST',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message);
$("." + response.type).show();
if (response.type=='success') {
res = true
} else if (response.type == 'error') {
res = false
}
},
error : function(response) {
console.log ('fail')
//console.log(data)
alert("Error encountered. Please try again later.");
}
});
return res;
} catch (err) {
console.error( err )
}
}
const handlerB = async function () {
await $.ajax({
url : 'submission.php',
type : 'POST',
data : input,
dataType : "json",
success : function(response) {
$(".container").html(response);
}
})
}
let $resultA = await handlerA()
// Now exec B
if ($resultA == true) {
let $resultB = await handlerB();
$resultB;
}
} else {
$(".error").html('You have entered wrong OTP.')
$(".error").show();
}
}
If necessary, then here is the PHP file(controller.php) where the sendOTP() function is defined:
<?php
session_start();
error_reporting(E_ALL & ~ E_NOTICE);
require ('textlocal.class.php');
include('config/db_connect.php');
class Controller
{
function __construct() {
$this->processMobileVerification();
}
function processMobileVerification()
{
switch ($_POST["action"]) {
case "send_otp":
$mobile_number = $_POST['mobile_number'];
$sender = 'me';
$otp = rand(100000, 999999);
$_SESSION['session_otp'] = $otp;
$message = "Your One Time Password is " . $otp;
$numbers = array(
$mobile_number
);
$url = 'https://www.something.hk/s.php';
$data = array(
"user" => "user",
"pass" => "password",
"to" => $mobile_number,
"from" => $sender,
"unicode" => 0,
"mess" => $message,
"otp" => 1,
"schtime" => 0
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
require_once ("verification-form.php");
break;
case "verify_otp":
$otp = $_POST['otp'];
$MPF_account = $_SESSION['MPF_account'];
$Telephone = $_SESSION['Telephone'];
$Gender = $_SESSION['Gender'];
$Job = $_SESSION['Job'];
$Monthly_salary = $_SESSION['Monthly_salary'];
$Existing_loan = $_SESSION['Existing_loan'];
$Residential_Type = $_SESSION['Residential_Type'];
$Existing_loan = $_SESSION['Existing_loan'];
$Job_Type = $_SESSION['Job_Type'];
$Existing_loan_amount = $_SESSION['Existing_loan_amount'];
if ($otp == $_SESSION['session_otp']) {
unset($_SESSION['session_otp']);
echo json_encode(array("type"=>"success", "message"=>"Thank You! Your form has been successfully submitted." ,"MPF_account"=>$MPF_account,
"Telephone"=>$Telephone,"Gender"=>$Gender,"Job"=>$Job,"Monthly_salary"=>$Monthly_salary,"Existing_loan"=>$Existing_loan,
"Residential_Type"=>$Residential_Type,"Existing_loan"=>$Existing_loan,"Job_Type"=>$Job_Type,"Existing_loan_amount"=>$Existing_loan_amount
));
}
else {
echo json_encode(array("type"=>"error", "message"=>"Mobile number verification failed"));
}
break;
}
}
}
$controller = new Controller();
?>
Also, here is the HTML form that was used at the first stage:
<!DOCTYPE html>
<html>
<head>
<title>OTP SMS</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="verification.js"></script>
<?=(isset($_POST['g-recaptcha-response']) && $data->success) ? "<script>sendOTP()</script>" : ""?>
</head>
<body>
<div class="container">
<div class="error"></div>
<form action="validate-captcha.php" id="frm-mobile-verification" method="POST">
<div class="form-heading">Mobile Number Verification</div>
<div class="form-row">
<input type="number" id="mobile" class="form-input" placeholder="Enter the 8 digit mobile" value="<?php echo $_SESSION['Telephone'] ?>">
</div>
<div method="post" class="g-recaptcha" data-sitekey="key2"></div>
<input type="submit" name="submit" value="Submit" class="btn brand z-depth-0">
</form>
</div>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="verification.js"></script>
</body>
</html>
Fixing JavaScript output by PHP
You have this in your code:
var $("#mobile").val() = "<?php echo"$numero"?>";
This is not valid JavaScript you are outputting.
var must be used with a variable name. That is what the syntax error is supposed to tell you.
What you intended is to set the value. Look at the jQuery documentation on how to do that:
https://api.jquery.com/val/#val2
That leaves us with this solution...
$("#mobile").val("' . $numero . '");
...which puts the value for $numero from the PHP variable into the input field with id mobile.
Fixing the order of JavaScript
Your PHP code now outputs this:
echo '<script type="text/javascript">
var $("#mobile").val() = "' . $numero . '";
</script>';
echo '<script src="jquery-3.2.1.min.js" type="text/javascript"></script>';
Notice you add jQuery after you do $("#mobile").val(), which requires jQuery. So you have to add jQuery first (includes the fix from before):
echo '<script src="jquery-3.2.1.min.js" type="text/javascript"></script>';
echo '<script type="text/javascript">
$(document).ready(function(){
$("#mobile").val("' . $numero . '");
});
</script>';
Notice I also added a document.ready handler to load the HTML document first before calling the JavaScript.
Please respect the comments
Please read the comments again. They were trying to help you discover the JavaScript error there. You were insisting your code is okay - or at least your wording indicated you don't see the problem at all - you "just need the solution".
They were hinting you should rethink and you were showing no signs of understanding the syntax error is fault of your code.
You are supposed to go "Oh maybe the syntax is wrong, I will check the documentation again how to do that".
Hello I'm a beginner in Ajax and PHP so sorry if my question is useless or stupid. But I am trying to do a live search with ajax and I have looked over and over internet but nothing could help me... so here I am! :-) I have 4 files one for the html, one to connect to the database, one for jQuery and the last one for the script in php. I have looked on the console with chrome and I can see that the ajax works but there is no output and I have no idea why... I'll leave you the code below and an early thank you! Also there might be some French in the code but it's just the variables and I will secure my connection to the database later. Thank you again.
Html :
<html>
<head>
<meta charset="utf-8" />
<title>live search test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche">
</div>
<br>
<div class="resultat" id="resultat">
</div>
</body>
</html>
PHP to connect to the database:
<?php
$host="localhost";
$user="root";
$password="";
$db="smartphone";
$conn=mysqli_connect($host,$user,$password,$db);
?>
jQuery:
$(document).ready(function(){
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef = ' + recherche;
if (recherche.length > 1) {
$.ajax({
type : "GET",
url : "fetch.php",
data : data,
success : function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
});
And the script in PHP:
include'connect.php';
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn ->prepare($sql);
$req -> execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req -> fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result ->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
?>
Remove whitespace from 'motclef = '
var data = 'motclef= ' + recherche;
Other wise put underscore $_GET['motclef_'] in your PHP code(if you don't remove space then)
if (isset($_GET['motclef_'])) {
$motclef = $_GET['motclef_'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn->prepare($sql);
$req->execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req->fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
i am trying to autocomplete using bootstrap typeahead but its not fetching results.
i tried many times using jquery,ajax
index.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="typeahead.js"></script>
<script>
$(function() {
$('#typeahead').typeahead({
source:function(typeahead,query)
{
$.ajax({
url :'mysql.php',
type :'POST',
data :'query=' + query,
dataType :'json',
async :false,
success:function(data)
{
typeahead.process(data);
}
});
}
});
});
</script>
</head>
<body>
<input type="text" name="term" id="typeahead" class="form-control" size="50" placeholder="Search" >
</body>
</html>
mysql.php
<?php
$conn = mysqli_connect('localhost', 'root','','mydb');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$searchTerm = $_POST['query'];
$query = mysqli_query($conn,"SELECT * FROM content_ref_table WHERE title LIKE '%{$searchTerm}%' ORDER BY title ASC");
while ($row = mysqli_fetch_assoc($query)) {
$data[] = $row['title'];
}
echo json_encode($data);
?>
i am using typeahead along with ajax call,but its not giving results
I believe you are using bootstrap3-typeahead / or another bootstrap 2.x typeahead deriviation? If so, you have messed up the arguments for the source method - it should be process, query where process is the async callback. Your code could be reduced to
$('#typeahead').typeahead({
source: function(query, process) {
var url = 'mysql.php?query=' + query
return $.get(url, {}, function(data) {
return process(data)
})
}
})
I am trying to populate a dynamic dropdown list based on the value user has inserted in the previous textbox(auto-complete). So, when user insert an actor/actress name in the auto-complete textbox, a dropdown will be populated by list of movies in which that actor has played.
Problem:
Could someone kindly let me know what is the problem with this code and why it populate an empty dropdown?
Here is the html/js code:
<html>
<?php
print_r($_POST);
?>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
</head>
<body>
Source:
<input type="textbox" name= "tag" id="tags">
<select id="movieImdbId" name="movieImdbId[]" multiple="multiple" width="200px" size="10px" style=display:none;>
</select>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
$("#tags").change(function () {
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#movieImdbId").html(response).show();
});
});
}
});
});
</script>
</body>
</html>
and this is actions.php code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['q']) && !empty($_POST['q'])){
$q = $_POST['q'];
$html = "";
try{
$conn = new PDO('mysql:host=localhost;dbname=imdb;charset=utf8mb4','user','pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = $conn->prepare("SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q");
$sql->execute(array(':q' => $_POST['q']));
while($rows = $sql->fetch(PDO::FETCH_OBJ)){
$option = '<option value="' . $rows['movieImdbId'] . '">' . $rows['movieImdbId'] . '</option>';
}
$html .= $option;
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
I really appreciate if someone can help me fix it.
Thanks.
You call via POST
$.post("actions.php")
but check for GET Variables
if(isset($_GET['q']) && !empty($_GET['q']))
So i guess your php script delivers an empty string.
Print the response to console and see if you get a result.
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
});