I am trying to make a select have some pre-loaded options.
I have a php script that queries for these options, and I want to load them into the select on an html page.
My attempt right now..
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$("#usersList").html(data.value);
});
});
});
</script>
</head>
<body>
<form>
Find Users in: <select id="usersList" name="usersList">
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
PHP
<html>
<head>
</head>
<body>
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$ary[] =$info['State'];
}
mysql_close();
?>
</body>
</html>
My PHP works fine, but I am not sure how to get that information into my select.
All help appreciated!
First:
The html select-tag needs to get closed like this:
<select></select>
Next:
Your $ary isnt defined anywhere and it isnt returned anywhere
Use json_decode(); to return json
(and dont use any html head/body in your php file which outputs json)
Your json.php:
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
$ary = Array();
while($info = mysql_fetch_array( $data ))
{
array_push($ary,$info["state"]);
}
mysql_close();
echo json_encode($ary);
?>
Next:
You need to append option tags to your select with jquery like this:
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$.each(data,function(key,indata){
$("#usersList").append($("<option>",{
html : indata
}));
})});
});
});
Seems you have jquery library is missing. Please add it after the <head> tag and try:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the php, after mysql_close(). Add
print json_encode($ary);
Related
I am updating my site content with AJAX by using this method i have found here: https://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html
This works very well but according to this tutorial i have to echo the values i want to show as an updated value in the background running "record_count.php". Later all values are shown up in my frontend file "index.php" within the specific <div id="xxx">. my problem is now that in my background "record_count.php" i have several values i echo but in need them in separate HTML <div id="1, 2, ...> In my example it is $name and $city. How can i connect the values to a specific HTML <div id="1, 2, ...> ? (Please ignore the old query method i have copy/paste here. In my code i am using prepared statements with PDO)
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php?q=<?php echo $id; ?>').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
<body>
<div id="load_tweets"> </div>
</body>
</script>
record_count.php
<?php
include("db.php");
$search_word=$_GET['q'];
$sql = mysqli_query($db,"Select name, city FROM users where id = $id");
$record_count=mysqli_num_rows($sql);
//Display count.........
echo $city;
echo $name
?>
Is this the right way to retrieve data from mysql using jquery? The php side is working fine ($data gets printed onto the page) but jquery doesn't seem to be receiving the variable at all.
Besides that, is there a way to get the jquery function to run after the page AND after the google maps initMap() function has finished loading? Is it possible to include jquery code inside a standard javascript function?
admin.php
<?php
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
echo json_encode($data);
?><!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
What I've tried
js/admin.js
$(document).ready(function() {
$.ajax({
url: '../admin.php',
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
})
});
I received a "404 Not found" error in the console
The 404-Error indicates that you are using a wrong URL in your jQuery code to get the data. Try to enter not just the filename but the whole URL like https://example.com/admin.php for the url parameter.
Besides your problem getting the data via jQuery, what happens when you open admin.php directly in your browser? Are you getting the $data AND your HTML Code? If thats the case I would recommend you to wrap the whole PHP-Code inside an if-statement:
if($_SERVER['REQUEST_METHOD'] === 'POST'){
header('Content-Type: application/json');
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
die(json_encode($data));
}
else{ ?>
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
<? } ?>
Now, if its a POST-Request like from your js, the PHP will return the data as JSON. Also the right header will be set. If its not a POST-Request the PHP will return your HTML.
To your other question: Yes, it is possible to use jQuery in a normal JavaScript function.
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.
Please someone help, I am really going to be crazy!.
I have a PHP form with some questions and one of the question is "Which are your favourite movies?" for which I used jQuery auto-complete feature which works fine!. However, It is possible that users forget the name of a movie, but remember an actor that played in that movie. So, I would like to enable user typing an actor/actress name in the auto-complete textbox (e.g., "Tom Cruise") and based on inserted actor name, a dynamic dropdown menu should be added which contains list of movies that the actor (e.g, Tom Cruise) has played in them.
This is what I tried but not work :((
<html>
<?php
print_r($_POST);
?>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"/>
</head>
<body>
<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" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php", //php file which fetch actors name from DB
minLength: 2,
select: function (event, ui){
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.
$("#movieImdbId").html(response).show();
});
}
});
});
</script>
</body>
</html>
and this is actions.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_GET['q']) && !empty($_GET['q'])){
$q = $_GET['q'];
include('Connection.php'); //connection to the DB
$sql = $conn->prepare("SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q");
$sql->execute(array(':q' => $q));
$html = "";
while($row = $sql->fetch(PDO::FETCH_OBJ)){
$option = '<option value="' . $row->movieImdbId . '">' . $row->movieImdbId . '</option>';
$html .= $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
Question: Why when user insert an actor name in the text-box, the dropdown menu is populated but is EMPTY?
In your ajax call, you send a POST request, and you try to get the params with $_GET in you php.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags.
$("#movieImdbId").html(response).show();
});
change the $.post method to $.get.
OR
if(isset($_GET['q']) && !empty($_GET['q'])){
$q = $_GET['q'];
}
change $_GET to $_POST.
I am trying to see if a username has already been taken in a mysql database and it does not seem to want to work. Ideally it would show as I was typing on the form. Any help would be greatly appreciated as I do not see anything wrong with the code.
On my main page is the code for the jquery, javascript and html.
The corresponding page is testusername.php.
<script type="text/javascript">
$(document).ready(function() {
$('#feedback').load('testusername.php').show();
$('#username_input').keyup(function() {
$.post('testusername.php', { username:form.username.value },
function(result) {
$('#feedback').html(result).show();
});
});
});
</script>
<form name='form'>
<fieldset>
<legend>Test Form</legend>
Username: <br /><input type='text' id='username_input' name='username'></input>
</fieldset>
</form>
<div id = "feedback"></div>
testusername.php is:
<?php
include 'functions2.php';
?>
<?php
$username = mysql_real_escape_string($_POST['username']);
$query1a = mysql_query("SELECT * FROM users WHERE username='$username'");
$count = mysql_num_rows($query1a);
if ($count==0)
{
echo "Available";
}
else {
echo "Username exists";
}
?>
This script should work to handle your client side part, Assuming you have jQuery loaded to your pafe properly.
<script type="text/javascript">
$(document).ready(function() {
$('#username_input').keyup(function() {
$.post('testusername.php', { username: $(this).val() },function(result){
$('#feedback').html(result).show();
});
});
});
</script>
For the server side, dont use * in the query. You may use something like SELECT 1 FROM .... Also you may want to make sure you are not going to be a victim of SQL Injection.