Ranjith
Ranjith

Reputation: 2819

Load file into jquery dialog

I just confused with jquery dialog and with php form submit

I have two forms, page1.php and page2.php

In page1.php, I have <a> link

<a id="addNew"> Add New </a>
<div id="myDiv"> 
       <!-- load 'page2.php' file using this div --> 
</div>

and when I click this link , load page2.php file in jquery dialog with form values.

This is my script

<script>
   $("#addNew").click(function() {
       $("#myDiv").load('page2.php').dialog({modal:true}); 
   });
</script>

These scripts works fine load with page2.php file.

Now my question is,

when I submit form values of page2.php it will be re-directed to page2.php. But I wants to stay with my page1.php.

How to I achieve this? Thanks in advance

Upvotes: 0

Views: 505

Answers (2)

Ohgodwhy
Ohgodwhy

Reputation: 50808

Seeing as how you didn't provide a form, one can only make assumptions.

<form id="some_form" action="page2.php" method="post">
    <input type="text" name="user_name"/>
    //a collection of form elements
<form>

Then use ajax, and capture the form submit event, while preventing it from it's default action

$(document).on('submit', '#some_form', function(e){
    e.preventDefault(); //stop form from redirecting, also stops sending of data
    var $this = $(this); // cache form object for performance
    $.ajax({
        url: $this.prop('action'),
        type: $this.prop('method'),
        data: {
          handle_form: 'ajax',
          form_data : $this.serializeArray()//array of objects
        },
        success:function(data){
            //data is what is returned from the server if successful
        }
    });
    return false; //just another example of stopping form submit, don't need both
});

Then in your page2.php file, just check for the existence of a field.

if(isset($_POST['user_name']) && $_POST['handle_form'] == 'ajax'):

    //your form is trying to be submit
    //handle the submission
    echo 'We submit the form!'; //is the 'data' in our success function

elseif(isset($_POST['user_name']) && !isset($_POST['handle_form'])):

    //regular form submission, no ajax, no javascript.

endif;     

Upvotes: 1

Daniel
Daniel

Reputation: 18692

You can use ajaxForm which will submit form using an ajax call when you loaded your page2. For example:

HTML:

<form id="login" action="YOUR_FILE" method="post">
    <label>Name:</label>
        <input type="text" name="name" /><br />

    <label>Password:</label>
        <input type="password" name="pass" /><br />

    <input type="submit" name="submit" value="Login" /> 
</form>

JavaScript:

function processJson(data) {
    // your code goes here
}
$("#login").ajaxForm({
     dataType:  'json',
     success:   processJson // what to do when call succeed 
});

Have a nice day!

Upvotes: 0

Related Questions