AJAX Custom error handling Code issue - javascript

My Code Igniter PHP page returns json_encode query when page is load with success data. I made a json_encode when no records found. But i dont know how to pass my no record error to jQuery
PHP
if (($query->num_rows() > 0) && ($counter > 0)){
echo(json_encode($query->result()));
$counter = 0;
} else {
//return false;
$response["error"] = 1;
$response["error_msg"] = "NO records found";
echo json_encode($response);
}}
JQuery
$.ajax({
url: <? base_url() ?> +'main/data',
dataType: "JSON",
type: "POST",
success: function(retdata) { //working
$.each(retdata, function(i) {
$("#main_div").append('<div>' + retdata[i].name + '<br>' + retdata[i].marks+ '</div>');
});
}
});

controller:
public function controller_function()
{
//$query = your get query code
$response = array(
'result' => array(),
'error_msg' => '',
);
if ($query->num_rows() > 0)
{
$response['result'] = $query->result();
}
else
{
$response['error_msg'] = 'NO records found';
}
echo json_encode($response);
}
Javascript:
$.ajax({
url: <? base_url() ?> +'main/data',
dataType: "JSON",
type: "POST",
success: function (retdata)
{
if (retdata.error_msg)
{
alert(retdata.error_msg);
}
else
{
$.each(retdata.result, function (i)
{
$("#main_div").append('<div>' + retdata.result[i].name + '<br>' + retdata.result[i].marks + '</div>');
});
}
}
})

Related

dynamic select option and dynamic data from php

I tried develop add several selectbox dynamically and get data from selectbox my codes:
this codes add new selectbox and work
var y = 1;
var z = 1;
$('#add_kind').on('click', function () {
var html = '';
html += '<div class="prInput-row">';
html += '<select name="kind_id" class="halfselect kinds">';
html += '<option value="0">Kinds</option>';
html += '<?php foreach($kinds as $kind): ?>';
html += '<option value="<?php echo $kind->id;?>"><?php echo $kind->name;?></option>';
html += '<?php endforeach; ?>';
html += '</select>';
html += '<select name="kind_desc_id" class="halfselect kind_descriptions">';
html += '<option value="0">Kind Descriptions/option>';
html += '</select>';
html += '<input type="text" name="stock_piece" class="halfselect" placeholder="Stock Piece"/>';
html += '</div>';
$('#kind_area').append(html);
$('.kinds').each(function () {
$(this).attr('class', 'halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class', 'halfselect kind_descriptions_'+z);
z++;
});
});
$('.kinds').each(function () {
$(this).attr('class','halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class','halfselect kind_descriptions_'+z);
z++;
});
this codes get data from db and not work,
var i = 1;
$(".kinds_"+i).on('change', function() {
var kindID = $(this).val();
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
i++;
});
how can change those codes and how can get dynamically datas
this picture my example
#anon, I solved thank you so much but 2 times write codes but how can write one time ?
$("#add_kind").click(function(){
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
});
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
you can get all element that have class started with "kinds_" with selector $("[class^=kinds_]") then do a loop to get your class index. So maybe something like this will work:
$.each($("[class^='kinds_']"), function() {
var selector = "."+$(this).attr("class");
$(document).on('change', selector, function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
})

show only one value from ajax return array

How can I display only one thing from the array. Now it shows the whole array but I only want to show the reason from the array. because the rest is't really important. I have added index.php to show what I do there. I would like that it only showed the reason from data.
test.js
$(document).ready(function() {
var date = "";
var begin = "";
var tijdsduur = "";
var aantal = "";
$('#datum').change(function() {
date = $("#datum").val();
console.log(date);
});
$('#beginTijd').change(function() {
begin = ($(this).val());
console.log(begin);
});
$('#Tijdsduur').change(function() {
tijdsduur = ($(this).val());
console.log(tijdsduur);
});
$('#aantalSloepen').change(function() {
aantal = ($(this).val());
console.log(aantal);
$.ajax({
type: "POST",
url: "index.php",
data: {
date: date,
begin: begin,
eind: tijdsduur,
quantity: aantal
},
success: function(data) {
$('#testajax').html(data);
console.log(data);
}
});
});
});
index.php
<?php
$date = "";
$begin = "";
$tijdsduur = "";
$aantal = "";
if (isset($_POST['date']) && isset($_POST['quantity'])) {
if (isset($_POST['date'])) {
print_r($_POST);
// echo "Yes, mail is set";
$date = $_POST['date'];
$begin = $_POST['begin'];
$tijdsduur = $_POST['eind'];
$aantal = $_POST['quantity'];
$eind = $begin + $tijdsduur;
$startTijd = "$date " . $begin;
$eindTijd = "$date " . $eind . ":00";
// echo $date . "<br>";
// echo "$startTijd". "<br>";
// echo "$eindTijd". "<br>";
// echo $aantal. "<br>";
$canmakereservation = "https://www.planyo.com/rest/?method=can_make_reservation&api_key=YOURKEY&resource_id=110556&start_time=$startTijd&end_time=$eindTijd&quantity=$aantal";
$cleancanmakereservation = preg_replace("/ /", "%20", $canmakereservation);
$reservationavailable = file_get_contents("$cleancanmakereservation");
$reservationAvailable = json_decode($reservationavailable, true);
// echo "$cleancanmakereservation";
echo json_encode($reservationAvailable);
}
else {
echo "No, mail is not set";
}
exit;
}
?>
console.log
Set the dataType: 'json' in ajax request like
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "indextest.php",
dataType: 'json',
data: {
date: '',
begin: '',
eind: '',
quantity: ''
},
success: function(data) {
console.log(data.date);
}
});
</script>
and in php
<?php
$data = array('date' => '10-10-2010','date2' => '10-10-2010');
echo json_encode($data);
?>

only show some data of array on ajax return

Is there a way to only show [reason] from the array and not everything inside data? somebody said that I need to use JSON but I tried contentType: "application/json" with stringify() but then success: function(data) returns my whole HTML instead of the array.
My question is how can I show only [reason] in $('#testajax').html(data); instead of everything inside data?
console.log
script.js
$(document).ready(function(){
var date = "";
var begin = "";
var tijdsduur = "";
var aantal = "";
$('#datum').change(function() {
date = $("#datum").val();
console.log(date);
});
$('#beginTijd').change(function(){
begin =( $(this).val() );
console.log(begin);
});
$('#Tijdsduur').change(function(){
tijdsduur =( $(this).val() );
console.log(tijdsduur);
});
$('#aantalSloepen').change(function() {
aantal = ($(this).val());
console.log(aantal);
$.ajax({
type: "POST",
url: "index.php",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {
date: date,
begin: begin,
eind: tijdsduur,
quantity: aantal
},
success: function(data) {
$('#testajax').html(data);
console.log(data);
}
});
});
});
UPDATED index.php
<?php
$date = "";
$begin = "";
$tijdsduur = "";
$aantal = "";
if (isset($_POST['date']) && isset($_POST['quantity'])) {
if (isset($_POST['date'])) {
print_r($_POST);
echo "Yes, mail is set";
$date = $_POST['date'];
$begin = $_POST['begin'];
$tijdsduur = $_POST['eind'];
$aantal = $_POST['quantity'];
$eind = $begin + $tijdsduur;
$startTijd = "$date " . $begin;
$eindTijd = "$date " . $eind . ":00";
echo $date . "<br>";
echo "$startTijd". "<br>";
echo "$eindTijd". "<br>";
echo $aantal. "<br>";
$canmakereservation = "https://www.planyo.com/rest/?method=can_make_reservation&api_key=YOURKEY&resource_id=110556&start_time=$startTijd&end_time=$eindTijd&quantity=$aantal";
$cleancanmakereservation = preg_replace("/ /", "%20", $canmakereservation);
$reservationavailable = file_get_contents("$cleancanmakereservation");
$reservationAvailable = json_decode($reservationavailable, true);
echo "$cleancanmakereservation";
echo json_encode($reservationAvailable);
}
else {
echo "No, mail is not set";
}
exit;
}
?>
console.log(date[0].reason);
console.log(date);
Return data in json_encode from your index.php
Then in your ajax success function just get it by
success: function(data) {
console.log(data.reason); //if its comming then add it to your html.
$('#testajax').html(data.reason);
}

Access JavaScript Variable in PHP

I have problem to set the AJAX variable in use in my PHP code
When I change the value of area the following function will be called:
function find_map(){
var value1 = $("#area").val();
var value2 = $("#city").val();
$.ajax({
url :"find_my_map.php", // json datasource
type: "post", // method , by default get
dataType:"json",
data:
{
area_id:value1,
city_id:value2
},
success: function(data)
{
console.log(data);
$.each(data, function(index, element) {
alert("area_name:" + element.area_name);
alert("city_name:" + element.city_name);
var map_area_name= element.area_name;
var map_city_name= element.city_name;
$("#map_area_name").val(map_area_name);
$("#map_city_name").val(map_city_name);
});
},
error:function(data){
console.log(data);
}
});
}
find_my_map.php file
include_once("config.php");
if(isset($_POST['area_id']) && isset($_POST['city_id']))
{
$area_id = $_POST['area_id'];
$city_id = $_POST['city_id'];
$sql = "SELECT * FROM area a, city c WHERE a.city_id=c.city_id AND c.city_id='$city_id' AND a.area_id='$area_id'";
$qry = mysql_query($sql);
while($fetch = mysql_fetch_array($qry))
{
$area_name=$fetch['area_name'];
$city_name=$fetch['city_name'];
$data[]=array(
'area_name' => $area_name,
'city_name' => $city_name
);
}
$json_data = array($data);
echo json_encode($data);
}
this is my php code
<?php
echo $address ="here i want to use **map_area_name AND map_city_name**"; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$area_latitude = $output->results[0]->geometry->location->lat;
$area_longitude = $output->results[0]->geometry->location->lng;
echo "<br><input type='text' name='area_latitude' id='area_latitude'value='".$area_latitude."'> <br>";
echo "<input type='text' name='area_longitude' id='area_longitude' value='".$area_longitude."'>";
?>

jquery select2 - Format the results via AJAX php

i use select2, i want to format my results like
name, first.
$("#id").select2({
minimumInputLength : 0,
allowClear: true,
ajax : {
url : "Form/page.php",
dataType : 'json',
data : function (term, page) {
return {
q : term
};
},
results: function (data, page) {
return { results : data.ex};
},
formatResult : function formatResult(ex) {
return '<b>' + ex.name + '</b>';
}
}
});
my php file like
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['text']=$r['name'];
$rows['first']=", ". $r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
how can i do that, thanks
I think the php code has to be like this:
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['name']=$r['name'];
$rows['first']=$r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
So, you pass an array of json objects with an id, name and first.
Change the return of formatResult to:
return '<b>' + ex.name + '</b>, ' + ex.first;
PHP example reposted from the Select2 - source example:
https://github.com/ivaynberg/select2/wiki/PHP-Example
In JS:
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
and in PHP:
<?php
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
?>

Categories

Resources