</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/15658246/ajax-showing-retrieved-values-as-undefined" dir="ltr">AJAX showing retrieved values as undefined</a>
<span class="question-originals-answer-count">
(5 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2013-03-27 17:15:34Z" class="relativetime">7 years ago</span>.</div>
</div>
</aside>
I want to retrieve a set of array from PHP to ajax. The code I have does not return anything back, could someone help me how to retrieve the value from PHP to ajax. If i dont create the array in the mysql_fetch it will retrieve the last value from the database and pass it to the ajax function. I want to get the whole values. How can i do this?
AJAX CODE:
<script>
//Global Variables
var channel;
function overall(){
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
window['channel']="overall";
$.ajax({
type:"GET",
url:"dash2.php",
data:{channel:channel},
dataType:'json',
success:function(data){
console.log(data.a);
console.log(data.b);
console.log(data.c);
}
});
}
</script>
PHP CODE:
<?php
error_reporting(0);
$channel=$_GET['channel'];
$host="192.168.0.29";
$username="root";
$password="root";
$dbname="realcl";
mysql_connect($host,$username,$password)
OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$query = 'select * from '.$channel;
$masterresult = mysql_query($query);
$success[];
$timeout[];
$fail[];
while($row1 = mysql_fetch_array($masterresult))
{
$success[]=$row1[1];
$timeout[]=$row1[2];
$fail[]=$row1[3];
}
echo json_encode(array("a"=>$success,"b"=>$timeout,"c"=>$fail));
?>
</div>
This will lead to a fatal error (and because of that, non-valid json...):
$success[];
$timeout[];
$fail[];
You probably want:
$success = array();
// etc.
And you have a huge sql injection problem, you should check your table name against a white-list of allowed table names. You should also switch to PDO (or mysqli) as the mysql_*
functions are deprecated.