简体   繁体   中英

Submit a form inside colorbox with ajax

Until now I was using this code to post data from within a colorbox window until I ran into encoding errors, data being submitted as "ΞΞΞ§Ξ'Ξ©ΞΞ" instead of 'ΔΙΧΡΩΜΟ':

$("#productadd").submit(function(){
  $.post(
  $(this).attr('action'),
  $(this).serialize(),
  function(data){
    alert('Product added to cart!');  
    $().colorbox.close();
  }
);

After some searching I decided to change my code to this so I can set the encoding when posting but I need some help to complete it:

$.ajax({
    type: "POST",
    url: $(this).attr('action'),
    contentType: "application/json; charset=iso-8859-7",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        alert('Product added to cart!'),  
        $().colorbox.close(),
        $("#success").html("json.length=" + json.length);
        itemAddCallback(json);
    },
    error: function (xhr, textStatus, errorThrown) {
        $("#error").html(xhr.responseText);
    }
});

but none of the calls inside success: are made, with the page being redirected to the url in form action and neither the alert or $().colorbox.close() are being called whereas, with the previous code, it used to submit in the same window (without redirectiong to the action url) and showing the alert and finally, closing the colorbox window. Any suggestions?

you have to prevent the normal form submit by preventing it to execute the default action, else it will perform a redirect to the url of the form as a normal form submission.

$("#productadd").submit(function(e){
e.preventDefault();
$.ajax({
    type: "POST",
    url: $(this).attr('action'),
    contentType: "application/json; charset=iso-8859-7",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        alert('Product added to cart!'),  
        $().colorbox.close(),
        $("#success").html("json.length=" + json.length);
        itemAddCallback(json);
    },
    error: function (xhr, textStatus, errorThrown) {
        $("#error").html(xhr.responseText);
    }
});
});

i believe this solves you problem with form submission

$("#productadd").submit(function(event){
event.preventDefault(); // prevent submission of the form and send ajax
  $.post(
  $(this).attr('action'),
  $(this).serialize(),
  function(data){
    alert('Product added to cart!');  
    $().colorbox.close();
  }
);

as for the encoding it could depend on Browser encoding that you get that result, try changing to other greek encodings or UTF-8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM