JS中的奇迹。 一个功能有不同的结果

It's a Miracle! Help me to understand it.

I have the some html code in my php file:

<form action="" method="post" name="r_form" >
<table>
<tr>
<td> Name: </td>
<td> <input type="text" name="r_name" id = "rname" /> </td>
</tr>
<tr>
   <td align="center" colspan="2"> <img src="FE.png" width="40" height="40" id="firstentryID" onClick="nextFunc()"></td>
</tr>
</table>
</form>

And the follow code in my auth.php:

    <script type="text/javascript">

    Preload();
    nextFunc();

    function Preload() { 
    var valueToPush = {};
var name2 = [];
    var userID1 = '<?php echo $id_user;?>';
                   $.ajax({
                       url: 'TR.php',
                        type: 'POST',
                        data: {userID1: userID1},
                       success: function(data){
                        var names = data
                $('#result_div_id').html(data);
                             var json2 = $.parseJSON(data);
                     EntriesCount =json2.length; 
               $.each(json2, function() {
               $.each(this, function(k, v){


    switch(k) {
     case 'Name':
       valueToPush.Name = v;    
         break;

    // and more parametrs - it doesnt matter.
    }
    });

    name2.push({ID_Clients: valueToPush.id, Name: valueToPush.Name, Phone: valueToPush.Phone, Email: valueToPush.Email, Status: valueToPush.Status, Birthday: valueToPush.Birthday, ClientFrom: valueToPush.ClientFrom, User: valueToPush.User});

    });
    }
    });
    }
    ...

And in my nextFunc() I have:

function nextFunc(){

document.getElementById("rname").value = name2[currententry]['Name'];
}

In my JSON so I have:

[12]
0:  {
ID_Clients: "87"
Name: "Вася"
Phone: "1234578"
Status: "4"
Birthday: "2016-10-21"
ClientFrom: "4"
User: "2"
}-
1:  {
ID_Clients: "88"
Name: "Петя"
Phone: "2345669"
Status: "3"
Birthday: "2016-10-11"
ClientFrom: "2"
User: "2"
} ...  and so on...

The Miracle is:

When I Call the NextFunc() from my block like in this code i recieve the

Uncaught TypeError: Cannot read property 'Name' of undefinedat NextFunc()

But when I press the FE.png on my web page the code is working!!!

WHY????

there are no miracles in CS

I'm pretty sure that your problem in your variables scope, which is in defining the variable in preLoad function scope, then trying to call this variable from another scope.

to solve this, you need to move your name2 variable to the global scope,

like following:

var name2 = [];
Preload();
nextFunc();

and within your Preload(); function , comment this line var names2 = [];

This is your problem.

Preload();
nextFunc();

When you call Preload, it starts downloading your JSON. However, since downloads can take a long time, the download doesn't pause the rest of the code - it's asynchronous, so it continues to download in the background while the rest of the code executes. By the time you call nextFunc, the JSON still hasn't downloaded yet.

By the time you click your image, the JSON has finished downloading so the function works.

Instead of calling Preload and nextFunc one after another, you need to use a callback. The callback is the function that will be called once the JSON has finished downloading. In fact, you already have a callback called success .

success: function(data){
                        var names = data
                $('#result_div_id').html(data);
                             var json2 = $.parseJSON(data);
                     EntriesCount =json2.length; 
               $.each(json2, function() {
               $.each(this, function(k, v){


    switch(k) {
     case 'Name':
       valueToPush.Name = v;    
         break;

    // and more parametrs - it doesnt matter.
    }
    });

    name2.push({ID_Clients: valueToPush.id, Name: valueToPush.Name, Phone: valueToPush.Phone, Email: valueToPush.Email, Status: valueToPush.Status, Birthday: valueToPush.Birthday, ClientFrom: valueToPush.ClientFrom, User: valueToPush.User});

    });

To solve the problem, call nextFunc directly after the line that says name2.push in your callback so you can ensure that name2 exists by the time nextFunc is called.

Also, be aware that since you're using the push function, if you download JSON multiple times the array will be double its initial length. You may want to clear it beforehand.

Almost always, if the same function behaves differently for seemingly no reason, it's because of something that hasn't loaded yet - that should be your first suspicion in this scenario.