0

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?

Community
  • 1
  • 1
aarelovich
  • 5,140
  • 11
  • 55
  • 106

2 Answers2

1

You don't print the result of json_encode.

Change the code in addproject.php to:

echo json_encode($res);
Lorenzo Marcon
  • 8,029
  • 5
  • 38
  • 63
  • According to the example I've read $res should be the result and it is what I get in obj.result. I should be able to see it if the code enters the function on success. Am I understanding the example wrong? Because in the example function names is simply used for a switch statement, to to actually call a function.... – aarelovich Aug 27 '14 at 12:33
  • One more thing. In my defense the example in the link did not have the echo in the encode command, though...... – aarelovich Aug 27 '14 at 12:38
  • you're right, the example seems wrong as well. glad it worked! – Lorenzo Marcon Aug 27 '14 at 12:40
1
<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);
?>
Smruti Singh
  • 565
  • 1
  • 4
  • 14