Show ajax process 1 by 1 when something is done - javascript

I have a code and it works, and it shows all notifications at the same time.
I have question..
How to get notifications when one of the functions is done? (Notifications appear one by one)
There are several functions in the indexing.php file.
$preproses = $_POST["preproses"];
if($preproses == "preproses"){
//mulai proses
set_time_limit(0);
buatindex();
hitungbobot();
panjangvektor();
}
function buatindex() {
code
}
function hitungbobot() {
code
}
function panjangvektor() {
code
}
In index.php there is a code to call that function
<script type="text/javascript">
function preproses(){
var preprosesx = "preproses";
$.ajax({
type : "POST",
url : "indexing.php",
data: {preproses:preprosesx},
error: function(){
$("#notif").prepend("fail");
},
success: function(html){
$("#notif").prepend("Process done <br/>"+html);
},
});
return false;
}
</script>
click to precess
If all processes are completed, a notification will appear
<span id="notif"></span>

$preproses = $_POST["preproses"];
if($preproses == "preproses"){
//mulai proses
set_time_limit(0);
setTimeout(function(){ buatindex() }, 3000);
setTimeout(function(){ hitungbobot() }, 3000);
setTimeout(function(){ panjangvektor() }, 3000);
console.log("Completed all");
}
function buatindex() {
code
}
function hitungbobot() {
code
}
function panjangvektor() {
code
}
Also you can console.log in ajax success response.
Something Like this : JsFiddle Example

count your post parameter ($_POST["preproses"]) and keep into an javascript variable like var count = ""; . you can also take an hidden text variable which will be increase by 1 after every notification send. after all notification values send this hidden variable will be equal to the count variable. then you can be sure that all the notifications have been sent. Hope this will work for you..:)

Haven't you tried async: false yet? This will stop further processing until one ajax request is complete.

Related

Cancelling AJAX request if previous AJAX response hasn't been received [duplicate]

Is it possible that using jQuery, I cancel/abort an Ajax request that I have not yet received the response from?
Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort().
See the documentation:
abort Method (MSDN). Cancels the current HTTP request.
abort() (MDN). If the request has been sent already, this method will abort the request.
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
UPDATE:
As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See The jqXHR Object (jQuery API documentation).
UPDATE 2:
As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an xhr any more. See the 3.0 blog here.
UPDATE 3: xhr.abort() still works on jQuery 3.x. Don't assume the update 2 is correct. More info on jQuery Github repository.
You can't recall the request but you can set a timeout value after which the response will be ignored. See this page for jquery AJAX options. I believe that your error callback will be called if the timeout period is exceeded. There is already a default timeout on every AJAX request.
You can also use the abort() method on the request object but, while it will cause the client to stop listening for the event, it may probably will not stop the server from processing it.
Save the calls you make in an array, then call xhr.abort() on each.
HUGE CAVEAT: You can abort a request, but that's only the client side. The server side could still be processing the request. If you are using something like PHP or ASP with session data, the session data is locked until the ajax has finished. So, to allow the user to continue browsing the website, you have to call session_write_close(). This saves the session and unlocks it so that other pages waiting to continue will proceed. Without this, several pages can be waiting for the lock to be removed.
It's an asynchronous request, meaning once it's sent it's out there.
In case your server is starting a very expensive operation due to the AJAX request, the best you can do is open your server to listen for cancel requests, and send a separate AJAX request notifying the server to stop whatever it's doing.
Otherwise, simply ignore the AJAX response.
AJAX requests may not complete in the order they were started. Instead of aborting, you can choose to ignore all AJAX responses except for the most recent one:
Create a counter
Increment the counter when you initiate AJAX request
Use the current value of counter to "stamp" the request
In the success callback compare the stamp with the counter to check if it was the most recent request
Rough outline of code:
var xhrCount = 0;
function sendXHR() {
// sequence number for the current invocation of function
var seqNumber = ++xhrCount;
$.post("/echo/json/", { delay: Math.floor(Math.random() * 5) }, function() {
// this works because of the way closures work
if (seqNumber === xhrCount) {
console.log("Process the response");
} else {
console.log("Ignore the response");
}
});
}
sendXHR();
sendXHR();
sendXHR();
// AJAX requests complete in any order but only the last
// one will trigger "Process the response" message
Demo on jsFiddle
We just had to work around this problem and tested three different approaches.
does cancel the request as suggested by #meouw
execute all request but only processes the result of the last submit
prevents new requests as long as another one is still pending
var Ajax1 = {
call: function() {
if (typeof this.xhr !== 'undefined')
this.xhr.abort();
this.xhr = $.ajax({
url: 'your/long/running/request/path',
type: 'GET',
success: function(data) {
//process response
}
});
}
};
var Ajax2 = {
counter: 0,
call: function() {
var self = this,
seq = ++this.counter;
$.ajax({
url: 'your/long/running/request/path',
type: 'GET',
success: function(data) {
if (seq === self.counter) {
//process response
}
}
});
}
};
var Ajax3 = {
active: false,
call: function() {
if (this.active === false) {
this.active = true;
var self = this;
$.ajax({
url: 'your/long/running/request/path',
type: 'GET',
success: function(data) {
//process response
},
complete: function() {
self.active = false;
}
});
}
}
};
$(function() {
$('#button').click(function(e) {
Ajax3.call();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="button" type="button" value="click" />
In our case we decided to use approach #3 as it produces less load for the server. But I am not 100% sure if jQuery guarantees the call of the .complete()-method, this could produce a deadlock situation. In our tests we could not reproduce such a situation.
It is always best practice to do something like this.
var $request;
if ($request != null){
$request.abort();
$request = null;
}
$request = $.ajax({
type : "POST", //TODO: Must be changed to POST
url : "yourfile.php",
data : "data"
}).done(function(msg) {
alert(msg);
});
But it is much better if you check an if statement to check whether the ajax request is null or not.
Just call xhr.abort() whether it's jquery ajax object or native XMLHTTPRequest object.
example:
//jQuery ajax
$(document).ready(function(){
var xhr = $.get('/server');
setTimeout(function(){xhr.abort();}, 2000);
});
//native XMLHTTPRequest
var xhr = new XMLHttpRequest();
xhr.open('GET','/server',true);
xhr.send();
setTimeout(function(){xhr.abort();}, 2000);
You can abort any continuous ajax call by using this
<input id="searchbox" name="searchbox" type="text" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
var request = null;
$('#searchbox').keyup(function () {
var id = $(this).val();
request = $.ajax({
type: "POST", //TODO: Must be changed to POST
url: "index.php",
data: {'id':id},
success: function () {
},
beforeSend: function () {
if (request !== null) {
request.abort();
}
}
});
});
</script>
As many people on the thread have noted, just because the request is aborted on the client-side, the server will still process the request. This creates unnecessary load on the server because it's doing work that we've quit listening to on the front-end.
The problem I was trying to solve (that others may run in to as well) is that when the user entered information in an input field, I wanted to fire off a request for a Google Instant type of feel.
To avoid firing unnecessary requests and to maintain the snappiness of the front-end, I did the following:
var xhrQueue = [];
var xhrCount = 0;
$('#search_q').keyup(function(){
xhrQueue.push(xhrCount);
setTimeout(function(){
xhrCount = ++xhrCount;
if (xhrCount === xhrQueue.length) {
// Fire Your XHR //
}
}, 150);
});
This will essentially send one request every 150ms (a variable that you can customize for your own needs). If you're having trouble understanding what exactly is happening here, log xhrCount and xhrQueue to the console just before the if block.
I was doing a live search solution and needed to cancel pending requests that may have taken longer than the latest/most current request.
In my case I used something like this:
//On document ready
var ajax_inprocess = false;
$(document).ajaxStart(function() {
ajax_inprocess = true;
});
$(document).ajaxStop(function() {
ajax_inprocess = false;
});
//Snippet from live search function
if (ajax_inprocess == true)
{
request.abort();
}
//Call for new request
Just use ajax.abort() for example you could abort any pending ajax request before sending another one like this
//check for existing ajax request
if(ajax){
ajax.abort();
}
//then you make another ajax request
$.ajax(
//your code here
);
there is no reliable way to do it, and I would not even try it, once the request is on the go; the only way to react reasonably is to ignore the response.
in most cases, it may happen in situations like: a user clicks too often on a button triggering many consecutive XHR, here you have many options, either block the button till XHR is returned, or dont even trigger new XHR while another is running hinting the user to lean back - or discard any pending XHR response but the recent.
The following code shows initiating as well as aborting an Ajax request:
function libAjax(){
var req;
function start(){
req = $.ajax({
url: '1.php',
success: function(data){
console.log(data)
}
});
}
function stop(){
req.abort();
}
return {start:start,stop:stop}
}
var obj = libAjax();
$(".go").click(function(){
obj.start();
})
$(".stop").click(function(){
obj.stop();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="go" value="GO!" >
<input type="button" class="stop" value="STOP!" >
If xhr.abort(); causes page reload,
Then you can set onreadystatechange before abort to prevent:
// ↓ prevent page reload by abort()
xhr.onreadystatechange = null;
// ↓ may cause page reload
xhr.abort();
I had the problem of polling and once the page was closed the poll continued so in my cause a user would miss an update as a mysql value was being set for the next 50 seconds after page closing, even though I killed the ajax request, I figured away around, using $_SESSION to set a var won't update in the poll its self until its ended and a new one has started, so what I did was set a value in my database as 0 = offpage , while I'm polling I query that row and return false; when it's 0 as querying in polling will get you current values obviously...
I hope this helped
I have shared a demo that demonstrates how to cancel an AJAX request-- if data is not returned from the server within a predefined wait time.
HTML :
<div id="info"></div>
JS CODE:
var isDataReceived= false, waitTime= 1000;
$(function() {
// Ajax request sent.
var xhr= $.ajax({
url: 'http://api.joind.in/v2.1/talks/10889',
data: {
format: 'json'
},
dataType: 'jsonp',
success: function(data) {
isDataReceived= true;
$('#info').text(data.talks[0].talk_title);
},
type: 'GET'
});
// Cancel ajax request if data is not loaded within 1sec.
setTimeout(function(){
if(!isDataReceived)
xhr.abort();
},waitTime);
});
This is my implementation based on many answers above:
var activeRequest = false; //global var
var filters = {...};
apply_filters(filters);
//function triggering the ajax request
function apply_filters(filters){
//prepare data and other functionalities
var data = {};
//limit the ajax calls
if (activeRequest === false){
activeRequest = true;
}else{
//abort if another ajax call is pending
$request.abort();
//just to be sure the ajax didn't complete before and activeRequest it's already false
activeRequest = true;
}
$request = $.ajax({
url : window.location.origin + '/your-url.php',
data: data,
type:'POST',
beforeSend: function(){
$('#ajax-loader-custom').show();
$('#blur-on-loading').addClass('blur');
},
success:function(data_filters){
data_filters = $.parseJSON(data_filters);
if( data_filters.posts ) {
$(document).find('#multiple-products ul.products li:last-child').after(data_filters.posts).fadeIn();
}
else{
return;
}
$('#ajax-loader-custom').fadeOut();
},
complete: function() {
activeRequest = false;
}
});
}

How can I execute a query on success of jQuery

I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});

Reload only a <DIV> and php code with in that div

I have below code in a page called home.php.
<div class="Wrapper-notify" id="Wrapper-notify">
<?php echo rand(10,100); ?>
</div>
How can I reload only this div and the php code on regular time interval. (I'm using codeigniter framework) please help
PHP is evaluated on the server-side, so you will need to make a call to the server in order to re-evaluate the PHP expression. Considering that the only thing your PHP seems to be doing is generating a random number, and depending on what you're trying to accomplish overall, you might consider using Javascript to "refresh" the div, instead. You could do something like this:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function refreshDiv() {
var divObj = document.getElementById("Wrapper-notify");
var randNum = getRandomInt( 10 , 100 );
divObj.innerHTML = String( randNum );
}
setInterval( "refreshDiv()" , 2000 );
The above Javascript will change the number inside the div every 2 seconds.
You should first create a .php page, let's say test.php printing data like this :
<?php
echo rand(10,100);
?>
An you can use this code to load data from your page, this one is pure javascript
function getValue()
{
if (window.XMLHttpRequest)
AJAX=new XMLHttpRequest();
else
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX)
{
AJAX.open("GET", "test.php", false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send();
return AJAX.responseText;
}
else
return null;
}
window.onload=function()
{
setInterval(function(){
document.getElementById("Wrapper-notify").innerHTML = getValue();
},1000);
};
However, if you are using jQuery you can the use .get method to load data from server
$(document).ready( function()
{
setInterval(function(){ changeDiv(); },1000);
});
function changeDiv()
{
$.ajax({
url: "test.php",
success: function(result)
{
$("#Wrapper-notify").html(result);
}
});
}
You can use AJAX for this,
You define a function that will talk with your server to get data.
$('div #Wrapper-notify').load('http://yoursite.com #newContent');
Set time interval using function and call that in a regular time period like below.
setInterval( function() {
$('div #Wrapper-notify').load('http://yoursite.com #newContent');
}, 6000); // every 6000 milliseconds
I suppose you could do it with AJAX. Do a setInterval in Javascript that executes a function every x seconds. That function should call your PHP file via AJAX and pass the response to your DIV. The PHP file should just contain
<?php echo rand(10,100); ?>
This method is probably overkill for what you're probably aiming to achieve though.
I only see one simple solution, ajax call to a php in a time interval and just push the response into a container:
This is an example using jQuery:
setTimeout(function() {
$.get('/my/page', function(data) {
$('#my_container').html(data);
})
}, 3000);
If you just need random number between 10 and 100 , no need for php ... you need just some javascript : jsFiddle
window.onload=function()
{
setInterval(function(){
document.getElementById("Wrapper-notify").innerHTML = parseInt((Math.random()*100)+10);
},1000);
};
and if you're using some jQuery you can use this : jsFiddle
$(document).ready( function()
{
setInterval(function(){$("#Wrapper-notify").html(parseInt((Math.random()*100)+10))},1000);
});
You need to create new action, that will output only rand number from 10 to 100. Lets call it for example get_rand_num_action:
public function get_rand_num_action(){
return mr_rand(10,100);
}
In your view (where you have Wrapper-notify div), in the end of the or in tag create new ajax request to your get_rand_num_action
Gather data from get_rand_num_action response and update your Wrapper-notify div using native JS or jQuery:
function changeWrapperDiv(){
$.ajax('/controller/get_rand_num_action', {
success: function(response){
$("#Wrapper-notify").text(response);
}
});
}
// Change div every 5 seconds
setInterval(5000, changeWrapperDiv)
Hope this will help you.

How to return json value from php page to html page by ajax and how to show result on html page

I m validating email id in php and ajax, and want to return value from php page to html in JSON format.
I want to keep that return value in php variable for the further use.
I'm doing these all in codeigniter, and I want to show .gif image while my AJAX is processing. (Pre loader image)
AJAX/Javascript/jQuery:
function checkEmail(value_email_mobile) {
if (value_email_mobile !== '') {
//alert('te');
$.ajax({
type: "POST",
url: url_check_user_avail_status,
data: "value_email_mobile=" + value_email_mobile,
success: function(msg) {
alert(msg);
//$('#psid').html("<img src='images/spacer.gif'>");
// $('#stat').html(msg);
//
//$('#sid').sSelect({ddMaxHeight: '300px'});
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
}
PHP/Controller:
<?php
function check_email_or_mobile($param)
{
$ci = CI();
$value = $param['email_or_mobile'];
$query = "SELECT user_email , mobile FROM tb_users WHERE user_email = '$value' or mobile = '$value'";
$query = $ci->db->query($query);
if ($query->num_rows() > 0)
{
if (is_numeric($value))
{
return $res = "This mobile number is not registerd";
}
else
{
return $res = "This Email id is not registerd";
}
}
}
This is just to give you an example on how it will work.
First off, (obviously) there must the a preloader image ready inside the document. This must be hidden initially.
Second, before triggering the AJAX request, show the loading animated GIF.
Third, after the request if successful. Hide the image again inside your success: block inside the $.ajax().
Consider this example: Sample Output
PHP:
function check_email_or_mobile($param) {
// your functions, processes, blah blah
// lets say your processes and functions takes time
// lets emulate the processing by using sleep :)
sleep(3); // THIS IS JUST AN EXAMPLE! If your processing really takes time
$data['message'] = 'Process finished!';
// with regarding to storing, use sessions $_SESSION for further use
$_SESSION['your_data'] = $data_that_you_got;
echo json_encode($data); // use this function
exit;
}
// just a simple trigger for that post request (only used in this example)
// you really dont need this since you will access it thru your url
// domain/controller/method
if(isset($_POST['request'])) {
check_email_or_mobile(1);
}
HTML/jQuery/AJAX:
<!-- your animated loading image -->
<img src="http://i600.photobucket.com/albums/tt82/ugmhemhe/preloader.gif" id="loader" style="display: none;" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- <script type="text/javascript" src="jquery.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
// before the request, show the GIF
$('#loader').show();
$.ajax({
url: document.URL, // JUST A SAMPLE (url_check_user_avail_status)
type: 'POST',
data: {request: true},
dataType: 'JSON',
// data: "value_email_mobile=" + value_email_mobile,
success: function(response) {
// After a succesful response, hide the GIF
$('#loader').fadeOut();
alert(response.message);
}
});
});
</script>
My assumption is, since this is just a simple email checking, this wont really take a chunk of time. The other way is to fake the loading process.
success: function(response) {
// After a succesful response, hide the GIF
// Fake the loading time, lets say 3 seconds
setInterval(function(){
$('#loader').fadeOut();
alert(response.message);
}, 3000);
}
Let us know what part of your code is not working?
1) Check if the request flow is hitting the function checkEmail? PHP has inbuilt JSON converting utility json_encode. You could start using that.
2) If you want to store this on the server for further use, you could think about usage like
a) Storing it in Database (If really needed based on your requirements. Note: This is always expensive)
b) Session - If you would want this info to be available for all the other users too.
c) Or keep it in the memory like any of the caching mechanisms like memcache etc
3) For displaying the busy display,
// Before the below ajax call, show the busy display
$.ajax({
});
// After the ajax call, hide the busy display.
You could do this using JavaScript / JQuery on your choice.
I remember using
JSON.parse(data)
to convert JSON ino a javascript object.
Jquery has its own JSON parser btw. Something like $.JSONParse(data)

Error in Javascript return

I want to receive HTML code in chat.openChat() from chat.getHtmlPage() but return operation is "undefined".
var chat = {
openChat : function($url){
$('#popup').html(chat.getHtmlPage($url)); // It's wrong, UNDEFINED.
},
getHtmlPage : function($url){
$.ajax({
url: $url
}).done(function($html) {
return $html; // It's OK! $html is with correct html, see with alert().
});
}
}
$(document).ready(function(){
$('.btnChat').click(function(){
chat.openChat($(this).attr('href')); // It's OK!
...
return false;
});
});
By default AJAX request is asynchronous, so it ends after you get result from getHtmlPage. Even if you change it to be synchronous, you will still have undefined in openChat, because you return value from done handler, not from getHtmlPage.
You should provide a callback to getHtmlPage method. Example:
var chat = {
openChat : function($url){
chat.getHtmlPage($url, function(html) {
$('#popup').html(html);
});
},
getHtmlPage : function($url, callback){
$.ajax({
url: $url
}).done(callback);
}
}
Ajax calls are asynchronously, that's why you can't use the return of the ajax function immediately. to store the result in $('popup').
You will have to do something like this:
openChat : function($url){
chat.getHtmlPage($url));
},
setHtmlPage : function ($html) {
$('popup').html($html);
},
getHtmlPage : function($url){
$.ajax({
url: $url
}).done(function($html) {
chat.setHtmlPage($html);
});
}
You may also want to have a look to the jquery documentation about ajax. There is a way to make ajax requests synchronously, but that will block your browser and it's deprecated in the newer versions. (and it's not really ajax after all)
Check the part about async
It should be like this:
var chat = {
openChat : function($url){
chat.getHtmlPage($url);
},
getHtmlPage : function($url){
$.ajax({
url: $url
}).done(function($html) {
$('#popup').html($html);
});
}
}
$(document).ready(function(){
$('.btnChat').click(function(){
chat.openChat($(this).attr('href')); // It's OK!
...
return false;
});
});
AJAX is asynchronouse. Once you call it, script exection goes to next line and .done is called later, after request is finished. Also, return from done will do nothing. As it's jquery ajax event triggered after request is done. And jquery will not pass returned value to upper level of code even if you will make it work in synchronouse way.
The first 'A' in AJAX is 'Asynchronous', this means: by the time the .done() gets called, the rest of your code already moved on. With this knowledge, a return in .done() simply makes no sense.
Instead, we just deactiveate the asynchronous behaviour of AJAX, setting async: false in the .ajax-object. But be aware that this is not the original purpose of AJAX and it may cause trouble in some browsers.
Oone solution would then be to set the return into your getHtmlPage (in addtion to setting async to false!):
getHtmlPage : function($url){
//a new variable to store the ajax-result
//defining it here, so it's only visible within the scope of getHtmlPage
var html;
$.ajax({
url: $url,
async: false
}).done(function($html) {
//we use the html variable here to store the result
html = $html;
});
//finally returning the variable
return html;
}
This way, your return statement won't be executed until the ajax-call finishes.
SOLUTION
To do one general function (original idea).
var chat = {
openChat : function($url, $htmlElement){
chat.setHtmlPage($url, $htmlElement);
},
setHtmlPage : function($url, $htmlElement){
$.ajax({
url: $url
}).done(function($html) {
$($htmlElement).html($html);
});
}
}
$(document).ready(function(){
$('.btnChat').click(function(){
chat.openChat($(this).attr('href'), '#popup');
...
return false;
});
});

Categories