简体   繁体   中英

Return echo from php-function to ajax

I have a question re. receiving data from php-function to ajax.

Ajax (in html-file):

function showUser(name) {
$.ajax({      
  type: 'POST',                        
  url: '/api.php',                            
  data: { 
    name : "\""+name+"\"",
    func_id : "1" 
  },                        
  dataType: 'json',                       
  success: function(data)           
  {
    if (data == null) { 
      console.log("Something went wrong..");
    } else {
      console.log(data);

Php (separate php-file):

<?php 
error_reporting(E_ALL);

//MySQL Database connect start  
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";

$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
  echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end

$func_id = $_POST['func_id'];

function showUser() {
  global $con;
  $name = $_POST['name'];
  $sql = "SELECT * FROM users WHERE first_name=$name";
  $result = mysqli_query($con, $sql);            
  $array = mysqli_fetch_row($result);             
  mysqli_close($con);
  echo json_encode($array);   
}

if ($func_id == "1") {
  showUser();
}
?>

The question: Everything works if I don't have the showUser-function in the php, ie I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax. Is there a fix for this? Thanks!

The reason may be that the variables inside a function're visible only for function itself. Try this way:

$name = $_POST['name'];
function showUser($name) {
    global $con;
    $sql = "SELECT * FROM users WHERE first_name=$name";
    $result = mysqli_query($con, $sql);            
    $array = mysqli_fetch_row($result);             
    mysqli_close($con);
    echo json_encode($array);   
}

Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.

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