Tuesday, May 23, 2017

jQuery AJAX call with JSON

Make AJAX call with jQuery and then receive and parse JSON string.


<html>
<head>
    <title>Making AJAX call with jQuery 3+</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        makeAJAX();

        function makeAJAX() {
            var request = $.ajax({
                url: '/ajax.php',
                method: "GET",
                data: {
                    id: 21,
                    minprice: 10,
                    maxprice: 1000
                },
                beforeSend: function(xhr) {
                    // set security token in AJAX request header
                    // xhr.setRequestHeader('X-Sec-Header','<?php echo $_SESSION["sectok"]; ?>');

                    // show loader
                    //$("#imgload").show();
                }
            });

            request.done(function(msg) {
                console.log(msg.films[0]);
                alert("name " + msg.films[0].name);
            });

            request.fail(function(jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            });

            request.always(function() {
                // hide loader
                //$("#imgload").hide();
            });
        }
    </script>
</head>
<body>
    <h1>Making AJAX call with jQuery 3+</h1>
    <div id="response"></div>
</body>
</html>


and here's the ajax.php:

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json');

$data = array(
 array("id"=>1,"name"=>"Brendan","year"=>1992),
 array("id"=>2,"name"=>"Thane","year"=>1997),
 array("id"=>3,"name"=>"Hoyt","year"=>1994),
 array("id"=>4,"name"=>"Xanthus","year"=>1991),
 array("id"=>5,"name"=>"Francis","year"=>1991),
 array("id"=>6,"name"=>"Plato","year"=>1998),
 array("id"=>7,"name"=>"Sylvester","year"=>1998)
);

 $rarray = array(); 
 $rarray['films'] = $data;
 echo json_encode($rarray);