1

I'm trying to get some data from a PHP file using AJAX but I get only an error:

Uncaught TypeError: Cannot read property 'protocole' of null

protocoleGenerator.php

<?php    
    $array = array(
        'protocole' => '1029384756',
    );
    echo json_encode($array);
?>

script.js

function getDemoProtocol() {
    $.ajax({
        url: 'protocoleGenerator.php',       
        data: "",
        dataType: 'json', //data format      
        success: function (data) {
            var protocole = data['protocole'];
            console.log("Prot: " + protocole);
        }
    });
}

What is wrong here?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Bejkrools
  • 1,129
  • 2
  • 17
  • 38
  • 5
    Have you checked what the exact response is using the network tab of the console? – Rory McCrossan Feb 04 '16 at 14:28
  • Is script.js and protocoleGenerator.php in the same directory? – ksealey Feb 04 '16 at 14:35
  • Everything looks fine to me, assuming the path is correct. Try adding `header('Access-Control-Allow-Origin: *');` in your `.php` file. below the ` – yardie Feb 04 '16 at 14:38
  • @ksealey - no, but path is correct, in Network tab `protocoleGenerator.php` is `STATUS 200` and `METHOD GET` – Bejkrools Feb 04 '16 at 14:39
  • 4
    Can you see what the responseText is? `console.log(data)` would help too. – Rory McCrossan Feb 04 '16 at 14:42
  • 3
    @andre3wap it's not a CORS issue if success is already being triggered. That header will be of no benefit – charlietfl Feb 04 '16 at 14:42
  • http://api.jquery.com/jquery.parsejson/ – pablito.aven Feb 04 '16 at 15:41
  • There is nothing wrong with your code itself. The only problem for me is that script.js might be inside of some js/ folder and protocolGenerator.php is on the root than it is not findfing the path. Try to look on Dev console Network response and see if it is realy finding its way and returning what it should. There is another thing you could try. Add a header on PHP with content-type json – Guilherme Ferreira Feb 04 '16 at 15:50
  • Can I ask a question? What is protocol? for what do you use it here? – BananaBuisness Feb 04 '16 at 20:06
  • The error message is not ambiguous: "Cannot read property 'protocole' of null". Means that: 1) the Ajax request was successfull (since `success function is being executed; 2) it not depends on a false invocation (`data['protocole']` is absolutely equivalent to `data.protocole`); 3) anyway, `data` value is found to be `null` (exactly what the error message said). So what happens is _only_ that `protocolGenerator.php` returned `null` for some reason, as considered by the Wizard's answer. BTW I wonder why this answer had been downvoted, while at the opposite it's pertinent! – cFreed Feb 05 '16 at 03:26
  • 1
    The issue is originating from somewhere else, your included code runs flawlessly here. – John Weisz Feb 05 '16 at 10:36

3 Answers3

0

I can't comment for now :( and write my suggestions as an answer. It seems like you have mistype in protocoleGenerator.php. May be end line looks like echo json_encode($aray);, in this case json_encode() returns pure null (if you have disable php notices). The success function receives null and can't get a property from this object. It's only my subjective suggestion. It may be wrong.

P.S: You can get value / call function as Object.my_fun(), or Object['my_func']() - for this particular case it doesn't matter how did you access to the variable. For example:

   var o = {};
   o.test = 'my test value';
   o.fff = function() {return 'fff called.';};
   console.log('dot-style:' + o.test);
   console.log('arr-style:' + o['test']);
   console.log('dot-style:' + o.fff());
   console.log('arr-style:' + o['fff']());

Ok, I've got a minus. If assumed, that topic starter show us hard copy-paste of his code, here is no issues. My suggestion based on the error message - the "success function" gets HTTP/200 answer from the server with text "null". With empty or non-valid json response jquery-ajax calls an "error handler". I'm sure that it can't be caused by json_encode() behaviour - my example above prove it.

Another suggestion is specific server config, rewrites, redirects or something else. But I've exclude this suggestion.

Oh...

<?php
$array = array(1,2);
$аrray = array(3,4);
var_dump($array);
var_dump($аrray);

result looks like that:

array(2) {
  [0] =>
  int(1)
  [1] =>
  int(2)
}
array(2) {
  [0] =>
  int(3)
  [1] =>
  int(4)
}

Did you see the difference? I don't, but the second $array begins from cyrillic character.

Wizard
  • 862
  • 6
  • 9
  • Your answer is the only pertinent. Look at my comment under the OP. I don't understand why somebody downvoted it. I upvote to compensate. – cFreed Feb 05 '16 at 03:29
  • Thanks for support, @cFreed. Now I have some interest to know what kind of bug it is/was here. Another suggestion: topic starter has two or more copies of `protocoleGenerator.php` at different locations or has mistype in the filename. – Wizard Feb 05 '16 at 06:48
  • @FlashThunder, I haven't any issues neither v1.12 nor 1.8.3 or 3.0.0beta jQuery.. HTTP/404 makes jQuery to call an 'error handler'. In this case existence of header 'Content-Type' doesn't matter, although I will set it up in my project. – Wizard Feb 05 '16 at 14:51
  • Ouch, I mean that 'Content-Type' header can have any valid value, like `text/html` or even `text/plain` instead of `application/json` – Wizard Feb 05 '16 at 15:12
0

I run your code in my localhost, it's working fine please check below code in your system, if you still get any error then post your whole code so I can check in my system.

index.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Json</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
    function getDemoProtocol() {
        $.ajax({
            url: 'protocoleGenerator.php',       
            data: "",
            dataType: 'json', //data format      
            success: function (data) {
                var protocole = data['protocole'];
                console.log(protocole);
                alert(protocole);
                console.log("Prot: " + protocole);
            }
        });
    }
    getDemoProtocol();  // Javascript method

    // Jquery Method
    $(function (){
        $.ajax({
            url: 'protocoleGenerator.php',       
            data: "",
            dataType: 'json', //data format      
            success: function (data) {
                console.log(data);
                var protocole = data.protocole;
                console.log("Prot: " + protocole);
            }
        });
    });
</script>
</head>

<body>
</body>
</html>

protocoleGenerator.php

<?php 
header('Content-Type: application/json');  
$array = array(
    'protocole' => '1029384756',
);
echo json_encode($array);
?>
Raju Dudhrejiya
  • 1,637
  • 2
  • 15
  • 16
0

This is because you are getting Error 404: not found. Check console (tick the log XHR requests checkbox).

The solution would be, changing this:

url: 'protocoleGenerator.php',  

to this:

url: './protocoleGenerator.php',

Working example:

http://neolink.dyndns.org:81/stackoverflow/1.php

PS. This is weird that jQuery runs success function even when response was 404.

PS 2. If it won't work (it should!), give the full path instead (like http://blabla.com/1/3/45345/protocoleGenerator.php, as that may be server dependable)

Flash Thunder
  • 11,672
  • 8
  • 47
  • 91