I have two problems. One is totally in PHP the other in Javascript. But both are equal in what I'm trying to get.
index.php
$.ajax({
type: "post",
url: "insert_info.php?type=info",
data: { array : all },
success: function(data) {
alert(data);
// Returns: {'status':1}
// I want to get "1"
// data[0] -> doesn't work
}
});
insert_info.php
// Connects to another file
include_once('verify_info.php');
$verify = new verify_info();
$arr = array("status:" => 1);
$extension = $verify->verify_file($_REQUEST['array'][9]);
if($extension[0] == 0){
$arr = array("status:" => 0);
}
echo json_encode($arr);
verify_info.php
public function verify_file($file){
$extensions = array('jpg', 'png', 'jpeg', 'bmp');
$info = pathinfo($file);
$arr = array();
if(!in_array($info['extension'], $extensions)){
$arr = array("status:" => 0);
}else{
$arr = array("status:" => 1);
}
return $arr;
}
In insert_info.php, I would like to get by $extension[0] the status retrieved from the function verify_file();
After that I output as json_encode the value to Javascript and I would like, again, to parse the info.
What am I doing wrong? Thanks.
Edit 1: alert(data.status);
doesn't work either.
Edit 2: alert(data.status);
would never work since I echo {'status:', 1}
(problem with that two points in the middle) Correct way for solving the issue of javascript:
var obj = jQuery.parseJSON(data);
alert(data.status);
I'm still trying to get fixed the php.
Edit 3: All solved. Thank you guys.
public function verify_file($file){
$extensions = array('jpg', 'png', 'jpeg', 'bmp');
$info = pathinfo($file);
if(!in_array($info['extension'], $extensions)){
return false;
}
return true;
}
As I said in my comment, your setting your key in PHP to "status:"
is the trailing colon necessary on the end of your key? I don't think it's necessary, PHP arrays already offer mechanisms for fetching them and your JSON will contain the string without processing it so your key once you hit your JS code will still be "status:"
where most likely you intended for "status"
.
Regardless of whether you will make this change or not that doesn't break anything. In your Javascript code, as @charlietfl pointed out, you should be setting the dataType
of the return to "json"
so you're JS Ajax call would look like:
$.ajax({
type: "post",
url: "insert_info.php?type=info",
data: { array : all },
dataType: "json",
success: function(data) {
// Assuming no change on the backend
alert(data["status:"]);
}
});
If, however, you altered the string to remove the colon then accessing the status element of data would be data.status
as @A.Wolff pointed out in his comment. This doesn't work because of the trailing colon in the key - but accessing the data with a string key will still work.