How to submit second AJAX form produced from output of first - javascript

I am loading a form as a json output from an AJAX request.
The following PHP forms the JSON output of the request that displays the form:
$this->errors[] = "<form id='confirmreset' name='confirm_reset' action='" . URL .
"login/forgotPassword_action' method='post'><input type='hidden' name='user_email' value='" .
$this->user_email . "'> Email already registered. <input type='submit'
value='Click here for a PIN reminder'></form>";
I then want to be able to submit this form as an AJAX form too, but because it's not loaded in the DOM, my jquery doesn't seem to reference it. Any ideas?
Here's the code so far:
$("#confirmreset").on("submit",function(event){
//disable default click operation
event.preventDefault();
var action_url = $(this).attr("action");
alert_box_register("Resetting password...");
console.log(action_url);
var postData = $(this).serializeArray();
console.log(postData);
$.post(action_url,postData,function(data){
console.log(data);
var obj = $.parseJSON(data);
alert_box_register(obj.message);
});
});

Use .on()
As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.
$(document).on('submit','#confirmreset',function(event){ ..code here.. }
Syntax
$( elements ).on( events, selector, data, handler );

This should be as simple as putting the second request inside the first one's success function.

Related

jquery Post value to PHP webpage

I have made a web page with a dropdown menu. The idea is when we click any option of the dropdown menu it open produccion.php with a POST parameter 'edicion'. This parameter I use to do a query in a Database.
At moment the problem is that it's open the produccion.php but I think that doesn't POST the value of the variable
Jquery code:
$('#drEdicion a').click(function(event){
alert($(this).text());
var ed = $(this).text();
$.ajax({
url:"produccio.php",
type:"POST",
data:{edicion: ed},
dataType:"text",
success:function(data){
window.location.href = 'produccio.php'
}
});
});
Is it possible that the problem is when it's send via ajax?
Thanks in advance.
Your code is currently POSTing the content of the hyperlink over to produccio.php via AJAX. When that call completes it is then redirecting the user to the same page but without the POSTed value. Based on your comment:
I want to open produccion.php after selection option in dropdown button. With this option I do a query
it appears you actually want to open produccio.php with the POSTed value in the browser.
By far the easiest solution to the problem would be to alter the PHP code to accept the value of edicion from $_GET["edicion"] instead, and output your hyperlink as:
...
This will also provide a better experience for users, especially if they have issues with JavaScript (or, for example, happen to be a search engine). However, if you're set on only using $_POST, the following code may - I've not tested this myself - allow this:
$('#drEdicion a').click(function(event){
event.preventDefault();
var ed = $(this).text();
$('<form action="produccio.php" method="POST">' +
'<input type="hidden" name="edicion" value="' + ed + '" />' +
'</form>').appendTo('body').submit();
});
(with credit to the top answer on Dynamically create and submit form)
Follow bellow code :
$('#drEdicion a').click(function(event){
//alert($(this).text());
event.preventDefault();
var ed = $(this).text();
$.ajax({
url:"produccio.php",
type:"POST",
data:{edicion: ed},
dataType:"html",
success:function(data){
//#dropdown-menu id show all produccio.php data
$("#dropdown-menu").html(data);
}
});
});
produccio.php
<?php
$edicion = $_POST['edicion'];
//now you can able to access edicion post param
?>
HTML like this :
<div id="dropdown-menu"></div>

Using jquery to submit one form on page that shares element names with other forms

To give you the most basic view of my question, I'm trying to create a page that is very similar to how facebook and twitter's dashboards and comment systems work. You have one page that will continuously create form elements (posts) from database rows in a loop as the user scrolls down. Users will then be able to comment on each of these posts. I want to be able to use ajax to submit comments on each post individually without reloading the page.
I run into a problem where when I try to submit a comment on any form other than the first one that is loaded on the page. In addition the ajax only posts the first form elements on submit (due to each form and elements having the same name I'm guessing).
Below is my comment loading script: [forgive the old php, I know I need to update it to mysqli or PDO]
php
<?php ...
$query = mysql_query("SELECT * FROM `posts`");
while ($row = mysql_fetch_array($query)) {
echo "
<div name='comment_body'>
<form name='comment_form'>
<td>User: ".$row['user']."</td>
<td>Post: ".$row['post']."</td>
<textarea name='comment'></textarea>
<p name='post_id' style='display:none;'>".$row['post_id']."</p>
<input type='submit' name='submit'>
</form>
";
$query2 = mysql_query("SELECT * FROM `comments` WHERE `post_id` = $row['post_id']");
while ($row2 = mysql_fetch_array($query2)) {
echo "
<td>User: ".$row2['user']."</td>
<td>Comment: ".$row2['comment']."</td>
</div>
";
}
... ?>
jscript
<script>
$('.comment_form').on('submit', function (e) {
e.preventDefault();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : $('#comment').val(), post_id : $('#post_id').text()}
success: function() {
$("#comment_body").load("load_comments.php #comment_body");
}
});
});
</script>
The script works to a point because when I comment on the first post, it works as expected. I just can't seem to figure out how to target the forms further down the page individually. Here's an example:
The very top post has a post_id value of 40. If I comment on post_id = 38, ajax will submit the empty comment field and post_id = 40 into the database.
Any help with the script form targeting would be great. If I need to rebuild my php query to give each echoed form element an individual name, that's fine as well. Thanks in advance!
The data you're trying to send to in the ajax call is using:
$('#comment').val(), post_id : $('#post_id').text()
But your HTML doesn't have anything with an ID="comment" and ID="post_id". (the '#' in your selector means getElementById.) So you aren't sending any data to your php page. You need to use the correct selectors to get that data. (see below)
Get rid of the 'form' tags you don't need them. Change your
<input type="submit">
to a:
<input type="button" class="comment-submit">
Then your script can be:
<script>
$('.comment-submit').on('click', function (e) {
e.preventDefault();
// get a referenct to this particular comment_body div
var $commentbody = $(this).closest('.comment_body');
// find the textarea within this particular comment_body
var commenttext = $commentbody.find('textarea[name="comment"]').val();
// find the post_id paragraph within this particular comment_body
var postId = $commentbody.find('p[name="post_id"]').text();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : commenttext , post_id : postId}
success: function() {
$comment_body.load("load_comments.php #comment_body");
}
});
});
</script>
Frankly I'm not sure what your success function is trying to do. But I think you need to work on it too. Normally an ajax call will return data so your success function should have a return value and that would be used to populate some part of your screen. The jQuery 'load()' function is another ajax call inside the success callback of an ajax call. I really don't think you want or need to do this.
You cannot select a unique form by class because your class is identical across all forms. Add an "id" field to the form element like this:
"<form name='comment_form' id='"+ .$row['id'] +"'>"
Then select a given form using that unique ID, and add your event handler. This must be in the same scope as you define your form. Like this:
$('#'+ .$row["id"]).on('submit', function (e) {
//Handle the event
})

.post() return ID not being affected by pages Jquery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
This question is directly related to the question I asked here:
stop click() from happening on a ajax created input
I figured out the answer to that one by simply adding if (e.target === this), but now my returned response wont do anything when I check the box.
The new code that is being returned by my .post is:
$output .= "<table><tr><td>";
$output .= "<input id=\"toedit\" type=\"text\" placeholder=\"$item_to_edit\" size=20>";
$output .= "</td><td>";
$output .= "<input id=\"test_editing_check\" type=\"checkbox\" name=\"test_editing_check\" value=\"test_editing_check\" \>";
$output .= "</td></tr></table>";
But my Jquery which is on the original page:
$("#testing_editing").click(function(e){
if (e.target === this) {
var testhtml = $(this).html();
var meatseafood = '<?php echo $meatseafood; ?>';
$.post('edit_order.php', {'itemtoedit':testhtml,'meatseafood':meatseafood}, function(data) { //make ajax call to check_username.php
$("#testing_editing").html(data); //dump the data received from PHP page
});
}
});
$("#test_editing_check").click(function(){
if ( this.checked ) {
var testvalue = "HI";
alert(testvalue);
}
});
Doesn't seem to work on the check box that is being returned by the .post() call.
Is there something i need to do in order to make a .post() return be recognized by the main page's jquery code?
I hope its not something wrong with my syntax but i've used this exact (very basic) code on another page (but not with a .post() call) and it works fine.
Basically, when you click the div my main page writes, it calls a .post() and returns a editable input field and a check box. When i click that checkbox, i want it to make another .post() call and update a database with the newly entered data.
however, when i check the check box nothing happens.
it would seem my ajax returned code isn't recognized by the jquery from the original/main page.
with my test code all i'm trying to do is pop up an alert box when i click the checkbox to show that it has "read" the input box and can now send that data through the .post() call to be processed.
Let me know if you need any other code.
It seems pretty cut and dry though so i'm not sure why it isn't working and that's why i'm here :)
(the idea of what i'm trying to do is, a user submits a form, on the next page, a "confirmation box" is shown saying "is this what you wanted to submit with your form? and if the answer is no, they can "click" on the data and change it w/out having to reload the page. the clicking part works but the checkbox to acknowledge "yes, i want to change my data to this newly entered data" isn't working.)
Thanks for any help.
Derek Conlon
Try to assign the event after loading the checkbox like this:
$("#testing_editing").click(function(e){
if (e.target === this) {
var testhtml = $(this).html();
var meatseafood = '<?php echo $meatseafood; ?>';
$.post('edit_order.php', {'itemtoedit':testhtml,'meatseafood':meatseafood}, function(data) { //make ajax call to check_username.php
$("#testing_editing").html(data); //dump the data received from PHP page
// This is applied after loading the data from the ajax call
$("#test_editing_check").click(function(){
if ( this.checked ) {
var testvalue = "HI";
alert(testvalue);
}
});
});
}
});

Post data with jQuery

I'm using sortable to sort a list. Then once the user clicks the Submit button I want it to post the data to another php page. I currently can get it to display an alert with the data I want posted but can't get the JavaScript post right.
This is the submit button.
<input type='submit' value='Submit' onclick='saveOrder();'/>
This is the JavaScript part that creates an alert.
function saveOrder()
{
var wordOrder = $( "#sortable" ).sortable('toArray').toString();
alert(wordOrder);
}
This outputs a,b,c,d,e in an alert box. I want this posted instead of showing an alert.
What I would like to do is post this data so I can loop through it on another PHP page.
foreach( $_POST as $stuff )
{
echo $stuff;
}
You can do this via ajax: -> http://api.jquery.com/jQuery.post/
function saveOrder() {
var wordOrder = $( "#sortable" ).sortable('toArray').toString();
$.post( "your/file.php", {wordOrder: wordOrder}, function( data ) {
//Do nothing
});
//$.post("your/file.php", {wordOrder: wordOrder});
}
in PHP, you can:
echo $_POST['wordOrder'];

Submitting a dynamic form in jQuery

I am dynamically creating a form in Jquery, and this form needs to submitted using AJAX. I'm probably doing something stupid, so your help would be greatly appreciated.
I am dynamically creating a form when a link is clicked:
$('.edit_item').click(function(){
$(this).closest('table').wrap("<form id='update_project' name='update_project' method='POST'>");
var input_name = $(this).closest('tr').find("td:eq(0)");
var input_submit = $(this).closest('tr').find("td:eq(1)");
input_name.html("<input type='text' id='update_name' name='update[]' value='"+input_name.text()+"' />");
input_submit.html("<input type='submit' value='update' id='update_submit' name='update_submit' />");
});
When the form is submitted:
$('#update_project').live("submit", function(e){
e.preventDefault();
$.post('project/update', $(this).serialize(), function(data){
$('#complete_msg').html(data);
});
$('.update_submit').css('background', '#c9c9c9');
});
Unfortunately, the page is refreshing (it shouldn't), and there is no return.
Thank you!
I would change the submit to a button:
input_submit.html("<input type='button' value='update' id='update_submit' name='update_submit' />
and the event, live is depreciated (http://api.jquery.com/live/):
$('#update_submit').click(function(e){
$.post('project/update', $('#update_project').serialize(), function(data){
$('#complete_msg').html(data);
});
$('.update_submit').css('background', '#c9c9c9');
});
Forgive me if my answer is too basic - your coding is quite advanced but you missed a couple of things. Better for me to be too pedantic rather than not provide enough info to immediately resolve your problem.
The page is refreshing when user clicks the update button because you are using the .submit method. If you do not want the form to refresh, use Stephen King's answer above to:
change the <input> type to type="button", then
use the ("#yourbuttonID").click() event to $.post your form data.
Also as SK said above, note the .live() is deprecated, so simply switch for .on()
Try this:
$('.edit_item').click(function(){
$(this).closest('table').wrap("<form id='update_project' name='update_project' method='POST'>");
var input_name = $(this).closest('tr').find("td:eq(0)");
var input_submit = $(this).closest('tr').find("td:eq(1)");
input_name.html("<input type='text' id='update_name' name='update[]' value='"+input_name.text()+"' />");
input_submit.html("<input type='button' value='update' id='update_submit' name='update_submit' />");
});
$(document).on("click", "#update_submit", function(e){
$.post('your_processor_filename.php', $(this).closest('form').serialize(), function(data){
$('#complete_msg').html(data);
});
$('.update_submit').css('background', '#c9c9c9');
});
Note that you need the .closest('form') selector to get your form data serialized.
I would also use $(document).on('click'... to ensure your injected button is found.
I am unfamiliar with the type of file to which you are sending the form data for processing, but project/update is not a familiar file type to me. Ensure that it is a page of code that can process your data, such as a .PHP file. See my example above -- or, better yet...
By way of example, create a .PHP file named 'your_processor_filename.php' (i.e. the filename I am referencing in the code I typed above). Put it in the same folder and type the following at the top:
//echo 'Got to the PHP side';
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
That will echo back what you sent and allow you both to see the data going through and confirm that the AJAX is working.
Note that your HTML must contain a div with the ID complete_msg to see the return message, such as:
<div id="complete_msg"></div>

Categories

Resources