Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send php response to ajax

Okay I have a php script which ends as so :

if ($success)
{
    $result = array('success' => true);
}
else
{
    $result = array('success' => false, 'message' => 'Something happened');
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
  echo json_encode($result);

And some jquery that I was planning on having alert me when my script is working.

    jQuery(document).ready(function() {

    $.ajax({
        url: './contactengine.php',
        type: 'GET',
        dataType: 'JSON',
        success: function(response) {
                        alert("GOOD");
                },
                error: function() {
                        alert("BAD");
                }
    });

});

edited source

like image 659
lostAstronaut Avatar asked Apr 11 '12 22:04

lostAstronaut


People also ask

How PHP can be used in an AJAX application?

Create an XMLHttpRequest object. Create the function to be executed when the server response is ready. Send the request off to a PHP file (gethint. php) on the server.

How send AJAX response to HTML?

ajax({ url: 'test. html', dataType: 'html', success: function(response) { $('#testDiv'). html(response); } }); The code above will take all of the code you retrieved with your AJAX query and will output it into the testDiv.


1 Answers

        <?php 
        if ($success){
             $result = array("status" => "1");

             echo json_encode($result);
            }
            else{
              print "<meta http-equiv=\"refresh\" content=\"0;URL=/404.html\">";
            }    
        ?>
        <script>
        jQuery(document).ready(function() {

          $.ajax({
                           type: 'GET',
                           url:  'Thatscriptsomething.php',
                           cache: 'false',
                           dataType: 'json',
                           success: function(response) {
                               if(response.status == "1") {
                                    alert("we having a working script");
                               } else {
                                    alert("Oops, script is a no go");
                               }
                            }
                        });
        });
        </script>
like image 65
Ryan Avatar answered Sep 22 '22 22:09

Ryan