Ajax code for the counterpart of success - php

I have this code to do autocomplete function from database. what if the input is not in database, how can i show the error message?
this is my js code:
$('#txt_fname').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'under the hood/rehabCreateAjax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'country_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#txt_mname').val(names[1]);
$('#txt_sname').val(names[2]);
$('#txt_nickname').val(names[3]);
$('#txt_stuNum').val(names[4]);
}
});
this is my php code:
require_once '../connection/dbConn.php';
if($_POST['type'] == 'country_table'){
$row_num = $_POST['row_num'];
$name = $_POST['name_startsWith'];
$query = "SELECT stu_fname, stu_mname, stu_sname, stu_nickname, student_id FROM student
where (UPPER(stu_fname) LIKE '".strtoupper($name)."%') or (UPPER(stu_mname) LIKE '".strtoupper($name)."%') or
(UPPER(stu_sname) LIKE '".strtoupper($name)."%') or (UPPER(stu_nickname) LIKE '".strtoupper($name)."%')";
$result = mysqli_query($conn, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['stu_fname'].'|'.$row['stu_mname'].'|'.$row['stu_sname'].'|'.$row['stu_nick name'].'|'.$row['student_id'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
by the way..i have tried to put else in my php code.. not working.

If I understood correctly you want to respond to an empty results set, and not to some sort of server error. If this is the case you should include it in your success callback. simply check in your client code if the data array has items and respond accordingly:
success: function( data ) {
if (data.length) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
} else {
console.log("no results");
}
}
The error callback suggested by #Koogle is not meant for this purpose, and you definitely should not return a 404 from the server, which is only used when the url itself is not found (or for that matter a 500, which implies an internal server error).
The error callback represents a low-level failure to get a response from the server, and is automatically ran by JQuery if the request failed. It should not be forced to run by returning an error code for a successful request (200). The error you are referring to is high-level, because it stems from the inherent logic of your code, and not from an objective failure to execute the code itself for whatever reason.
Thus, the label error in your case is dictated by the way you perceive the logic of your code. e.g if you are filtering results in a table and the filter doesn't return any results, this can hardly qualify as an error. However, if you expect that the request would always return at least one result, then error may be justified, although I believe that exception is the more accurate term.

You could respond in your php script with an HTTP error message and handle the error in JS as follows:
$.ajax({
url : 'under the hood/rehabCreateAjax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'country_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
error: function (response) {
// Handle error here
console.log(response);
}
}
The PHP should be something like:
$query = "SELECT stu_fname, stu_mname, stu_sname, stu_nickname, student_id FROM student
where (UPPER(stu_fname) LIKE '".strtoupper($name)."%') or (UPPER(stu_mname) LIKE '".strtoupper($name)."%') or
(UPPER(stu_sname) LIKE '".strtoupper($name)."%') or (UPPER(stu_nickname) LIKE '".strtoupper($name)."%')";
$result = mysqli_query($conn, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['stu_fname'].'|'.$row['stu_mname'].'|'.$row['stu_sname'].'|'.$row['stu_nick name'].'|'.$row['student_id'].'|'.$row_num;
array_push($data, $name);
}
// Respond with error
if($data.length() == 0) {
http_response_code(500);
echo "No such entry";
return;
}
echo json_encode($data);

Related

Autocomplete does not work in CodeIgniter

When doing an ajax-request for an autocomplete I get an undefined error:
View:
<input type="text" name="" id="search">
<ul>
<div id="result"></div>
</ul>
Javascript:
$("#search").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo base_url(); ?>index.php/admin/ajaxPro",
dataType: 'json',
type: 'POST',
data: req,
success: function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
select: function(event, ui) {
$("#result").append(
"<li>"+ ui.item.value + "</li>"
);
},
});
Controller:
public function ajaxPro()
{
$term = $this->input->get('term');
$this->db->like('business_name', $term);
$data = $this->db->get("user_table")->result();
header('Content-Type: application/json');
echo json_encode($data);
}
Database:
this is the table
There is no error in the console, Data is showing the network preview but it is not showing on the view page I do not know what the problem is Can you help
The Problem:
Return value: undefined
Change your Controller code to something like this:
public function ajaxPro()
{
$term = $this->input->get('term');
$this->db->like('business_name', $term);
$data = $this->db->get("user_table")->result();
$ajaxData = array();
foreach($data as $row) {
$ajaxData[] = array( // Set "label"+"value" for autocomplete for each result
'label' => $row['name'], // <- change this to your column name
'value' => $row['id'] // <- this should be the ID-Value
);
}
header('Content-Type: application/json');
echo json_encode(
'status' => 'success',
'data' => $ajaxData
);
}
And your ajax success callback:
success: function(r){
if(typeof r.status != "undefined" && r.status == "success"){
response(r.data); // lets autocomplete build response list
} else {
console.log(r); // error occured
}
},
(I changed your response variable from data to r to clearify this is not just the actual data, but a response in a variable that can contain much more than just the data from your sql-find result. It usually holds data exactly in the format you give in json_encode() )
Explanation:
In this line:
if(data.response =="true"){
You are asking for a value/key response that does not exist.
Tips on Debugging and Troubleshooting:
To see what your ajax-response look like, you can open the Dev-Tools in your Browser (ususally F12 and go to the Tab that shows your network requests. There you can find your ajax-request and see the headers you sent and the final response.
Furthermore if you add debugger; in this line, you can debug your javascript and see all variables available in the current scope:
success: function(r){
debugger; // this is a breakpoint equivalent and will halt your code execution when dev tools are open!

how can I access json data from another url inside a html page

here is my php code which would return json datatype
$sql="SELECT * FROM POST";
$result = mysqli_query($conn, $sql);
$sJSON = rJSONData($sql,$result);
echo $sJSON;
function rJSONData($sql,$result){
$sJSON=array();
while ($row = mysqli_fetch_assoc($result))
{
$sRow["id"]=$row["ID"];
$sRow["fn"]=$row["posts"];
$sRow["ln"]=$row["UsrNM"];
$strJSON[] = $sRow;
}
echo json_encode($strJSON);
}
this code would return
[{"id":"1","fn":"hi there","ln":"karan7303"},
{"id":"2","fn":"Shshhsev","ln":"karan7303"},
{"id":"3","fn":"karan is awesome","ln":"karan7303"},
{"id":"4","fn":"1","ln":"karan7303"},
{"id":"5","fn":"asdasdas","ln":"karan7303"}]
But how can I access this data in html, that is, I want particular data at particular position for example i want to show 'fn' in my div and 'ln' in another div with another id
Before trying anything else I tried this
$.ajaxSetup({
url: 'exm1.php',
type: 'get',
dataType: 'json',
success: function(data){
console.log(data);
}
});
but it shows that data is undefined I don't know what I am doing wrong
What you've got should kind-of work if you swapped $.ajaxSetup (which is a global configuration method) with $.ajax. There are some significant improvements you could make though.
For example, your PHP does some odd things around the value returned by rJSONData. Here's some fixes
function rJSONData($result) {
$sJSON = array();
while ($row = mysqli_fetch_assoc($result)) {
$sJSON[] = array(
'id' => $row['ID'],
'fn' => $row['posts'],
'ln' => $row['UsrNM']
);
}
return json_encode($sJSON);
}
and when you call it
header('Content-type: application/json');
echo rJSONData($result);
exit;
Also make sure you have not output any other data via echo / print or HTML, eg <html>, etc
In your JavaScript, you can simplify your code greatly by using
$.getJSON('exm1.php', function(data) {
console.info(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR, textStatus, errorThrown);
});
Use $.ajax instead of $.ajaxSetup function.
Here is a detailed answer from another SO post how to keep running php part of index.php automatically?
<script>
$.ajax({
// name of file to call
url: 'fetch_latlon.php',
// method used to call server-side code, this could be GET or POST
type: 'GET'
// Optional - parameters to pass to server-side code
data: {
key1: 'value1',
key2: 'value2',
key3: 'value3'
},
// return type of response from server-side code
dataType: "json"
// executes when AJAX call succeeds
success: function(data) {
// fetch lat/lon
var lat = data.lat;
var lon = data.lon;
// show lat/lon in HTML
$('#lat').text(lat);
$('#lon').text(lon);
},
// executes when AJAX call fails
error: function() {
// TODO: do error handling here
console.log('An error has occurred while fetching lat/lon.');
}
});
</script>

Angular encoding data

I've got this code
Javascript
$http({
method: 'GET',
url: '../../php/getMesas.php',
}).then(function successCallback(response) {
$scope.mesas = response.data;
}, function errorCallback(response) {
$scope.mesas = 'No Response';
});
That is trying to get some table numbers, but when this really works it shows me the parameter name and the value, i need only the value, what can i do to get only the value so not the parameter name?
I'm using PHP as database connector.
PHP Code
<?php
include('base.php');
$data = array();
$result = mysql_query('SELECT table_number FROM waiters_assigned ORDER BY id',$connect);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
} else {
echo "0 results";
};
echo json_encode($data);
mysql_close($connect);
?>
The result is this one: {"table_number":"3"} what i need is just: 3
Firstly, please dont use mysql_query you should have a look at PDO or at the very least mysqli, for security and because it is deprecated.
As for returning just the number, update your while to return the field you desire:
while($row = mysql_fetch_assoc($result)){ $data[] = (int)$row['table_number']; }
When looking at your PHP i believe you're actually getting [{"table_number":"3"}], as you're json_encodeing an array.
The reason updating your PHP is better than updating your Javascript is that you appear to be returning an array of objects currently, when you actually want to return an array of numbers. Doing things the JS way you'll need to cycle through the response, parseInt on the strings, and strip the object down to a number. Far easier and more efficient to just send the correct data.
In your php code use mysqli or pdo extension because mysql extension is deprecated.
$http({
method: 'GET',
url: '../../php/getMesas.php',
}).then(function successCallback(response) {
$scope.mesas = response.data.table_number;//outputs 3
}, function errorCallback(response) {
$scope.mesas = 'No Response';
});
It's very simple:
$http({
method: 'GET',
url: '../../php/getMesas.php',
}).then(function successCallback(response) {
$scope.mesas = response.data ? "" + response.data.table_number : "";
}, function errorCallback(response) {
$scope.mesas = 'No Response';
});

jQuery Ajax Json response - check if is null

I am getting data from MySQL using jQuery Ajax and JSON. However I need to know when the response is empty. I passe a date parameter to my php that will return some data or not... depending on date.
My Javascript code (simple version):
function pac_irra(date){
.ajax({
url: 'get_db_data/pac_irra.php?date='+date,
dataType: 'JSON',
type: 'POST',
data: {get_values: true},
beforeSend: function(){
$("#morris-line-chart").append(load_img);
},
success: function(response) {
date = response[0].Timestamp;
$('#a1').append(date);
},
});
}
If for example I used yesterday (2015-09-26) data I get the following json data (only a part of it):
[{"Timestamp":"2015-09-26 16:50:00","pac":"35.20","irra":"38.97"},{"Timestamp":"2015-09-26 17:00:00","pac":"32.19","irra":"35.51"}]
Now, for example, if I chose a date without data it returns:
[]
In my javascript code below I would like to add a if statement to my success function in case of json array is empty... something like:
function pac_irra(date){
.ajax({
url: 'get_db_data/pac_irra.php?date='+date,
dataType: 'JSON',
type: 'POST',
data: {get_values: true},
beforeSend: function(){
$("#morris-line-chart").append(load_img);
},
success: function(response) {
date = response[0].Timestamp;
$('#a1').append(date);
if ( ***array is empty***) {
('#a1').append('No data');
};
},
});
}
In my success function I have a morris chart created with the json data... I don't put it in the code...
So how do I check if it's empty? I already made a lot of attempts:
if (response.length == 0)
or another attempt
if (response[0].Timestamp == "") or if (!response)
And nothing works... I still can't check if the json array is empty...
My php code:
<?php
error_reporting(0);
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/database/db_connect.php";
include_once($path);
if(isset($_GET['date'])) {
$date = $_GET['date'];
$days = $_GET['days'];
$var = array();
$query = "SELECT CONVERT_TZ(CONCAT(Date,' ',pac.Time), 'UTC', 'Europe/Lisbon' ) as Timestamp, ROUND((pac.Value/6440)*100,2) pac, ROUND((irra.Value/1000)*100,2) irra
FROM AggData pac
LEFT JOIN (SELECT Time, Value
FROM AggData WHERE Date=DATE_ADD('$date',INTERVAL '$days' DAY) and idEquipment=5 and idMeasure=6 ) irra
ON pac.Time=irra.Time
Where pac.Date=DATE_ADD('$date',INTERVAL '$days' DAY) and pac.idEquipment=1 and pac.idMeasure=3
AND (irra.Value>0 or pac.Value>0)
Order BY pac.Time asc
" or die("Error in the consult.." . mysqli_error($link));
$result = $link->query($query);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo json_encode($var);
}
?>
Try below if will check various condition
if((response && jQuery.isArray(response))?(response.length==0?false:(jQuery.isPlainObject(response[0])?!jQuery.isEmptyObject(response[0]):response[0])):response){
//console.log("adfdsaf");
}
if it will check if
response is null or undefined
or response == []
or response == [{}] or response[""]
I think this is the problem
success: function(response) {
if((response && jQuery.isArray(response))?(response.length==0?false:(jQuery.isPlainObject(response[0])?!jQuery.isEmptyObject(response[0]):response[0])):response){
('#a1').append('No data');
}else{
date = response[0].Timestamp;
$('#a1').append(date);
}
};
},
hopefully it will work

jquery ajax not parsing json data from php

I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.

Categories