JMarc
JMarc

Reputation: 1004

iframe versus div + jquery

I would like to know what is the more appropriate for what I want to achieve:

On my main page (main.php), I have links to different forms: form1.php, form2.php, form3.php. I need the pages of the links to open in a portion of main.php, i.e in a div or in a iframe on main.php, without refreshing main.php. The form pages enables to populate, delete, update a database. When I do those actions, I don't want main.php to refresh but only the appropriate form page. My first option is to open form1.php for example in a iframe of main.php. When I submit a form, only form1.php in the iframe is refreshed. My second option is to use jquery: open the link (form1.php) in a div of main.php. Submit the form within the div, and refresh the div only.

The second option is more demanding since I do not have much experience with ajax and jquery. The first option is more straight forward for me. I am wondering if there is any advantages to use the second option with a div refresh compared to iframe, i.e compatibility with different browsers and else... Thanks.

Upvotes: 8

Views: 4040

Answers (2)

user753676
user753676

Reputation:

Try $("#div").load("form.php"); from jQuery

This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data.

Reference: .load() | jQuery API Documentation

Upvotes: 1

Umur Kontacı
Umur Kontacı

Reputation: 35478

I'd recommend using jquery, ajax(XMLHttpRequest). Iframes are old, not semantic and you cannot access to an iframe within main.php.

$("#submit_button_id").click(function(e) {
    e.preventDefault();
    $.post('form.php', $("#form_name").serialize(), function(result) { 
        $("#div_id").html(result); } }

this snippet should work.
$("#submit_button_id").click(function(e) { : catches the click function of the assigned id and creates a trigger.

e.preventDefault(); : prevents the form submit regularly, we are going to submit it by jquery.

$.post sends the form in POST method.

'form.php' is your form controller which is going to return an html code to be shown.

("#form_name").serialize() this function is a utility for serializing form to be sent. it loads the input fields and converts them to like { field1: value, field2: value }

function(result) { is the 3rd parameter, on success, $.post calls the 3rd parameter as a function. we create an anonymous function to replace html of our div.

$("#div_id").html(result) sets the assigned div's html to result variable.

refer to http://api.jquery.com/ , they have a wonderful reference sheet.

Upvotes: 3

Related Questions