1

I have a bunch of forms as rows in a table. There's a submit button at the end of each row. When this button is clicked, my JQuery function creates two text boxes and another submit button. I want the POST variables from the both forms, so I can ultimately pass it onto my php script via AJAX. What would be the best way of doing this?

<script>
<?php 
$ajax_var = <<<HTML
<form method="post" id="ajax_form">
<div id="ajax_input">
    <input type="text" name="user_name" placeholder="Your name">
    <br>
    <input type="text" name="user_email" placeholder="Your e-mail">
    <br>
</div>
    <input id="ajax_submit" type="submit" value="submit">
</form>
HTML;
$ajax_var = str_replace("\n",'',$ajax_var);
?>

$("form").submit(function(e)
{
    e.preventDefault();
    $("#wrapper").prepend('<?php echo "$ajax_var" ?>');
});
$("form#ajax_form").submit(function(e)
{
    e.preventDefault();
});
</script>

The last JQuery function does not work as intended. Pressing the ajax-created submit reloads the page :S

1 Answer 1

1

As #ajax_form is not present initially. you should use .on:

$("#wrapper").on("submit", "form#ajax_form", function(e) 
{
    e.preventDefault();
    alert("It is working...");
    // Your code for Ajax
});

You can use any element wrapping the new form, if not sure put "body" in stead of "#wrapper".

Documentation: http://api.jquery.com/on/

Code Added as per communication in comments:

<script type="application/javascript">
var arr;
$(function(){
$("form").submit(function(e)
{
    e.preventDefault();
    $("#wrapper").prepend('<?php echo "$ajax_var" ?>');
    arr = $(this).serializeArray();
});
$("#wrapper").on("submit", "form#ajax_form", function(e)
{
    console.log(arr);
    e.preventDefault();
});
});
</script>
Sign up to request clarification or add additional context in comments.

8 Comments

Nice! And how should I pass $_POST variables between the forms I have in my table to my new AJAX form?
You can use form.serializeArray() for both forms, it will return you data for all fields in array format.
Okay, and if I assign it to a variable, it will be preserved between events?
I tested it, and it went out of scope once the second event was called (ajax form).
prepare a fiddle please or show me your full code. how are you declaring variable, just show me 2 - 3 lines around that?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.