-1

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?

1
  • you dint print anything? and where did you write this function prueba? Commented Aug 27, 2014 at 12:28

2 Answers 2

1

You don't print the result of json_encode.

Change the code in addproject.php to:

echo json_encode($res);
Sign up to request clarification or add additional context in comments.

3 Comments

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....
One more thing. In my defense the example in the link did not have the echo in the encode command, though......
you're right, the example seems wrong as well. glad it worked!
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);
?>

1 Comment

see the $.post() section. Its not copied and pasted. Made needed changes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.