0

i have a code in html:

HTML:

<div  id="all" aria-expanded="true">all</div>

and i want when this div was clicked, the ajax call:

AJAX:

$("#all").click(function () {

    $( "#adv-article-list" ).empty();
    $("#adv-article-list-pagination").empty();
    $.ajax({
        url: 'ajax_index.php', 
        type: "POST",
        dataType:'json',
        data: {name: 1},
        success: function(data)
        {
            arr_db=data;
        }
    });
    function(arr_db);
})

My code worked correctly, but not with one click. I must clicked twice on div. why?

PHP:

$userAnswer = $_POST['name'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname="db";

$conn = new mysqli($servername, $username, $password, $dbname);
$conn->query("SET NAMES 'utf8'");

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$result = $conn->query("SELECT * FROM wp_moeee ORDER BY  ID DESC");
$ar=array();

while ( $row = mysqli_fetch_assoc($result)){
    $ar[] = $row; // add the row in to the results (data) array
}

echo json_encode($ar);
HiDeoo
  • 10,353
  • 8
  • 47
  • 47
H Jahan
  • 11
  • 4

1 Answers1

0

Because jQuery $.ajax request is asynchronous by default.

async (default: true) Type: Boolean By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

Although you may change it:

Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

First time you trigger click event this happens:

  1. the ajax request has been sent, than
  2. function(arr_db); has been executed with arr_db not set yet
  3. ajax response triggered jQuery's success callback and arr_db=data;

Second time you trigger click event:

  1. second ajax request has been sent, than
  2. function(arr_db); has been executed, using arr_db from first response
  3. second ajax response triggered jQuery's success callback and arr_db=data;
skobaljic
  • 9,379
  • 1
  • 25
  • 51
  • tanx a lot. i changed async to false. – H Jahan Aug 15 '16 at 21:51
  • In fact, you should keep asynchronous ajax call, show some spinner while waiting for response and put `function(arr_db)` inside `success` ajax callback function. That is the way programmers usually go. – skobaljic Aug 16 '16 at 00:11