I need to get data from the database with ajax and put that data in the 'select' tag. I need to have every name in a different 'option'... View the code:
Index.php:
<label>Select:</label>
<select id="users"></select>
JS:
$(document).ready(function() {
setInterval(function() {
$.get("frombase.php", function(data) {
data = JSON.parse(data);
for (var id in data) {
$("#users").empty();
$("#users").append("<option value='"+ id +"'>"+ data[id] +"</option>")
}
});
}, 1000);
});
And frombase.php:
$sql = "SELECT * FROM `users`";
$result = mysqli_query($db, $sql);
$name = array();
while ($row = mysqli_fetch_assoc($result)) {
$name[] = $row['name'];
}
echo json_encode(array("name" => $name));
mysqli_close($db);
Look at the result (I do not need this)
(My english is not good, because I use Google Translate)
I would do in this way...
JS:
$(document).ready(function() {
$.ajax({
url :'frombase.php',
type: "POST",
dataType: "json",
success : function(data){
$("#users").empty();
$(data['options']).each(function(k,v){
$("#users").append("<option value='"+ v['id'] +"'>"+ v['name'] +"</option>");
});
},
error:function(){
alert('Error of server comunication');
}
});
});
PHP:
$db = 'YOUR CONNECTION';
$query = $db->prepare("SELECT id,name FROM users");
$query->execute();
$query->bind_result($id,$name);
while ($query->fetch()) {
$result[] = array('id'=>$id,'name'=>$name);
}
$root['options'] = $result;
$root = json_encode($root);
$db->close();
echo $root;
Related
I want a dependent select box I can load the data from my database into the select box however, when I click the show all countries when all select boxes have data only the province will return to the default data. What I need to do is when I click show all countries all the data from select box will reset to its default data and so on and so forth.
AJAX Script:
$(document).ready(function(){
//Show Province
$("#sort-country").change(function(){
var country = $(this).val();
$.ajax ({
url:"fetch_province.php",
method: "POST",
data: {country:country},
dataType: "text",
success: function(data){
$("#sort-province").html(data);
}
});
});
//Show Town
$("#sort-province").change(function(){
var country = $("#sort-country").val();
var province = $(this).val();
$.ajax ({
url:"fetch_town.php",
method: "POST",
data: {country:country, province:province},
dataType: "text",
success: function(data){
$("#sort-town").html(data);
}
});
});
//Show Barangay
$("#sort-town").change(function(){
var country = $("#sort-country").val();
var province = $("#sort-province").val();
var town = $(this).val();
$.ajax ({
url:"fetch_barangay.php",
method: "POST",
data: {country:country, province:province, town:town},
dataType: "text",
success: function(data){
$("#sort-barangay").html(data);
}
});
});
});
Fetch Province:
<?php
require "connect.php";
$output = "";
$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' ORDER BY province";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Province</option>";
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='".$row['province']."'>".$row['province']."</option>";
}
echo $output;
?>
Fetch Town:
<?php
require "connect.php";
$output = "";
$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' AND province='".$_POST['province']."' ORDER BY town";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Town</option>";
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='".$row['town']."'>".$row['town']."</option>";
}
echo $output;
?>
Fetch Barangay:
<?php
require "connect.php";
$output = "";
$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' AND province='".$_POST['province']."' AND town='".$_POST['town']."' ORDER BY barangay";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Barangay</option>";
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='".$row['barangay']."'>".$row['barangay']."</option>";
}
echo $output;
?>
I have this code:
$.ajax({
type: "POST",
url: 'gets/getQuery.php',
data: {'type': $("#type").val(),'isAjax':true},
dataType:'json',
success: function(data) {
var select = $("#type"), options = '';
select.empty();
options = "<option value=''></option>";
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";
}
select.append(options);
}
});
where:
<select id="type"></select>
I'm using this same code about 10 times with different select (different IDs and different getQuery.php file).
On localhost,everything is working fine,however,on online server,only 2 of the selects can read data from php file.
This is the php code of getQuery.php:
<?php
include("../db.php");
if (isset($_POST['type'])) {
$type = trim($_POST['type']);
$result = array();
$type = mysqli_real_escape_string($con,$type);
$res = mysqli_query($con,"SELECT * FROM Table order by Type");
while ($row = mysqli_fetch_array($res)) {
$result[] = array(
'id' => $row['ID'],
'name' => $row['Type']
);
}
echo json_encode($result);
}
?>
Anyone knows what might be the problem?
Thanks
I have an UI in which the user can add objects (stored as JSON in my database). So, when the user is clicking on a button, it calls the ajax wich calls my php to get the desired JSON code.
The problem is that my ajax returns me "success" but with no JSON code. I don't know where the problem is located.
Here's my JS/AJAX:
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: {objectId: objectId},
dataType: 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
Here's my scriptObject.php:
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.");
echo json_encode($res);
[EDIT]
It answers me:
{"status":"error","message":"Problem in fetching data."}
Try following
<script type="text/javascript">
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
dataType : 'json',
data: { objectId: objectId },
success: function(response) {
var json = $.parseJSON(response);
if(json.status == 'error')
console.log(json.message);
else if(json.status == 'success')
console.log(json.objectJson);
}
});
</script>
and in scriptObject.php
<?php
// your database connection goes here
include 'config.php';
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.".mysql_error());
echo json_encode($res);
?>
scriptObject.php
if(isset($_POST['objectId']))
{
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
die;
}
you are execution the php code inside a function.
how does the compiler or the interpreter know to execute a function inside your php file.
Add dataType to your ajax options
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: objectId,
dataType : 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
then your php code
function getObjectJson() {
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
}
Below is my php file to apply query
$host = "localhost";
$user = "root";
$pass = "abc123";
$databaseName = "class";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT id, name FROM lecturer");
if (mysql_num_rows($result)) {
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
header('Content-type: application/json');
echo json_encode( $data );
}
And this is my other file where i am applying javascript. I have searched a lot of same queries but could not find solution. Please help me
<script type="text/javascript">
function lecturer(){
$("#a1_title").empty();
$("#a1_title").append("<option>Default</option>");
$.ajax({
type:'POST',
url : 'get-data.php',
contentType :"application/json; charset-utf8",
dataType:'json',
type:'POST',
success:function(data){
$('#a1_title').empty();
$('#a1_title').append("<option>Default</option>");
$.each(data, function(i, data){
$('#a1_title').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
});
},
complete: function(){
}
)};
}
$(document).ready(function(){
lecturer();
});
</script>
Please help me I have tried to solve this problem buy i am not able to do it.
Your PHP code had bad syntax since you had your array() was surrounded with curly braces rather than parentheses. You also had some errors in your $.ajax, a misplaced parentheses. In addition, you do not need an iterator ([i]) in your $.each() function - you can just get each item's bit of information by associating this iteration's values. And as #Jay Blanchard said, mysqli would be used best here.
Try the following editions:
PHP:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "test";
$con = mysqli_connect($host, $user, $pass, $databaseName);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, name FROM lecturer");
if (mysqli_num_rows($result)) {
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
JS:
<script type="text/javascript">
function lecturer() {
$("#a1_title").empty();
$("#a1_title").append("<option>Default</option>");
$.ajax({
type: 'POST',
url: 'get-data.php',
contentType: "application/json; charset-utf8",
dataType: 'json',
type: 'POST',
success: function (data) {
$('#a1_title').empty();
$('#a1_title').append("<option>Default</option>");
$.each(data, function (k, v) {
$('#a1_title').append('<option value="' + v.id + '">' + v.name + '</option>');
});
},
complete: function () {
}
});
}
$(document).ready(function () {
lecturer();
});
</script>
I have tried removing the JSON.stringify and changing the post to get change cache to false and true. I am at a loss as to what needs to happen. It always goes to the else statement in my php and returns the default JSON. I have allowed crossdomain in my php with the wildcard so that is definitely not the problem.
Code:
$(document).ready(function() {
$('.check').click(function(){
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "POST",
crossDomain: true,
url: "retrieveColumn.php",
data: JSON.stringify({ ID: thisID}),
cache: true,
async:true,
datatype: "json",
success: function(data)
{
console.log(data);
alert(data);
}
});
});
});
PHP which always goes to the else condition:
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID ");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
}
else
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = 2");
$row = $stmt->fetch_assoc();
print json_encode($row);
}
Unless this is part of a larger document, you have unnecessary brackets which might be causing problems.
if(isset($_POST['ID'])){
$ID = $_POST['ID'];
{ /* <!-- HERE! What is this?? */
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID ");
if($stmt->num_rows) //if there is an ID of this name{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
}
else
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = 2");
$row = $stmt->fetch_assoc();
print json_encode($row);
}
You don't need to stringify the object you submit as data here:
data: JSON.stringify({ ID: thisID}),
Use:
data: { ID: thisID},