Início > Javascript, jQuery > Wait an response from ajax request

Wait an response from ajax request

Hi,

I was had some problem with javascript processing why I need the response from ajax request and with return do some process and manipulation inserting contents, something like that:

$(“#btn-export”).click(function (event) {
var graphicPage = $(“<div id=’content’></div>”);

$.get(“/Report/graphic.htm”, function (data) {
graphicPage.html(data);
});

graphicPage.find(“img”).each(function(key, value) {

$(value).attr(“src”,  document.location.protocol + “//” + document.location.host + $(value).attr(“src”));

});

//more processing

$(“body”).append(‘<form id=”exportform” action=”../Report/Export” method=”post” target=”_blank”><input type=”hidden” id=”exportdata” name=”exportdata” /></form>’);
$(“#exportdata”).val(graphicPage.html().toString());
$(“#exportform”).submit().remove();
});

But my problem was on the final to send to the resource to be processed as Excel spreadsheet, because the ajax request is asynchronous and the graphicPage variable sometimes is empty and another time contain the original content from request. How to I solve that?

I was search this link (documentation of jQuery.get()) and the last comment an user (Hyponiq) gave the solution to another user. Solution:

var value = (function () {
var val = null;

$.ajax({
‘async’: false,
‘global’: false,
‘url’: ‘path/to/url.php’,
‘success’: function (data) {
val = data;
}
});

return val;
})();

Using this solution I adapt to my problem and came up with this code:

$(“#btn-export”).click(function (event) {
var graphicPage = (function () {
var value = $(“<div id=’content’></div>”);

$.ajax({
async: false,
global: false,
url: “/Report/graphic.htm”,
success: function (data) {
value.html(data);
}
});

return value;
})();

graphicPage.find(“img”).each(function (key, value) {
$(value).attr(“src”, document.location.protocol + “//” + document.location.host + $(value).attr(“src”));
});

//more processing

$(“body”).append(‘<form id=”exportform” action=”../Report/Export” method=”post” target=”_blank”><input type=”hidden” id=”exportdata” name=”exportdata” /></form>’);
$(“#exportdata”).val(graphicPage.html().toString());
$(“#exportform”).submit().remove();
});

There, now could cause the variable to be filled before processing.

Thanks,

  1. Nenhum comentário ainda.
  1. Nenhum trackbacks ainda.

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Sair / Alterar )

Imagem do Twitter

You are commenting using your Twitter account. Sair / Alterar )

Foto do Facebook

You are commenting using your Facebook account. Sair / Alterar )

Connecting to %s

Seguir

Obtenha todo post novo entregue na sua caixa de entrada.