Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target an iframe with a HTML Post with jQuery

If I'm using jQuery or JavaScript to do a post, how can I make it target an iframe rather than the current page?

jQuery.post( 
    url, 
    [data], 
    [callback], 
    [type] 
) 

That is the format of the jQuery post, it doesn't seem as though there is anywhere to specify the target like there is in the <form> tag.

Any ideas?

like image 776
Matt Avatar asked Jun 16 '09 21:06

Matt


4 Answers

You can do this via a regular form:

<form action="targetpage.php" method="post" target="iframename" id="formid">
   <input type="hidden" name="foo" value="bar" />
</form>

You can then use jQuery to submit the form:

$("#formid").submit();
like image 54
Josh Avatar answered Nov 12 '22 02:11

Josh


Maybe you are missing the point of an AJAX request - why are you trying to specify the "target" of an asynchronous request? This makes no sense as the whole point of AJAX is that the request from the server gets sent back to the Javascript, free of page reloads or HTML destinations.

If you wanted to load the result of the request onto an iframe, you might do:

$.post('myurl', function(data) {
    $('#myframe').html(data);
}, 'html');
like image 5
Paolo Bergantino Avatar answered Nov 12 '22 01:11

Paolo Bergantino


You can solve the no-form-allowed-within-a-form problem by dynamically creating the form and appending it to the body. So you'd do something like this:

$().ready(function() {
    $('body').append('<form 
       action="url" 
       method="post" 
       target="iframename" 
       id="myspecialform">
         <input type="hidden" name="parameter" value="value" />
       </form>');
});

That creates your iframe-updating form outside of the main form that encompasses everything else on the page. Then just call it as Josh recommended: $('#myspecialform').submit();.

like image 5
Alexander Garden Avatar answered Nov 12 '22 02:11

Alexander Garden


here is how I did it in javascript with plain html:

var form=$("<form/>").attr({
    method: "post",
    action: "iframe.php",
    target: "list_frame"
});
form.append($("<input/>").attr({name:"field1",value:0}));
form.append($("<input/>").attr({name:"field2",value:1}));
form.append($("<input/>").attr({name:"field3",value:2}));
form.append($("<input/>").attr({name:"field4",value:3}));
form.append($("<input/>").attr({name:"field5",value:4}));
$("body").append(form);
form.submit();
like image 5
Christopher Thomas Avatar answered Nov 12 '22 02:11

Christopher Thomas