Search code examples
jqueryajaxcgi

jQuery Ajax CGI: load script


I am trying to load my Perl CGI script's content into the HTML page. .load() does not work. Please tell me what's wrong here:

$(document).ready(function() {
  $('input:checkbox').change(function() {
    var nom = $(this).attr("value");
    if ($(this).is(':checked')) {
      alert('okok');
      $('body').load("../cgi-bin/essai.pl");
    } else {
      //$("#" + nom).remove();
    }
  });

I would like:

  • When I check the checkbox (which has as value "toto") load (in Ajax) essai.pl?param=toto
  • When I uncheck this checkbox, remove the content loaded before.

Hope someone has a little time to help me to leave this jQuery nightmare.
Bye.


Solution

  • You're loading your script's output directly into the body, hence you make all previous body content (including your checkbox(es)) disappear. I assume that is what you experience.

    What you should do is have a dedicated block for the script generated content, and use that block as the target of your load function.

    HTML:

    <body>
    <div id="controller">
      <input type="checkbox" name="toto" id="toto"></input> Load / unload content
      </div>
    <div id="target">
      Content comes here
      </div>
    </body>
    

    JavaScript:

    $('input:checkbox').change(function(){
        if ( $(this).is(':checked') ) {
          var target_url = "../cgi-bin/essai.pl?param="+$(this).attr('name');
          $('div#target').load(target_url);
        }
        else {
          $("div#target").html('');
        }
    });
    

    I would also refrain from the "../cgi-bin/" type relative path definition and use absolute path instead.

    Working example available at http://jsbin.com/izuni4/19

    EDIT Seems like I didn't fully grasp what you were trying to achieve. Here is an edited version of the same javascript which appends/removes content blocks triggered by multiple checkboxes. Hope that solves your issue:

    http://jsbin.com/izuni4/22/