Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8611763
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T04:27:17+00:00 2026-06-12T04:27:17+00:00

I’m creating a jQuery example for a presentation in my Web class. I’m trying

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T04:27:18+00:00Added an answer on June 12, 2026 at 4:27 am

    Your problem is that in pure JS you are using synchronous request. Which is specified by third parameter set to false in this line:

    xhr.open("POST", AJAX_Controller+'?ajax=1&action='+action, false);
    

    So, in this case browser is waiting until request is done at this line:

    xhr.send(post_data);
    

    and than execute onreadystatechange handler and only after that return is executed.

    jQuery has the same option (see async:false added):

    $.ajax({
        type: "POST",
        url: AJAX_Controller+'?ajax=1&action='+action,
        async:false,
        data: post_data,
        success: function(reponse) {
            resultat_ajax = processResponse(reponse, data, action);
        }
    });
    

    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:

    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]));
    

    with

    $.ajax({
            type: "POST",
            url: AJAX_Controller+'?ajax=1&action='+action,
            async:false,
            data: post_data,
            success: function(reponse) {
                resultat_ajax = processResponse(reponse, data, action);
                input = document.createElement('select');
                input.setAttribute('id', 'ID'+no_ligne+'_'+noms_champs[compteur]);
                input.setAttribute('name', 'ID'+no_ligne+'_'+noms_champs[compteur]);
                input.innerHTML = resultat_ajax;
            }
        });
    

    Of course, you will need to pass no_ligne, noms_champs and compteur into ajaxRequest

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am reading a book about Javascript and jQuery and using one of the
I am trying to render a haml file in a javascript response like so:
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.