I try to get the cities according to the country which is passed as parameter and sent via ajax. But for some countries I can get cities and update my form with these cities, for against for other I have this error
{"readyState":0,"responseText":"","status":0,"statusText":"OK"}
When I look in logs for those countries that returns me an error I have the names of the cities retrieved from the database.
I do not understand why this error.
how can I fix it?
Please find below my code
Model
function get_ville_depart($country = null){
$this->db->select('NUMVILLEDEPART, NOMVILLEDEPART')->from('villedepart');
$this->db->join('pays','pays.NUMPAYS=villedepart.numpays');
$this->db->where('pays.NUMPAYS', $country);
$this->db->order_by("NOMVILLEDEPART","asc");
$query = $this->db->get();
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
}
return $cities;
}else{
return FALSE;
}
}
Controller
function get_ville_depart($country){
foreach($this->ville_model->get_ville_depart($country) as $ville){
log_message('debug',json_encode($ville));
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($this->ville_model->get_ville_depart($country));
}
View
$('#paysdepart').on("change",function(){
$("#villedepart > option").remove();
var country_id = $('#paysdepart').val();
var base_url="<?= site_url('annonce');?>";
$.ajax({
type: "GET",
url: base_url+"/get_ville_depart/"+country_id,
dataType:'json',
success: function(cities)
{
if(!jQuery.isEmptyObject(cities))
{
$("#ifnotvilledepartindatabase").hide();
$("#dynamicvilledepart").show();
$.each(cities,function(NUMVILLEDEPART,NOMVILLEDEPART)
{
var opt = $('<option />');
opt.val(NUMVILLEDEPART);
opt.text(NOMVILLEDEPART);
$('#villedepart').append(opt);
});
}else
{
$("#dynamicvilledepart").hide();
$("#ifnotvilledepartindatabase").show()
}
},
error:function(error)
{
alert("Error "+JSON.stringify(error));
$("#dynamicvilledepart").hide();
$("#ifnotvilledepartindatabase").show()
}
});
});
Error in those country which does not have any City.
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
}
return $cities;
}else{
return new stdClass; /* Only this line have to change */
}
Use direct URL to see the error for the particuler Country ID.
I have tested in local everything if fine .
Everything seems fine to me, but here my guess about your code :
==> MAKE SURE THE COUNTRY ID IS NEVER EQUAL TO NULL
1 - in your Model, change this,
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
return $cities;
}
else{
return FALSE;
}
to this :
if($result = $query->result_array())
$cities = array_column($result, 'NOMVILLEDEPART', 'NUMVILLEDEPART');
return $cities;
2 - in your Controller, change this :
function get_ville_depart($country){
foreach($this->ville_model->get_ville_depart($country) as $ville){
log_message('debug',json_encode($ville));
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($this->ville_model->get_ville_depart($country));
}
to this :
function get_ville_depart($country){
$countries = $this->ville_model->get_ville_depart($country);
return $this->output->set_content_type('application/json')
->set_output(json_encode($countries));
}
3 - In your View, Change this :
var country_id = $('#paysdepart').val();
to this :
var country_id = $(this).val();
Note : you can access directly to this page "http://{mywebsite}/get_ville_depart/{country_id}"
with {country_id} equal to the country ID you have a problem with, and check if everything's OK before using the Ajax Query.
Related
Main
public function update_sample(){
$id3 = sanitize($this->input->post('id3'));
$sample3 = sanitize($this->input->post('sample3'));
if($this->session->userdata('position_id') != ""){
$username = $this->model->get_users($this->session->userdata('user_id'))->row()->username;
$query = $this->model->update_sample($data);
$data = array(
"success" => 1,
"message" => 'Note: You have successfully updated');
}else{
$this->logout();
}
generate_json($data);
}
model
public function update_sample($sample){
$sql = "UPDATE test SET sample=? WHERE id=? AND enabled= 1";
$data = array($sample);
return $this->db->query($sql, $data);
}
js
$("#table-grid").delegate(".btnUpdate", "click", function(){
var id = $(this).data('value');
$.ajax({
type: 'post',
url: base_url+'Main/view_details',
data: {'id3': id},
success: function(data){
var res1 = data.result1;
if(data.success==1){
document.getElementById("sample3").value = res1[0].samples;
$('#update').modal();
}
}
});
});
I want to update Data from database I've been stuck here for long.
I don't know how your class is created, but it looks like your function only returns true for query execution, you'll need to check for "affected_rows".
Try the code below, with a little luck it may work, otherwise you have to check the $result variable and modify the code corresponding to the result.
public function update_sample($sample){
$sql = "UPDATE test SET sample=? WHERE id=? AND enabled= 1";
$data = array($sample);
$result = $this->db->query($sql, $data);
return $result && $result->affected_rows > 0 ? true : false;
}
been scratching my head for hours on this one,
I have the below JQuery code that watches for a change in the select with the name of "CategoryID". It then posts the value of the "CategoryID" select to a PHP processor script which queries MySQL for the sub categorys and returns the updated options and populates the "SubCategoryID" select.
In the PHP processor script if I var_dump($_POST) at the top of the script I get an empty POST array. I've also tried dumping the $_REQUEST but still empty print_r() gives the same empty array
However the script runs fine and retrieves the correct data from the db and populates the web page.
I can even change the script and save the "CategoryID" to the DB and it populates it with the correct value...
As a relative nubee to JS for my own understanding how is this possible.
I have looked at some of the other questions posted but none of them give a solution
$(document).ready(function() { $('select[name="CategoryID"]').change(function() {
var selectedCategoryID = $('select[name="CategoryID"] option:selected').val();
var selectedSubCategoryID = $('select[name="SubCategoryID"] option:selected').val();
$.ajax({
method: "POST",
url: '/../_JQuery/PHPProcessorScript.php',
data: { CategoryID : selectedCategoryID, SubCategoryID : selectedSubCategoryID },
cache: false
}).done(function(data) {
$("select[name=SubCategoryID]").html(data);
})
})
})
PHP Processor script
var_dump($_POST); exit; // Returns an empty array with no ajax values
// If I remove exit the script returns the expected result so the ajax values are being parsed somehow...
$_POST['CategoryID'] = trim($_POST['CategoryID']);
$_POST['SubCategoryID'] = trim($_POST['SubCategoryID']);
if (empty($_POST['CategoryID'])) {
print '<option value="">select a category first</option>';
}
if (!empty($_POST['CategoryID'])) {
if (ctype_digit($_POST['CategoryID'])) {
if (strlen($_POST['CategoryID']) <= 11) {
$DBConnection = new database_connector();
$PS1SQL = 'SELECT
ID,
Description
FROM db_table
WHERE
CategoryID = :CategoryID';
$Statement = $DBConnection->Prepare($PS1SQL);
$Statement->bindParam(':CategoryID', $_POST['CategoryID'], PDO::PARAM_INT);
$Statement->Execute();
if ($PS1RS = $Statement->fetchAll(PDO::FETCH_ASSOC)) {
$PS1RS = array_merge(array(000 => array('ID' => 0, 'Description' => 'choose a sub category')), $PS1RS);
foreach ($PS1RS as $Key => $SubCategory) {
if ($_POST['CategoryID'] == $SubCategory['ID']) {
$SubCategoryList .= "<option value=\"$SubCategory[ID]\" selected=\"true\">$SubCategory[Description]</option>\n";
} else{
$SubCategoryList .= "<option value=\"$SubCategory[ID]\">$SubCategory[Description]</option>\n";
}
}
print $SubCategoryList;
} else {
print '<option value="" selected="true">Oops! no sub categorys available</option>';
}
}
}
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;
}
}
i have api that returns a list of cities and the relevant geo zone when i type the post code.
eg:
postcode -3000 returns 9 cities and geo zone - A012
postcode -3008 returns 12 cities and geo zone - C01
So i have written the below code. Once the post code is entered it will append the cities into a dropdown. which works great
php
if($response == NULL || $response < 1 )
{
echo "wrong Postcode";
} else{
foreach ($response as $q)
{
$cty = $q['city'];
$geozone = $q['geozone'];
echo '<option value="'.$cty.'">'.$cty.'</option>';
}
jquery
<script type="text/javascript">
$(document).ready(function()
{
$(".postcode").change(function()
{
var dataString = 'postcode='+ id;
$.ajax
({
type: "POST",
url: "load.php",
data: dataString,
cache: false,
success: function(val)
{
$(".city").html(val);
}
});
});
});
</script>
the problem is i need to append the $geozone which is returned in the php to a input box
since i have echoed the option values, i can easily append it
echo '<option value="'.$cty.'">'.$cty.'</option>';
but how do i return $geozone = $q['geozone']; to my main page so i can use it with a text field
I think that is better build the select from json data. Try to change the php for somthing like this
if($response == NULL || $response < 1 )
{
echo "wrong Postcode";
} else{
echo json_encode($response);
}
This will return a json array with the complete response with the cities and geozone, then you need to build the form with JS
$.ajax({
type: "POST",
url: "load.php",
data: dataString,
cache: false,
dataType: "json"
success: function(val)
{
options = "";
for(x in val){
options += '<option value="'+val[x].city+'">'+val[x].city+'</option>'
}
$(".city").html(options);
$(".form").append('<input type="text" value="'+val[x].geozone+'">');
}
});
This will build the form for you. You will have to adapt this code to json response and the .form for the parent selector of your form.
I would do like this
first make one array to return. At index 0 you concatenate options and at index 1 concatenate $geozone in a ipnut hidden (if that is useful).
$dataReturn = array();
$dataReturn[0] = '';
$dataReturn[1] = '';
if($response == NULL || $response < 1 )
{
echo "wrong Postcode";
} else{
foreach ($response as $q)
{
$cty = $q['city'];
$geozone = $q['geozone'];
$dataReturn[0] .= '<option value="'.$cty.'">'.$cty.'</option>';
$dataReturn[1] .= '<input type='hidden' value="'.$geozone.'"';
}
echo json_encode(array($dataReturn);
json_encode(array($dataReturn)
Now parse it at success
success: function(val)
{
parsed = $.parseJSON(val);
$(".city").html(val[0][0]);
$(".hidden").html(val[0][1]); //a div
}
I did not test, but I already did something like that. Hope my memory has helped.
You can use extra attribute in option tag like this.
echo '<option value="'.$cty.'" geozone="'.$geozone.'" >'.$cty.'</option>';
This will echo as
<option value="Mumbai" geozone="A012" >Mumbai</option>
and Use jquery's .attr() method to get the value from option
var myTag = $(':selected', element).attr("geozone");
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);
}