I dont know if i am tired or why i cannot get it right please help what i need is
<script language="javascript">
$(document).ready(function(){
getResultsCountry();
})
function getResultsCountry() {
$.ajax({
url:'suggest_country.html',
type:'POST',
data: 'q=',
dataType: 'json',
success: function( json ) {
$('#country')[0].options.length = 0;
$.each(json, function(i, value) {
if (value=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(value).attr('value', value).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(value).attr('value', value));
};
});
}
});
};
</script>
Code in external file looks like
<?php
$results = mysql_query('SELECT DISTINCT country FROM MyTable WHERE country LIKE \'%\' ORDER BY country');
while( $result = mysql_fetch_array($results) ) {
$cities = $cities.' short = \''.$result['country'].'\' OR';
}
$cities = substr($cities, 1,strlen($cities)-3);
$results2 = mysql_query('SELECT full, short FROM `Countries` WHERE '.$cities);
$json = array();
while( $result2 = mysql_fetch_array($results2) ) {
$json[] = $result2['short'].','.$result2['full'];
}
echo json_encode( $json );
mysql_close($db2);
?>
Response i am getting is
["AG,ANTIGUA AND BARBUDA","AU,AUSTRALIA","BR,BRAZIL","CA,CANADA","KY,CAYMAN ISLANDS","CN,CHINA"]
What i need is to fill it in the options for tag i got this part too, but i cannot make it fill country code AG as value and name as name like
<option value="AG">Antigua</option>
please break it down for me i am really confused and tired its been hours of headache.
You need to split values
$.each(json, function(i, value) {
var arr_values = value.split(',');
if (value=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(arr_values[1]).attr('value', arr_values[0]).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(arr_values[1]).attr('value', arr_values[0])));
};
});
It would make your ajax callback much easier if you didn't have to split your strings..
while( $result2 = mysql_fetch_array($results2) ) {
$json[] = array('short'=>$result2['short'],
'full' => $result2['full']
);
}
And then you can parse by
$.each(json, function(i, value) {
if (value['full']=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(value['full']).attr('value', value['short']).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(value['short']).attr('value', value['full'])));
};
});
Related
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;
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 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 a drop down box with multiple select . The dropdown looks like this:
<select multiple class="form-control" name="batch_no[]" id="batch_no" required onchange="getBatchCourseDetail();">
<option value="">-----------Select Your Batch----------</option>
<?php
foreach ($result as $res)
{
?>
<option value="<?php echo $res['batch_code']; ?>"><?php echo $res['batch_code']; ?></option>
<?php
} ?>
</select>
In onchange function call i have the script like this:
function getBatchCourseDetail()
{
var other = String($('#batch_no').val());
var opts = [],
opt;
var split1 = other.split(',');
for (var i = 0; i < split1.length; i++)
{
opt = split1[i];
opts.push(opt);
}
$.ajax({
url: 'course_apply_batch_course_detail_ajax.php',
type: 'POST',
data:
{
batch_code: opts
},
success: function (data)
{
//console.log(data);
$('#batch_information_autofill').html(data);
}
});
}
In the ajax file that is in course_apply_course_detail_ajax.php page I retrieve all the values of the drop down .
course_apply_course_detail_ajax.php :
<?php
require('classes/autoloader.php');
$course_apply = new \Model\CourseApplyModel();
$batch_code111=array();
$batch_code111 = $_POST['batch_code'];
$batch_code1 ="'" .implode("','",$batch_code111) ."'";
$parameter = array(
"batchcode" => $batch_code1,
"status" => 0);
$result11 =$course_apply->getBatchCourseDetail11($parameter);
echo"<pre>";
print_r($result11);
echo"</pre>";
exit;
?>
I will be getting the $batch_code1 values as : 'LATS-CHMB-1000','LATS-SA-1000','LATS-ABSE-1003' which is stored in the array variable 'batchcode'.
In Model My query looks like this:
public function getBatchCourseDetail11($parameter)
{
/* $QUERY1="SELECT start_date,end_date,course_code FROM batch WHERE
batch_code IN('LATS-CHMB-1000','LATS-SA-1000','LATS-ABSE-1003') AND status =0"; */
$query1="SELECT start_date,end_date,course_code FROM batch WHERE status =:status AND batch_code IN(:batchcode)";
try{
$result1=$this->dbh->prepare($query1);
$result1->execute($parameter);
$data11=$result1->fetchAll(\PDO::FETCH_ASSOC);
return $data11;
}
catch(\PDOException $e)
{
print_r($e);
return false;
}
}
When i try to print the return data i'm getting array() but the query is executing correctly in the phpmyadmin.
Thanks in advance please help me to get solved from this issue.
The query is your issue
$query1="SELECT start_date,end_date,course_code
FROM batch
WHERE status =:status
AND batch_code IN(:batchcode)";
it is not possible to substitute an arbitrary query part with a placeholder. So for a comma-separated placeholders, like IN(), you must create a set of ?'s manually and put them into the query:
In short we must create a syntax like IN(?,?,?) if you have 3 values you want in your IN() list and then pass the 3 paremeters to the prepare.
public function getBatchCourseDetail11($parameter)
{
// generate the number of ? we need
$ins = str_repeat('?,', count($parameter['batchcode']) - 1) . '?';
$query1="SELECT start_date,end_date,course_code
FROM batch
WHERE status = ?
AND batch_code IN($ins)";
try{
$result1=$this->dbh->prepare($query1);
$params[] = $parameter['status'];
foreach ( $parameter['batchcode'] as $p ) {
$params[] = $p;
}
$result1->execute($params);
$data11=$result1->fetchAll(\PDO::FETCH_ASSOC);
return $data11;
}
catch(\PDOException $e) {
print_r($e);
return false;
}
}
Currently I am trying to create a live search bar that only produce 5 results max and more option if there is over 5 results. So what I have done so far is a jquery ajax script to call a php script that runs asynchronously on key up in textbox I have.
I want to get the php array then I will code it further using javascript.
This is my code now:
Javascript code
<script type="text/javascript">
function find(value)
{
$( "#test" ).empty();
$.ajax({
url: 'searchDb.php',
type: 'POST',
data: {"asyn": value},
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
});
}
</script>
SearchDb PHP code:
<?php
function searchDb($abc, $limit = null){
if (isset($abc) && $abc) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$abc%'";
if($limit !== null){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
$lists = array();
while ( $row = mysql_fetch_assoc($result))
{
$var = "<div>".$row["testa"]."</div>";
array_push($lists, $var);
}
}
return $lists;
}
$abc = $_POST['asyn'];
$limit = 6;
$lala = searchDb($abc);
print_r($lala);
?>
How can I get $lala
Have you considered encoding the PHP array into JSON? So instead of just echoing the array $lala, do:
echo json_encode($lala);
Then, on the Javascript side, you'll use jQuery to parse the json.
var jsonResponse = $.parseJSON(data);
Then you'll be able to use this jsonResponse variable to access the data returned.
You need to read jQuery .ajax and also you must view this answer it's very important for you
$.ajax({
url: 'searchDb.php',
cache: false,
type: 'post'
})
.done(function(html) {
$("#yourClass").append(html);
});
In your searchDb.php use echo and try this code:
function searchDb($str, $limit = null){
$lists = array();
if (isset($str) && !empty($data)) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$data%'";
if(0 < $limit){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
while ( $row = mysql_fetch_assoc($result))
{
$lists[] = "<div>".$row["testa"]."</div>";
}
}
return implode('', $lists);
}
$limit = 6;
$data = searchDb($_POST['asyn'], $limit);
echo $data;
?>
If you dont have or your page searchDb.php dont throw any error, then you just need to echo $lala; and you will get result in success part of your ajax function
ALso in your ajax funciton you have
//you are using data here
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
you must try some thing like this
success: function(data) {
var lala = data;
$( "#test" ).html($lala);
}