简体   繁体   中英

Ajax function return always error

I need to pass some value to a PHP file and from this return some values to the original script. I wrote this code.

$(document).ready(function() {
    var value = $('#myId').val();
    $('.myClass').click(function() {
        var request = $.ajax({
            type:   'POST',
            url:    'getinfo.php',
            data:   {fileIs: value},
            success: function(data) {
                alert(data);
            },
            error: function() {
                alert("Error"); 
            }
        });

        });   
    });

getinfo.php is like:

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());

if(isset($_REQUEST['fileIs'])) {
    $file = mysql_real_escape_string(htmlentities($_POST['fileIs']));
    $value = mysql_query("SELECT * FROM files WHERE filename = '".$file."' ");
    while($row = mysql_fetch_array($value)) {
        echo $row['fileTitle']; 
    }       
}

When i execute the script php AJAX function always return the alert with wrote "Error" that disappear automatically. How can i fix this problem? My goal is to send "value" variable content to the PHP file and get response from it to have the content in database corresponding to "value" content.

The ajax function can't tell what type of data is being returned because you aren't setting the header of the http response in the php code. Adding the following before the while loop should help:

header("Content-type: text/plain; charset=utf-8");

Documentation: http://php.net/manual/en/function.header.php

Try json_encode in getinfo.php

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());

if(isset($_REQUEST['fileIs'])) {
$file = mysql_real_escape_string(htmlentities($_POST['fileIs']));
$value = mysql_query("SELECT * FROM files WHERE filename = '".$file."' ");
while($row = mysql_fetch_array($value)) {
         $result = $row['fileTitle']; 
                        }       
}
echo json_encode($result);  or  //use one
return $result;                 //optional

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM