Reputation: 10218
I have a .php
script like this:
$arr = array();
$arg1 = $_GET['arg1'];
$arg2 = $_GET['arg2'];
if ($arg1 !==1 && $arg2 !==0) {
$arr['msg'] = 'wrong values!';
header('Content-Type: application/json');
echo json_encode($arr);
exit();
}
$arr['msg'] = 'correct values!';
header('Content-Type: application/json');
echo json_encode($arr);
And here is my .js
file:
$.ajax({
url : file.php,
type : 'GET',
data : {"arg1": 1, "arg2": 1},
dataType : 'JSON',
success : function (data) {
alert(data.msg);
}
});
As I expect, after executing those code, it should shows a alert containing this message: wrong values!
. But it doesn't work, Why?
Note1: If I pass data : {"arg1": 1, "arg2": 0}
, It will show a alert containing correct values!
as well. Now I think the problem is that if
-statement in the .php
file.
Note2: The above code worked fine already. But now I updated my Xampp and after updating that problem has occurred.
Upvotes: 0
Views: 86
Reputation: 96159
More or less just putting together all the comments:
Because php's implicit type-juggling might consider values equal to 0 or 1 other than you'd expect, I'd suggest you keep the strict comparison (=== or !==).
You apparently want to check some numbers, so I threw intval() in and kept the strict comparison. But you could instead test if ('1'!==$_GET['arg1'] || '0'!==$_GET['arg2'])
.
<?php
if ( !isset($_GET['arg1'], $_GET['arg2']) ) {
$response = [
'status'=>'error',
'msg'=>'missing parameter(s)'
];
}
else {
// you could add another test like http://docs.php.net/ctype_digit here first
$arg1 = intval($_GET['arg1']);
$arg2 = intval($_GET['arg2']);
if ( 1!==$arg1 || 0!==$arg2 ) {
$response = [
'status' => '...',
'msg' => 'wrong values!'
];
}
else {
$response = [
'status' => '...',
'msg' => 'correct values!'
];
}
}
header('Content-Type: application/json');
echo json_encode($arr);
---side note---
I could make an argument for something like
$arguments = [
intval($_GET['arg1']), // maybe even 'arg1'=>intval($_GET['arg1'])
intval($_GET['arg2'])
];
if ( array(1,0)!==$arguments ) {
....but no, I just mention it ;-)
Upvotes: 1
Reputation: 78
You want || (or), not && (and), in your conditional. As currently written, it will return an error only if both values are incorrect.
Upvotes: 0
Reputation: 827
Your if statement states that arg1 must not be 1 and arg2 must not be 0. When you pass data for arg1=1 and arg2=1 that statement will not work. Your problem is in your if statement. If you want your if statement work for each condition you should use or statement like this ||
if ($arg1 !==1 || $arg2 !==0) {//i made this condition *or* check this
$arr['msg'] = 'wrong values!';
header('Content-Type: application/json');
echo json_encode($arr);
exit();
}
Upvotes: 1