0

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

TheLovelySausage
  • 3,838
  • 15
  • 56
  • 106

5 Answers5

0

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.

Genocide_Hoax
  • 843
  • 2
  • 18
  • 42
  • This is just a guess that the script's URL is wrong, but you have no idea whether this is the case or not. Also, this is a terrible way to do it. First, you're forcing the protocol to be `http`. What if it's `https`? Second, you don't need to echo the server name. URLs starting with a `/` will automatically be relative to the web root. Third, if the request URI is something like `/subdirectory/script.php` your code would try to load `http://example.com/subdirectory/script.phpscripts/functions.php` which is almost definitely wrong too. – Mike May 31 '16 at 16:15
  • 1> This can be easily converted for https n http. 2> Yes, ofcourse it is a guess cuz the OP is not able to provide decisive facts on the error, whether it is 500, 404 , 403 so yes this was just a humble attempt to help someone. 3> this is considering a particular test case nope of us has conclusive envoirment details as well. – Genocide_Hoax May 31 '16 at 16:22
0

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);
}
Community
  • 1
  • 1
Mike
  • 23,542
  • 14
  • 76
  • 87
0

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

0

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

TheLovelySausage
  • 3,838
  • 15
  • 56
  • 106
-1

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