2

While looking at tons of examples of how to get a PHP variable sent to a JavaScript file, I still haven't had success getting it.

My PHP file is:

$title = $json["title"];

echo json_encode($title);

And my JavaScript file app.js is:

$.ajax({
            url : 'index.php',
            type : 'GET',
            data : film,
            dataType : 'json',
            success : function (data) {
                alert(data.title);
                console.log(data.title);
            },
        })

I would like to know the right code to get the PHP $title variable to the ajax call in app.js.

Thanks

2 Answers 2

2

For this example there are two files. One has the JQuery ajax method. The other file is a PHP script that returns the requested information.

show_title.html

<!-- JQuery library already loaded -->
<script>

$.ajax({
    url : 'get_title.php', // requesting a PHP script
    dataType : 'json',
    success : function (data) { // data contains the PHP script output
       alert(data.title);
       console.log(data.title);
    },
})

</script>

get_title.php

<?php

$json["title"] = 'a title';
echo json_encode($json);

?>
Sign up to request clarification or add additional context in comments.

2 Comments

does it matter where the php code is placed in the php file? i currently have it in a cURL session and that cURL session closes right after i've echoed the json_encode(); i've tried it outside the session and it still doesn't ring the success console.log
To narrow down where the problem is, try sending these simple examples, without the CURL. Then you ought to be able to tell if the problem is in your JavaScript, or your CURL session. I tested this example before I posted it and it worked just fine. If you find the problem is in your CURL session, post another question about it.
2

If you'd want a .title property on the response, then you should create an array then encode that instead. You got the other way around. Something like this:

PHP

<?php

$title = 'Yahoo!';
$json['title'] = $title;
echo json_encode($json);

2 Comments

does it matter where the php code is placed in the php file? i currently have it in a cURL session and that cURL session closes right after i've echoed the json_encode(); i've tried it outside the session and it still doesn't ring the success console.log
yes its okay, as long as the container of the data is defined and is not empty. of course make sure its not empty and you do the encoding and echo at the end (most likely in the final lines of the PHP file)

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.