Why ajax response doesn't work? - php

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.

More or less just putting together all the comments:
instead of $arg1...&&$arg2... use the logical-or operator
_GET contains strings (and arrays) and !== checks the data type first, hence $_GET['foo']!==1 will never be true
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 ;-)

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

You want || (or), not && (and), in your conditional. As currently written, it will return an error only if both values are incorrect.

Related

Why cant I check if something is not empty

I'm trying to validate if a image is uploaded or not.
But I can't figure this out since 2 hours...:
Input: ""
My Code:
$_SESSION["errorMessage"] = empty($image);
Output: 1 (true)
Then I want to check if it isnt empty:
$_SESSION["errorMessage"] = !empty($image); // Or empty($image) == false
But then The Output is nothing?!?!
Even If I try the first one out it, when it should be true, gives out: ""
Can anyone help me with this problem?
When you echo a false value, it won't echo anything. You have to tell php what to show, e.g. echo $_SESSION["errorMessage"] ? 'true' : 'false'; In your case you may want to cast it to an int: $_SESSION["errorMessage"] = (int)empty($image); You could also use var_dump to verify, i.e. var_dump( $_SESSION["errorMessage"] );
You can use the UPLOAD_ERR_NO_FILE value:
function isset_file($file) {
return (isset($file) && $file['error'] != UPLOAD_ERR_NO_FILE);
}
if(isset_file($_FILES['input_name'])) {
// It's not empty
}
Since sending $_FILES['input_name'] may throw a Notice
function isset_file($name) {
return (isset($_FILES[$name]) && $_FILES[$name]['error'] != UPLOAD_ERR_NO_FILE);
}
if(isset_file('input_name')) {
// It's not empty
}
Another example to try:
if ($_FILES['theFile']['tmp_name']!='') {
// do this, upload file
} // if no file selected to upload, file isn't uploaded.

File has copied successfully but condition is behaving wrong in Laravel

I have created a function to copy files one directory to another in Larave. For that, I've written below code, but the code is behaving wrong.
The function is returning value "1" that is "true" but the condition is behaving something wrong.
public static function copyOneToAnother($source) {
//Do Something
$destination = __DIR__."/uploads/testing_another_dir";
File::makeDirectory($destination);
return File::copyDirectory($source, $destination);
}
public function actionCopy(){
$source = __DIR__.'/my_project/project1';
$copy_status = $this->copyOneToAnother($source); //This is returning true
if($copy_status === 1){
echo "Files Copied Successfully";
}
else{
echo "There was an error";
}
}
This code always showing below results
There was an error
But files copied successfully and value of $copy_status is also 1 even it's going in else loop. I also tried using trim() and using true/false in if but didn't work for me.
You are checking data type matches then only you are displaying success message but data type there return true not 1 so
if($copy_status === 1){
echo "Files Copied Successfully";
}
if you check like below then it will show success
if($copy_status == 1){
echo "Files Copied Successfully";
}
Instead of comparing with one you can directly check like below so it will treat true
if($copy_status){
echo "Files Copied Successfully";
}
else{
echo "There was an error";
}
$a == $b
Equal TRUE if $a is equal to $b after type juggling.
$a === $b
Identical TRUE if $a is equal to $b, and they are of the same type.
Ref: http://php.net/manual/en/language.operators.comparison.php
If you are saying that $copy_status is returning true, then it can not be 1 at the same time.
=== checks for strict equality - 1 == true, but 1 !== true.
Also, you could just use
if ($copy_status) {
// do something here
}
This is essentially the same as writing if ($copy_status) == 1.
More about comparison here

php: receive json from POST and save to file

I want to receive a POST request from a JS client with a json body (i.e. this is not form data), and save the .gigs (javascript) array to a file, after checking the .password field. This is all my code (based on Receive JSON POST with PHP)
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params)){
/* json_decode(..., true) returns an 'array', not an 'object'
* Working combination: json_decode($json_params) WITH $inp->password
*/
$inp = json_decode($json_params);
} else {
echo "could not decode POST body";
return;
}
$password = $inp->password;
// echo $password;
if ($password == "****") {
$gigs = $inp['gigs'];
// WAS $res = file_put_contents('gigs.json', json_encode($gigs), TEXT_FILE);
$res = file_put_contents('gigs.json', json_encode($gigs));
if ($res > 0) {
echo "Success";
return;
} else {
if (!$res) {
http_response_code(500);
echo "file_put_contents error:".$res;
return;
} else {
http_response_code(500);
echo "Error: saved zero data!";
return;
}
}
}
else {
// http_response_code(403); // (2)
echo "Password invalid";
return;
}
What I find is that
if I comment out the if statement and uncomment echo $password; then the right password is there
if I uncomment line 2, which I want to do, then I get back a 500 and the error logs refer an Illegal string offset 'password' in line (1) above. Without that I get back a "Success" (all for the same password).
I don't understand what is happening, nor how to get 200, 403 and 500 error messages safely.
Note
$json_params = file_get_contents("php://input");
If your scripts are running upon regular HTTP requests, passing data like it comes from HTML form, them you should consider using $_POST for your content, not php://input. If you expect JSON in request body, then I'd be fine, yet I'd also check content type for application/json.
Next:
$inp = "I never got set";
if (strlen($json_params) > 0 && isValidJSON($json_params)){
$inp = json_decode($json_params, true);
}
$password = $inp->password;
$password = $inp['password'];
This is pretty broken. First, see json_decode() arguments (2nd) -> you are decoding to array (true), not object (false), so only $password = $inp['password']; will work in your case. Also the whole code will fail when your input data is invalid as in that case $np is rubbish string, not the array you try to read later on. Use null as default value and check for that prior further use.
Next:
$res = file_put_contents('gigs.json', json_encode($gigs), FILE_TEXT);
there's no FILE_TEXT option for file_put_contents(). Nor you'd need one.
Once you correct these you'd be fine. Also print_r() and var_dump() may be the functions you wish to get familiar with for your further debugging.
In general http://php.net/ -> lookup for functions you are about to use.

Saving variable value in a text file using PHP

by clicking on a button I am setting a variable in php using Ajax.
submitInfo(var1);
function submitInfo(var1)
{
$.ajax({
type: "POST",
url: "js/info.php",
data: {Info:var1},
success: function (result)
{
alert(result);
}
});
}
in my php code, How can I save "var1" in a text file? I have used this to save variable in a text file but it is not saving anything there:
<?php
if (isset($_POST['var1']))
{
echo $_POST['var1'];
}
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
?>
The first issue is that in your JQuery you actually assigning the var1 variable to 'Info'
so the $_POST array will contain this rather than var1.
You then only want to manage your attempts to write to the file in order to get nicer, more user friendly error messages which will give you something nicer to send back and help you if debug any other problems.
<?php
$var1 = "";
$filename = "js/test.txt";
// Get the correct $_POST object
if (isset($_POST['Info']) {
$var1 = $_POST['Info'];
}
// If the variable is not empty try to write your file
if (!empty($var1)) {
if(!$file = fopen($filename,"w")) {
$msg = "Cannot open file");
} else if (fwrite($file,$var1) === false) {
$msg = "Cannot write to file");
} else {
$msg => 'all was good'
}
fclose($file);
$result = array(
'error' => 'false',
'msg' => $msg
);
} else {
$result = array(
'error' => 'true',
'msg' => 'Info was empty'
);
}
// Send your message back
echo "{\"result\":".json_encode{$result)."}";
PS: Not tested this so fingers crossed there are no typos.
Try this:
<?php
if (isset($_REQUEST['Info'])){
$var1 = $_REQUEST['Info'];
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
}
?>

Jquery Validation Remote Check Unique Not Working

I wanted to post this online because I have been searching for days on this JQuery Remote validation issue. I cannot get it to work. I think my PHP code is correct as I have test the URL with a query in the URL and it returns false and true depending on with the recordset count is one or more
This is my Jquery Validate Code:
// validate form and submit
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#myform").validate({
rules: {
ord_ref: {
required: true,
minlength: 12,
remote: "check_ord_ref.php"
},
messages: {
ord_ref: {
remote: "Order Number Does Not Exist"
}
}
}
});
});
This is my PHP code for the remote page "check_ord_ref.php"
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = 'false';
} else {
$valid = 'true';
}
echo $valid;
Please someone can you help solve the puzzle for myself and anyone else having issues
Using JQuery 1.5.2min
Validates OK without remote function
Ok, so I'm no PHP expert, but I do know that jQuery Validate expects the following result from a remote validation method:
The response is evaluated as JSON and must be true for valid elements,
and can be any false, undefined or null for invalid elements
Sending down "true" or "false" (note the quotation marks) is going to result in the value being parsed as the error message instead of being evaluated as a boolean primitive.
Back to the PHP part, I think you should probably use json_encode with a boolean primitive. I'm not quite sure the way to do this in PHP, but I believe it would be something like this:
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = false; // <-- Note the use of a boolean primitive.
} else {
$valid = true;
}
echo json_encode($valid);
This problem seems to be plaguing remote validation scripters and the jQuery documentation on the matter is clearly lacking.
I notice you are using jQuery 1.5.2: from what I understand (and found from experience) you must use the jQuery callback that is sent to the remote script with $_REQUEST with versions after 1.4, AND jQuery is expecting "true" or "false" as a STRING. Here is an example, confirmed working on multiple forms (I'm using jQuery 1.7.1):
if($totalRows_rscheck_ord_ref < 0){
header('Content-type: application/json');
$valid = 'false'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
} else {
header('Content-type: application/json');
$valid = 'true'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
}
I found this answer here (in the answers section), randomly, and have since stopped pulling out my hair. Hope this helps someone.
To add to Andrew Whitaker's response above, I must stress that you are sure that the response is strictly JSON and that there are no other content types being returned. I was having the same issue with my script, and everything appeared to be set properly - including using json_encode(). After some troubleshooting with Firebug's NET tab, I was able to determine that PHP notices were being sent back to the browser converting the data from JSON to text/html. After I turned the errors off, all was well.
//check_validate.php
<?php
// some logic here
echo json_encode(true);
?>

Categories