not all ajax code working online - javascript

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

Related

Json_encode in While Loop

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;

Dependent Select Box using Jquery and Ajax in PHP

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;
?>

ajax not work and not show php data

when one record then show data when multiple record come then not show data other site.
ajaxx.php
<?php
include 'database.php';
session_start();
$post = $_POST;
$search = $post['search'];
$searchType = $post['searchType'];
if ($searchType == 'all')
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND (type='Bukhari' OR type='Muslim') ";}
else
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND type='$searchType' ";}
$result = mysqli_query($db,$sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row['title'];
echo json_encode($row);
}
} else
{ echo "Not Found Result" ; }
?>
when data record is one then append the data successfully when multiple record come then not show data and append not work
javascript code
function searchh()
{
var type = $("input[name='type']:checked").val();
var searchhh = $( ".myButton option:selected" ).text();
debugger;
$.ajax({
url: 'ajaxx.php',
type: "POST",
data: {'searchType':type, 'search':searchhh},
success: function (data) {
var duce = jQuery.parseJSON(data);
alert(duce.title);
}
});
}
I think your issue is in the while loop. You don't want to encode each row one-by-one, but as a whole like this.
$myResults = [];
while($row = $result->fetch_assoc()) {
$row['title'];
$myResults[] = $row;
}
echo json_encode($myResults);
You are producing invalid JSON by using echo json_encode($row); within a loop.
Try to craft an array of rows, and then display it.
if($result->num_rows > 0)
{
$output = array();
while($row = $result->fetch_assoc())
{
output[] = $row;
}
if($searchType == 'all')
{
echo json_encode($output);
}
else
{
echo json_encode(current($output)); // print just one
}
}

I want to autofill the dropdownlist using jquery and php

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>

how to select the select box item based on another and vice versa

how to select the select box item based on one another and vice versa.here I use ajax for redirect to query page.
while($fet = mysql_fetch_assoc($sql1))
{
echo "<option value=".$fet['username'].">".$fet['username']."</option>";
}
echo '</select></td>';
echo "<td><div id='myDiv'><select id=id name=id onchange=loadXMLDoc()>";
$sql = "select * from sample";
$sql1 = mysql_query($sql);
while($fet = mysql_fetch_assoc($sql1))
{
echo "<option value=".$fet['id'].">".$fet['id']."</option>";
}
echo '</select></div></td>';
You Need To Use Ajax For That,
For Example You Have A Select like This
<select id=id1 name=id1 onchange=loadXMLDoc()>
here is the second one you want to change
<select id=id2 name=id2>
On Javascript You Call a php file via ajax Like This
function loadXMLDoc(){
$.ajax({ // i think you used jquery on your project
type: "post",
url: "getdata.php",
data: $('input[\'name=id1\']'),
dataType: "json",
success:(function(result){
html = '';
if(result.data.length > 0){
$.each(result.data, function( index, value ) {
// alert( index + ": " + value );
html += '<option value="'+value.id+'">'+value.title+'</option>';
});
$('#id2').html(html);
}else{
// nothing
}
}));
});
}
then on php file you just echo the json_encode result you want to get
$sql = mysql_query('SELECT id,title FROM your_table Where your_field='.$_POST['id1']);
$query= mysql_query($sql);
while( $row = mysql_fetch_array($query)){
$json['data'][] = array('id' =>$row->id,'title'=>$row->title )
}
echo json_encode($json);

Categories

Resources