0

I have written this code to call a php function from javascript, the php function simply prints the arguments it receives, but this code is giving no output and nothing is printed, I am using google chrome browser, kindly help.

index.html file

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>
            jQuery.ajax(
            {
                type: "POST",
                url: 'save.php',
                dataType: 'json',
                data: {functionname:'saveUser', arguments:["username", "password"]},

                success: function (obj, textstatus) {
                    if( !('error' in obj) ) {
                        alert(obj.result);
                    }
                    else {
                        console.log(obj.error);
                    }
                }
            });
        </script>
    </head>
</html>

save.php file

<?php

    header('Content-Type: application/json');   
    if( $_POST['functionname'] == 'saveUser' ) {
        echo json_encode(Array(
            result => $_POST['arguments'][0] . ' ' . $_POST['arguments'][1]
        ));
    }

?>

output enter image description here

4
  • Where is functionname declared which you are sending via POST method? Commented Dec 27, 2015 at 9:42
  • data: {functionname:'saveUser', arguments:["username", "password"]}, Commented Dec 27, 2015 at 9:46
  • Sorry, I didn't see it. Could try again by adding these code to show errors at the start of your php script? error_reporting(E_ALL); ini_set('display_errors', 1); Commented Dec 27, 2015 at 9:49
  • Also, is there any output when you show page source by hitting Ctrl+U ? Commented Dec 27, 2015 at 9:51

2 Answers 2

2

There is a typo. you are missing to quote the array key

try this

echo json_encode(Array(
        'result' => $_POST['arguments'][0] . ' ' . $_POST['arguments'][1]
        ^      ^
    ));
Sign up to request clarification or add additional context in comments.

Comments

1

You have a syntax error in your save.php file. Enclose the result index by string quotes. Fix it first

if( $_POST['functionname'] == 'saveUser' ) {
    echo json_encode(Array(
        'result' => $_POST['arguments'][0] . ' ' . $_POST['arguments'][1]
        /*^^^^*/
    ));
}

And in index.html just add below the codes in ajax success.

success: function (obj, textstatus) {
    if( !('error' in obj) ) {
         document.write(obj.result); //This line
         alert(obj.result);
    }
    else {
       console.log(obj.error);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.