开发者

Jquery help creating ajax request

开发者 https://www.devze.com 2023-03-25 15:38 出处:网络
I am trying to create an ajax request where the URL is the form on submit. My Jquery: $(document).ready(function()开发者_Python百科 {

I am trying to create an ajax request where the URL is the form on submit.

My Jquery:

    $(document).ready(function()开发者_Python百科 {
$('.menuitem input:checkbox').change(function(){
        $.ajax({
          type:'get',
          url:form.submit();,
          data:form.serialize(),
          success:function(msg){
            $('#formcontent').html(msg);
          }
        })
    })
    $('input:submit').hide();

    $('.menuitem input:checkbox').change(function(){
    if($(this).is(":checked")) {
        $('div.hidediv').removeClass("hidediv");
    } 
});
});


$('.menuitem input:checkbox').change(function() {
    // fetch the form containing the checkbox whose value
    // has just changed so that we could infer its action and method
    var form = $(this).closest('form');
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: form.serialize(),
        success: function(msg) {
            $('#formcontent').html(msg);
        }
    });
});


fixed code

$(document).ready(function() {
    $('.menuitem input:checkbox').change(function(){
        var form = $(this).parents('form');
        $.ajax({
          type:'get',
          url:form.attr('action'),
          data:form.serialize(),
          success:function(msg){
            $('#formcontent').html(msg);
          }
        });

    $('input[type="submit"]').hide();

    $('.menuitem input[type="checkbox"]').change(function() {
        if($(this).is(':checked')) {
            $('div.hidediv').addClass('someclass'); // not needed it there is another way of identifying the div later to add to hidediv class again.
            $('div.hidediv').removeClass('hidediv');
        } else {
            $('div.someclass').addClass('hidediv'); 
        }
    });
});

Explanation:

  1. What is form it isn't defined anywhere.
  2. If form is defined and you do form.submit(); you would submit the form (not what you want.)
  3. You also missing a semicolon after the ajax function.
  4. you also used the wrong way of getting inputs of a specific type


The line where you have:

url: form.submit;,

should be:

url: form.attr('action'),

So you end up with:

    $.ajax({
      type:'get',
      url:form.attr('action'),
      data:form.serialize(),
      success:function(msg){
        $('#formcontent').html(msg);
      }
    })

You may also want to change the "type" value to form.attr('method') for consistency.

0

精彩评论

暂无评论...
验证码 换一张
取 消