2
var bbb;
var ma_category;
ma_category="Vocabulary";

$(document).ready(function() {
    $("#create_matching_activity").click(function(){
        $.ajax({
            type: "POST",
            url: "a_category_code.php?ma_category="+ma_category,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){
                bbb=data.Act_Category_Code;
            },
            complete: function(){
            }
        });
        alert(bbb);
    });
});

<?php

include('ActivityConf.php');

$ma_cat=$_GET['ma_category'];
$sql = $connect->prepare("SELECT Act_Category_Code FROM activity_category WHERE Act_Category='".$ma_category."'"); 
$sql->setFetchMode(PDO::FETCH_ASSOC);
$sql->execute();



$row = $sql->fetch();

$connect=null;
header('Content-type: application/json');
echo json_encode($row);


?>

This code reads from a database. im passing a variable from javascript to php using ajax. all is fine, but when i click to get my answer i get"undefined" as alert for first click, then the second click on i get the right variable in the alert.

what is the reason of this delay? Please if anyone can assist this issue. thank you.

Karimb
  • 45
  • 5

1 Answers1

2

Your alert is called synchronously, while the bbb is populated asynchronously inside of the callback - success.

In other words, right after the first click was fired, bbb was not populated with data yet (that is why it is undefined). The second time you click, the success function has a good chance to be executed and populate bbb with the data.

The fix to the problem is to move alert from outside of $.ajax to inside of $.ajax.success:

success: function(data){
    bbb=data.Act_Category_Code;
    alert(bbb);
},
GoOlga
  • 214
  • 1
  • 8
  • true, yet i placed the alert outside cause i need to use the 'bbb' outside the function. what could be the solution in this case? – Karimb Aug 21 '16 at 23:35
  • You need to set async:false; in ajax call, it will make ur request synchronous and will wait for the response of ajax call. – Afshan Shujat Aug 22 '16 at 04:51
  • Thank you guys, after Jason P marked the question i found a great answer in this question: http://stackoverflow.com/questions/1457690/jquery-ajax-success-anonymous-function-scope. Thank you Jason for the hint. – Karimb Aug 22 '16 at 15:24