Get variable from PHP file using JQuery/AJAX

If I understand right, you need to use JSON. Here is a sample.

In your PHP write:

<?php
// filename: myAjaxFile.php
// some PHP
    $advert = array(
        'ajax' => 'Hello world!',
        'advert' => $row['adverts'],
     );
    echo json_encode($advert);
?>

Then, if you are using jQuery, just write:

    $.ajax({
        url : 'myAjaxFile.php',
        type : 'POST',
        data : data,
        dataType : 'json',
        success : function (result) {
           alert(result['ajax']); // "Hello world!" alerted
           console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
        },
        error : function () {
           alert("error");
        }
    })

And that’s all. This is JSON – it’s used to send variables, arrays, objects etc between server and user. More info here: http://www.json.org/. 🙂

Leave a Comment