Adding an event to dynamically generated element using jQuery [duplicate] - php

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I tried to add a form from a php file to another php file using jQuery, and I added an event to my added input(submit) button, but it's nt work,
I have seen some answers that propose using the method $elm.on("click",function() instead of of $elm.click(function(), but it still not work.
So here is my code :
<div id="update" class="third">
<div class="updatingzone">
You will have to rwrite all the data again
<form method="post" class="updating">
<input type="text" name="id" class="id" style="width:40px;" />
<input type="submit" id="button" value="Insert" />
</form>
<input type="submit" id="button" class="cancel" value="Cancel" />
</div>
<div class="insertion"></div>
</div>
when I press the Button Insert this php file is added :
<?php require_once "connexion.php";
$gdb = new GestionBD();
$id = $_POST["id"];
$req = "select * from utilisateurs WHERE id='$id'";
$results = $gdb->selectFromBD($req);
foreach ($results as $result):
?>
<form class="insertMode" method="post">
<input type="text" value="<?php echo $result->nom;?>" class="nom" name="nom" /><br />
<input type="text" value="<?php echo $result->email;?>" class="email" name="email" /><br />
<input type="text" value="<?php echo $result->sexe;?>" class="sexe" name="sexe" /><br />
<input type="text" value="<?php echo $result->age;?>" class="age" name="age" /><br />
<input class="test" id="button" type="submit" value="Add" />
</form>
<?php endforeach;?>
When I press the button with the class test I don't get an alert with "no" message, as you can see in the script :
$(".updating").submit(function () {
var id = $(".id").val()
$(".insertion").show()
$.post("getId.php",{id:id},function (data) {
$(".insertion").html(data)
});
return false;
});
$(".test").click(function () {
alert("no");
});
And i am sorry if this is long.. Thank you people

Since the element is being generated dynamically, you need to use event delegation.
$(document).on("click",".test", function () {
console.log("no");
});
Reference Document: https://learn.jquery.com/events/event-delegation/
Hope this will help you.

use this construction for dynamicaly created objects: $(document).on("click", "elementSelector", function(){ /* function body*/})

Create delegated event binding using on like this
$(document).on("click",".test",function(){ ..... });
Note : Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

The jQuery method you're using assumes that the element is already within the DOM (already exists on the page) when your Javascript runs. Because you're adding HTML to the page after your script has run, your use of $(".test") will not catch any HTML added later.
You have two options:
1. Query your HTML only once the new HTML has been inserted
Include your $() query in the same callback where you're inserting your HTML, like this:
$.post("getId.php", {id:id}, function(data) {
$(".insertion").html(data);
// this will work now
$(".test").on("click", function() { ... });
});
Or, maybe better, scope your jQuery query to only look within the newly inserted HTML:
$.post("getId.php", {id:id}, function(data) {
var $insertion = $(".insertion");
$insertion.html(data);
// only find .test within the new HTML
$insertion.find(".test").on("click", function() { ... });
});
2. Change your jQuery syntax to bind an event listener to the body
As #diavolic points out, jQuery provides a second syntax for .on, where you bind your listener to an element but provide a selector as a second argument. The callback will only fire if the event is triggered on elements matching this selector. By binding the listener to the body tag (which is always present in the DOM) and providing .test as the selector, the .test element doesn't need to exist in the DOM when the javascript runs.
$(document.body).on("click", ".test", function() {
// do something
});
$.post("getId.php", {id:id}, function(data) {
$(".insertion").html(data);
});
Either option should work. The first option is a better option if you want to listen for clicks only within a specific element. The second is more reliable if you aren't sure when or where the new HTML will be inserted.
More information about event delegation can be found here: http://api.jquery.com/on/#direct-and-delegated-events

//for <input type="button" class="test" value="test">
jQuery(document).ready(function() {
jQuery('.test').on( 'click', function () {
alert('no');
});
});

Related

how to Get the value of input type hidden in modal using ajax

Good day..
i have modal and inside the modal i have div class
<div id="user-details-content" class="modal-body">
...
</div>
i supply the content inside that modal using ajax.
this is the supplied content:
<div id="hidden" class="hidden">
<input type="hidden" name="id" class="id" id="id" value="1">
<input type="hidden" value="email#email.com" class="email">
</div>
Now i try to get that input type="hidden" using this ajax
var id = $(this).parents('#user-details-content').find('.id').val();
but it returns undefined in my console.log
any suggestions ? on how to get that input type="hidden" and the value ?
EDIT - This is my ajax function
function inquiryId(){
var id = $(this).parents('#user-details-content').find('.id').val();
console.log(id);
$.ajax({
url: 'php_file.php',
type: 'POST',
data: { id: id,
},
dataType: 'json',
success: function(result){
console.log(result);
}
});
}
the problem may occurs because you loaded the html after the DOM loaded.
i guess you have kind of event listener right ?
A workaround could be doing something like :
$(document).on('some_event', '#your_css_selector', function(e){
// do your stuff here
});
Just want to get the input type=hidden value?
JQuery can get the value no matter it's hidden or show.
$('#id').val();
$('.email').val();
this is ok.
From the line of code:
var id = $(this).parents('#user-details-content').find('.id').val();
If you know the exact id and the class attributes of the input[type="hidden"], may I suggest using $("#id").val() and $(".email").val(). Below is a snippet to demonstrate my suggestion, hope it helps.
$(function(){
$("button").click(function(event) {
buttonSubmit_OnClick();
});
});
function buttonSubmit_OnClick() {
var message;
message = "Hello " + $("#id").val() + "! ";
message += $(".email").val();
$("p").html($("p").html() + "<br>" + message);
/* $.ajax() code-block goes here */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hidden" class="hidden">
<input type="hidden" name="id" class="id" id="id" value="1">
<input type="hidden" value="email#email.com" class="email">
<button>Click me!</button><!-- this is for demo! -->
</div>
<p></p><!-- this is for demo! -->
As a side note:
For better client-side code optimization:
$(this) is powerful, but also a wild-card. jQuery is always updating the this, so, this may not always be what you expect it to be. Best be used only when you really have to, when you do, store its reference in a variable. Remember, with great power, comes great responsibility.
ID-Based Selectors are much faster because they handled by using document.getElementById() which is native to the browser instead of going through jQuery's sizzle selection engine.
Being specific if possible. Avoid universal selectors such as .children() or .parents().
Here is a more eloquent read on optimizing jQuery selectors.

Posting and getting from php via jQuery

Update, I changed jQuery to this and it still doesn't work:
$("#click").click(function(){
$.post("accountcreation.php",function(response){ userCreation:"userCreation"
$("#justtesting").html(response);
})
})
Nothing is happening. I had the HTML and PHP working, but then I wanted to add live updating and began this jQuery code. What's wrong with it?
Thanks.
jQuery
$("#click").click(function(){
$.post("accountcreation.php", { userCreation:"userCreation"
})
$.get("accountcreation.php", function(data,status){
$("#justtesting").html(data);
})
})
HTML
Username: <input required type="text" name="userCreation"
onchange="userValidate();"
onkeypress="this.onchange();"
onpaste="this.onchange();"
oninput="this.onchange();">
<span id="userRegexJavascriptResponse"></span>
<br>
<input type="button" value="Submit" id="click">
<div id="justtesting"></div>
PHP (Part)
class accountcreation {
private $options;
function __construct($con, $ipCreation) {
$this->passwordCreation = $_POST['passwordCreation'];
$this->userCreation = $_POST['userCreation'];
$this->ipCreation = $ipCreation;
$this->emailCreation = $_POST['emailCreation'];
$this->con = $con;
}
Use this code instead. Your PHP script is expecting data via post, and you can get a response in that same .post() call.
$("#click").click(function(){
$.post("accountcreation.php", { userCreation:"userCreation"}, function(data){
$("#justtesting").html(data);
});
});
NOTE: I would strongly advise against inline javascript; it's so difficult to maintain and is just not good practice. Event listeners should be attached as above ... that's the way to go.
Your HTML should be:
Username: <input required type="text" name="userCreation">
<span id="userRegexJavascriptResponse"></span><br>
<input type="button" value="Submit" id="click">
<div id="justtesting"></div>
And, you do need to include jQuery core right before the JavaScript code:
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
If you open your dev tools and run the code snippet below, you should see a post call being made with the data you supply. This means that it should be able to work on your server or else you should be able to see any errors in the console of the dev tools.
$("#click").click(function(){
$.post("accountcreation.php", { userCreation:"userCreation"}, function(data){
$("#justtesting").html(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Username: <input required type="text" name="userCreation">
<span id="userRegexJavascriptResponse"></span><br>
<input type="button" value="Submit" id="click">
<div id="justtesting"></div>

Doesn't get value with jQuery

<form method="POST">
<div id="showme">Show me <?php echo $_POST['name']?></div>
Send the value<input type="radio" name="name" value="ja"/>
<input type="submit" id="submit" name="submit" value="BEREKENEN! ">
</form>
<script>
$(document).ready(function () {
$('#showme').hide();
$('#submit').click(function(e) {
e.preventDefault();
$('#showme').fadeIn(5000);
});
});
</script>
This code won't send the value of the radiobutton to the showme div.
I can't receive the $_POST['name'] when I use hide() and fadeIn() between the <script> tags.
Whenever I don't use jQuery it sends the data - when using it , it won't let me send the value.
How do I fix this problem, this is just an example of 1 radio button. I have a list of 6 radiobuttons that need to be sent to PHP section in the same file, I don't want to make another file for this.
This code will FadeIn the requested div, it shows me Show me but it won't show the value where I ask for with the line <?php echo $_POST['name']?>
PHP is parsed on the server. <?php echo $_POST['name']?> has already been evaluated and echod to the page long before any of the submission stuff happens. What you need is to use AJAX.
You can replace the submit button with just a regular button, remove the <form> element entirely even.
jQuery:
$('#submit').on('click', function(evt) {
var e = evt || window.event;
e.preventDefault();
$.post('page.php', { name: $('input[name="name"]').val() }, function ( data ) {
$('#showme').append(data).fadeIn(5000);
});
return false;
});
(if you do what I did below turning submit into button, you dont need the e.preventDefault())
PHP:
if(isset($_POST['name'])) {
echo $_POST['name'];
return;
}
HTML:
<div id="showme">Show me </div>
<label for="name">Send the value</label><input type="radio" name="name" value="ja"/>
<input type="button" id="submit" name="submit" value="BEREKENEN!">
I'm not so sure you can get a non-BOOLEAN value from a radio button with PHP though. You're probably better off using <input type="hidden" value="ja" /> or maybe type="text".

How to rebind jQuery script after it has been called used once?

I have three things going on:
I am sending information with this form.
<form method="post" id="myForm" action="includes/functions.php">
<input type="hidden" name="group_id" value="$group_id" />
<input type="hidden" name="submit_join"/>
<button class="request" id="sub" name="submit_join">Join</button>
</form>
This jQuery script runs a PHP script.
$("#sub").click(function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(){ $("#sub").html("Applied").fadeIn().addClass("applied").removeClass("request");
});
});
$("#myForm").submit(function() {
return false;
});
This is what the PHP script does. (Not a prepared statement)
if (isset($_POST['submit_join'])) {
//User ID
$user_id = $_SESSION['user_id'];
$group_id = $_POST['group_id'];
$sql="INSERT INTO group_assoc (user_id, group_id, permission, dateTime) VALUES ('$user_id', '$group_id', 0, now())";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($connection));
}
}
-It works just fine when someone clicks the button once.
It triggers the jQuery script
The jQuery script triggers the PHP script
The PHP does its job
The jQuery removes the class "request" and puts a class "applied"
Problem:
When the same user clicks another button (meaning a duplicate of the button that they just clicked), the page ignores the jQuery script and does what it would normally do, refresh the page. This is the unwanted process.
Why several forms and therefore why several buttons? I am doing a PHP while loop for every group in the website and every form contains a button (Join) that allows you to join the group and change the value on the database using the jQuery script above.
Question: How can I rebind the jQuery script so that when another button (<button class="request" id="sub" name="submit_join">Join</button>) is clicked, it will not ignore the jQuery script?
The problem seems to be that you are working with duplicate IDs, try with classes instead of id
<form method="post" class="myForm" action="includes/functions.php">
<input type="hidden" name="group_id" value="$group_id" />
<input type="hidden" name="submit_join" />
<button class="request" class="sub" name="submit_join">Join</button>
</form>
and
$(document).on('submit', '.myForm', function () {
return false;
})
$(document).on('submit', '.sub', function () {
var $form = $(this).closest('form');
$.post($form.attr("action"),
$form.serializeArray(), function () {
$("#sub").html("Applied").fadeIn().addClass("applied").removeClass("request");
});
})
Its always a good idea to pass in the event to the event handler, and do a event.preventDefault() to avoid browser's default behaviour on the elements.
$("#myForm").submit(function(event) {
event.preventDefault();
});
As for the multiple forms, you can use one handler to handle form submits. $('#sub') will bind to only the first button on the page, use a class to attach to multiple buttons of the same type which will still be inefficient. Here is a sample :
$('.subbtn').click(function(e){
var $form = $(this).parents('form'),
subUrl = $form.attr('action');
e.preventDefault();
$.post(...) ;
})
This handler should take care of your requirement. You can however use a single handler attached to the common wrapper of the forms (worst case 'body') to improve efficiency.
Like what jagzviruz said, it's always best to use the submit event's event handler to prevent the page refresh. And also, make sure you don't have any duplicate element IDs.
My approach would be something like this: (untested)
HTML
<form method="post" class="myForm" action="includes/functions.php">
<input type="hidden" name="group_id" value="$group_id" />
<input type="hidden" name="submit_join"/>
<button class="request" class="submit" name="submit_join">Join</button>
JS
$(".myForm").each(function() {
var $form = $(this),
action = $form.attr('action'),
$submit = $form.find('.submit');
$form.submit(function(event) {
event.preventDefault();
return false;
});
$submit.click(function(event) {
event.preventDefault();
$.post(...);
});
});
It's pretty much the same solution as what jagzviruz proposed, but I prefer to do things like this inside an .each() for clarity.

Jquery .submit wont intercept form submission

I have php code that echos a form that was inserted into my html by another jquery code. This all works fine. I am trying to submit this form with ajax.
echo '<form id="comment_form" action="commentvalidation.php?PhotoID='.$_GET['PhotoID'].'" method="POST">';
echo '<label>Comment: </label>';
echo '<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>';
echo '<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >';
echo '</form>';
The form works fine when submitted traditionally. The problem is I cant get it to be be submitted with ajax. The .submit just wont prevent the default action.
<script>
$(function(){
$('#comment_form').submit(function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
</script>
You're probably binding the submit event handler before the form is in your page. Use event delegation instead of direct binding, for example
$(document.body).on('submit', '#comment_form', function(e) {
e.preventDefault();
alert('We are in');
// and the rest, no need for return false
});
As an addendum, try not to echo out great chunks of HTML from PHP. It's much more readable and you're less likely to run into problems with quotes and concatenation if you just switch to the PHP context when required, eg
// break out of the PHP context
?>
<form id="comment_form" action="commentvalidation.php?PhotoID=<?= htmlspecialchars($_GET['PhotoID']) ?>" method="POST">
<label>Comment: </label>
<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>
<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >
</form>
<?php
// and back to PHP
The problem seems to be from the fact that form that was inserted into my html by another jquery code. From what I understood from this, the form was dynamically created after the page was loaded.
In that case when the submit handler registration code was executed the element was not existing in the dom structure - means the handler was never registered to the form.
Try using a delegated event handler to solve this
$(function(){
$(document).on('submit', '#comment_form', function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
Demo: Problem
Demo: Solution

Categories