I’m creating a jQuery example for a presentation in my Web class. I’m trying to convert a Javascript program we did as an exercise to jQuery (for the useful parts, like AJAX). So far so good, everything is working fine. Only thing : i can’t figure out how to populate select elements with options via Asynchronous AJAX.
Here is a screenshot of the program, so I don’t have to explain everything : http://imageshack.us/a/img829/5475/tableaui.png
All the cells are input elements with text inside it, and every modification is saved via AJAX. The last line is there to add a new row. When it is added, I add the row (with table.appendChild(tr) ) with all the elements created one by one inside it. Everything works there except for the selects (which are empty at first, their content is extracted from the DB). Here is some code (inside the function addLine, which is called after ajax confirms that my data has been inserted in the DB) :
input = document.createElement('select');
input.setAttribute('id', 'ID'+no_ligne+'_'+noms_champs[compteur]);
input.setAttribute('name', 'ID'+no_ligne+'_'+noms_champs[compteur]);
input.innerHTML = ajaxRequest('contenu_select', Array(no_ligne, valeurs[noms_champs[compteur]], noms_champs[compteur]));
ajaxRequest is what follows :
function ajaxRequest(action, data, ligneModifie, champModifie)
{
var AJAX_Controller = 'exer_7_carnet_formulaire.php';
var post_data = resultat_ajax = "";
// Set the posted data
if(action == 'update') {
//stuff
}
else if(action == 'insert') {
//stuff
}
else if(action == 'contenu_select') {
post_data += "noLigne=" + data[0] +
"&selected=" + data[1] +
"&type=" + data[2];
}
else {
post_data = null;
}
// Send the request
var jqxhr = $.ajax({
type: "POST",
url: AJAX_Controller+'?ajax=1&action='+action,
data: post_data,
success: function(reponse) {
resultat_ajax = processResponse(reponse, data, action);
}
});
return resultat_ajax;
}
gererReponse returns a string of all my options (confirmed working). The problem is : it executes the return before the request is finished, so it returns an empty string (since resultat_ajax is not yet defined). I confirmed with a setTimeout then the variable has the expected value after a second.
My question is : how can I populate my select in this case? The other version I created before (without jQuery) worked like a charm, with the exact same code except for the ajaxRequest function. Here is the function without jQuery who used to be there instead, which is working (returning my expected options) :
function ajaxRequest(action, data, ligneModifie, champModifie)
{
// Variables
var ReqTerminee = 4;
var ReponseOK_Local = 0;
var ReponseOK_Remote = 200;
var AJAX_Controller = 'exer_7_carnet_formulaire.php';
var xhr = getXMLHttpRequest();
var post_data = typeDeContenu = resultat_final = "";
// Monitoring request state
xhr.onreadystatechange = function() {
if (xhr.readyState == ReqTerminee)
if (xhr.status == ReponseOK_Local || xhr.status == ReponseOK_Remote)
resultat_final = gererReponse(xhr.responseText, data, action); // Here is the interesting part, this actually works and returns the right value.
else
alert("Code d'erreur: " + xhr.status);
};
// Sets the posted data
if(action == 'update')
{
// blahblah
}
else if(action == 'insert')
{
//blahblah
}
else if(action == 'contenu_select')
{
post_data += "noLigne=" + data[0] +
"&selected=" + data[1] +
"&type=" + data[2];
}
else
{
post_data = null;
}
// Sends the request
xhr.open("POST", AJAX_Controller+'?ajax=1&action='+action, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(post_data);
return resultat_final;
}
I’m a little disappointed that I can’t get the same result with the powerful jQuery than I get with simple Javascript :/ Do you have an idea of how I could manage to get the good returned value?
Thanks in advance, any help would be appreciated!
Sam
Your problem is that in pure JS you are using synchronous request. Which is specified by third parameter set to false in this line:
So, in this case browser is waiting until request is done at this line:
and than execute onreadystatechange handler and only after that
returnis executed.jQuery has the same option (see
async:falseadded):But – do not do that. JS is always executed in single thread and synchronous request will freeze whole page. Users will not be happy). Correct way to do that is to replace:
with
Of course, you will need to pass
no_ligne,noms_champsandcompteurintoajaxRequest