简体   繁体   中英

Calling a php script using ajax not working

I'm trying to do what the title says following this example:

How can I call PHP functions by JavaScript?

However I can't get it to work.

Here is the javascript function:

  <script>
function errorInProyect(err){
    if (document.getElementById("projname").value == ""){
      document.getElementById("projname_status").innerHTML =  "El nombre del proyecto no puede estar vacio";
    }
    else{
    jQuery.ajax({
        type: "POST",
        url: 'addproject.php',
        dataType: 'json',
        data: {functionname: 'prueba'},
        success: function (obj) {
              document.getElementById("projname_status").innerHTML =  "El resultado fue " + obj.result;
            }
    });
    }
}
  </script>

And my addproject.php is:

<?php 
    $res = array();
    $res['result'] = "soy la prueba";
    json_encode($res);
?>

and I know that the function is being called because the message in case of the empty string is being printed. What am I doing wrong?

You don't print the result of json_encode .

Change the code in addproject.php to:

echo json_encode($res);
<script>
function errorInProyect(err){
    if (document.getElementById("projname").value == ""){
      document.getElementById("projname_status").innerHTML =  "El nombre del proyecto no puede estar vacio";
    }
    else{
         $.post("addproject.php",{'functionname': 'prueba'},
                 function(data)
                   {
                      document.getElementById("projname_status").innerHTML =  "El resultado fue " + data.result;

                   },'json');

         }
}
  </script>

and you php page is

<?php 
    $res = array();
    $res['result'] = "soy la prueba";
    echo json_encode($res);
?>

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