简体   繁体   中英

Retrieve Data From PHP using JQuery

I'm not sure what I've done wrong with this but I have a php function that I need to retrieve some data from.

I am using JQuery 1.11 to execute an ajax function

$(document).ready(function() {
   $('#butt_example').on('click', function() {
      $.ajax({
         url      : 'scripts/functions.php',
         type     : 'GET',
         dataType : 'json',
         data     : {
            'action': 'test'
         },
         success: function(result) {
            var la_result = JSON.parse(result);
            console.log(la_result);
         },
         error: function(log) {
            console.log(log.message);
         }
      });
   });
});

Then I replaced my php function with a simple one just for testing

<?php
if(isset($_GET["action"])) {
   $arr = array();
   $arr[0] = "test";
   $arr[1] = "passed";

   header('Content-Type: application/json; charset=utf-8');
   echo json_encode($arr);
}
?>

However when I click the button to execute the code I see that the console log result is undefined.

Why is this?

UPDATE

After Mike's comment bellow I realised that it's actually executing the console log in the error condition.

So it's failing somewhere and I'm not sure why

Are u sure the AJAX call is able to reach the PHP function?

Try this In a .php file do this first

This will produce the base_url() similar to codeigniter or any other relative framework.

base_url in codeigniter

function url(){
  return sprintf(
    "%s://%s%s",
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME'],
    $_SERVER['REQUEST_URI']
  );
}

<script>
  var url="<?php echo url(); ?>"; 
</script>

Then in your JS file supply the URL

 $(document).ready(function() {
       $('#butt_example').on('click', function() {
          $.ajax({
             url      : url+'scripts/functions.php',
             type     : 'GET',
             dataType : 'json',
             data     : {
                'action': 'test'
             },
             success: function(result) {
                var la_result = JSON.parse(result);
                console.log(la_result);
             },
             error: function(log) {
                console.log(log.message);
             }
          });
       });
    });

As pointed out url extraction modified for both http and https.

As you can see from the manual :

error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

The first argument is a jqXHR object.

Also from here :

For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:

  • readyState
  • status
  • statusText responseXML and/or responseText when the underlying request responded with xml and/or text, respectively setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
  • getAllResponseHeaders()
  • getResponseHeader()
  • statusCode()
  • abort()

So as you can see, there is no jqXHR.message property. So when you do:

     error: function(log) {
        console.log(log.message);
     }

of course, you're going to get an undefined notice because that property doesn't exist.

From this answer , to get the error message you need to do:

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}

Works for me with jquery 1.12.3

success: function(result) {
        alert(result);
},

//shows "test,passed"

Next line of JSON returns in the console log: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data

It seems the error was related to the json_encode function.

CentOS 5 php installation does not include the json.so module so it had to be manually installed which then fixed the error.

Thanks to everyone for their help though it's greatly appreciated

Try this:

$(document).ready(function() {
   $('#butt_example').on('click', function() {
      $.ajax({
         url      : 'scripts/functions.php',
         type     : 'GET',
         dataType : 'json',
         data     : 'action=test',
         success: function(result) {
            var la_result = JSON.parse(result);
            console.log(la_result);
         },
         error: function(log) {
            console.log(log.message);
         }
      });
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM