jQuery Ajax Json response - check if is null - php

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

Related

Undefined Variable in Ajax from PHP

I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}

Return data AJAX PHP

By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.
This is my AJAX call:
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
data: {rede: $("#dropdown-parceria").val()},
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And this is what I got from trying to filter some data to return it,
but nothing worked:
<?php
require_once('../../includes/conecta.php');
$rede = $_POST['rede'];
function buscaDados($conexao){
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
}
Any idea?
Thanks!
You should add echo at the end :
echo json_encode($dados);
So the $dados array will be sent back to the ajax request as JSON response.
Parse the response to json uisng $.parseJSON() :
.done(function(resposta){
resposta = $.parseJSON(resposta);
console.log(resposta);
})
Hope this helps.
in your ajax code u add a success.
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
dataType: 'json',
data: {rede: $("#dropdown-parceria").val()},
success: function (data) {
//You do not need to use $.parseJSON(data). You can immediately process data as array.
console.log(data)
//if you have a array you use the following loop
for (var j =0;j < data.length;j++) {
console.log(data[j]);
// u can use data[j] and write to any fields u want.
// e.g.
$('.somediv').html(data[j].myarraykey);
}
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.
$rede = $_POST['rede'];
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
echo json_encode($dados);
die();

Ajax code for the counterpart of success

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

How to return a php variable in ajax callback and use it?

I am send a ajax request to php file where i will update the database and and i will select a value according to my condition. But how to return that $variable in ajax callback and show it in input text box.
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
}
});
my PHP file is
<?php
$conn = mysql_connect('localhost', 'root', 'root') or die("error connecting1...");
mysql_select_db("cubitoindemo",$conn) or die("error connecting database...");
if($_GET['id']==2) //taking
{
$book_id = $_GET['bookid'];
$startdate = $_GET['startdate'];
$update_validity = "UPDATE booking SET valid = '2',start_date_timestamp = '$startdate' where book_id = '$book_id'";
$query = mysql_query($update_validity);
if($query==TRUE)
{
$get_select_query = "select start_date_timestamp from booking where book_id = '$book_id'";
$get_query = mysql_query($get_select_query);
$row = mysql_fetch_assoc(get_query);
$startdate_return = $row['start_date_timestamp'];
echo $startdate_return;
}
}
?>
You should use json format like:
in your php file
$arrFromDb = array(
'id' => 1,
'bookName' => 'Da Vinci Code'
)
echo json_encode( $arrFromDb ); exit();
in you script
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
var book = $.parseJSON(data) // now book is a javascript object
var bookName = book.bookName;
}
});
I hope this will help you
Create an element in your page like <span> and give it a unique ID like <span id="testspan"></span>. This is where the text gets displayed. Then in your JS;
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
$( "#testspan" ).html(result);
}
});
Just echo in your php file, the output (instead of being shown by the browser as a default PHP page) will be usable in the JS as the result of the ajax call (data)
Try to use val(),
HTML
<input type="text" id="inputId" />
Js
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
$( "#inputId" ).val(data);
}
});
PHP CODE
<?php
echo $bookid= isset($_REQUEST['bookid']) ? $_REQUEST['bookid'] : "No bookid";
// you can use $_GET for get method and $_POST for post method of ajax call
return
?>
In updatenewuser.php
//after all operations
echo $variable_to_pass;
Then in the ajax request :
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
alert(result);//result will be the value of variable returned.
$("#input_box").val(result); //jquery
document.getElementById("input_box").value = result; // Javascript way
}
});
HTML being :
<input type="text" id="input_box" value=""/>
Cheers

onchange F(x) to php to Highchart on same page

I am continuing a previous question that was asked onclick -> mysql query -> javascript; same page
This is my onchange function for a drop down of names. it is called when each drop down is changed. The idea is to send each runners name into the php page to run a mysql query then return 3 arrays to be entered into javascript.
function sendCharts() {
var awayTeam = document.getElementById('awayRunner').value;
var homeTeam = document.getElementById('homeRunner').value;
if(window.XMLHttpRequest) {
xmlhttp14 = new XMLHttpRequest();
}
else {
xmlhttp14 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp14.onreadystatechange = function() {
if(xmlhttp14.readyState == 4 && xmlhttp14.status == 200) {
var parts = xmlhttp14.responseText.split(','); //THIS IS WHAT IS RETURNED FROM THE MYSQL QUERY. WHEN I ALERT IT, IT OUTPUTS IN THE FORM 14,15,18,16,17,12,13
... code that generates the chart
series: [ {
name: document.getElementById('awayRunner').value,
data: [parts,','], //THIS IS WHERE AN ARRAY MUST BE ENTERED. THIS OUPUTS ONLY ONE NUMBER
type: 'column',
pointStart: 0
//pointInterval
},
{
name: document.getElementById('homeRunner').value,
data: parts, // TRIED THIS
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [], //THIS IS WHERE 3rd ARRAY MUST BE ENTERED
type:'spline',
pointStart: 0
//pointInterval
},
]
});
}
}
xmlhttp14.open("GET", "getCharts.php?awayRunner="+awayRunner+"&homeRunner="+homeRunner, true);
xmlhttp14.send();
}
my php code looks like this. As you'll see, there are 3 arrays that must be returned to be entered into different spots in the javascript to generate the code.
$away=$_GET['awayRunner'];
$home=$_GET['homeRunner'];
$db=mydb;
$homeRunner=array();
$awayRunner = array();
$totalOverall= array();
$getHome="select column from $db where tmName = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['column'];
}
$getAway="select column from $db where tmName ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['column'];
}
$week = 0;
while($week<20){
$week++;
$teamCount = "select count(column) from $db where week = $week";
$resultTeam = mysql_query($teamCount);
$rowTeam = mysql_fetch_array($resultTeam);
$t = $rowTeam['count(column)'];
$getLeague = "select sum(column) from $db where week = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$totalOverall[]=$row3['sum(column)']/$t;
}
}
echo join(',',$awayRunner);
currently, by doing it this way, the chart only outputs the second value in the array. for instance, if var parts is equal to 23,25,26,24,23...only 25 is shown.
A previous question resulted with the following answer -
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
I'm lost on #'s 5 - 7. Can someone provide examples of code that gets this done? Normally, I would just ask for direction, but I have been stuck on this problem for days. I'm about ready to scrap the idea of having charts on my site. Thanks in advance
EDIT
this is the first change that I have made to send and receive just one request
<script>
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "data=" + $("#awayRunner").val(),
dataType: "json",
url: "/my.php",
success: function(response){
alert(response);
}
});
});
});
The data displayed in the alertbox is in the form 12,15,16,15. Now, when I enter in
data: response,
only the second number from each is being displayed in the chart. Any ideas?
EDIT
OK, so i figured out that the info in response is a string. It must be converted to an INT using parseInt to be usable in the chart. currently, I have
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayTeam").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var asdf = [];
asdf[0] = parseInt(response[0]);
asdf[1] = parseInt(response[1]);
asdf[2] = parseInt(response[2]);
asdf[3] = parseInt(response[3]);
alert(asdf);
will have to write a function to make this cleaner.
I can't believe it, but I finally got it. here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Categories