Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

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);

Wednesday, July 10, 2013

PHP debugging with JavaScript Console, Error and Access Log

You can use JavaScript console to output global and other variables from your PHP file. That way you can use JS console to track what is is going on in PHP backed files that are called by $.ajax. Also you should be familiar with PHP's functions utf8_encode and utf8_decode

Raw outuput of JSON string and Base64 encoded JSON string

Tuesday, July 2, 2013

Parse JSON generated by PHP

This tutorial shows how to parse a JSON string generated by PHP. Place job.php and index.html in same folder.