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?

11
  • 5
    Have you checked what the exact response is using the network tab of the console? Commented Feb 4, 2016 at 14:28
  • Is script.js and protocoleGenerator.php in the same directory? Commented Feb 4, 2016 at 14:35
  • 4
    Can you see what the responseText is? console.log(data) would help too. Commented Feb 4, 2016 at 14:42
  • 3
    @andre3wap it's not a CORS issue if success is already being triggered. That header will be of no benefit Commented Feb 4, 2016 at 14:42
  • 1
    The issue is originating from somewhere else, your included code runs flawlessly here. Commented Feb 5, 2016 at 10:36

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
@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.
Ouch, I mean that 'Content-Type' header can have any valid value, like text/html or even text/plain instead of application/json
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);
?>

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.