I created custom form for fast reply (.append), now I want to use ajax for submit reply without reloading, I tried .on('submit', function(e)... which doesn't work (tried event delegation also). Now I tried .on('click', function(e)... and this works - don't know why.
$("#newpost").on('click', '.send', function(event) {
event.preventDefault();
});
This doesn't work:
$("#newpost").on('submit', '.send', function(event) {
event.preventDefault();
});
Appended form:
<form id="newpost" method="post" action="/forum/addpost/"+ id +"/"+ rek +" name="newpost">
<div class="editor" align="left">
<textarea name="post" cols="50" rows="5"></textarea>
<div class="submit" align="right">
<input class="send" value="." title="Send" type="submit">
</div>
</div>
</form>
So why .on('submit'..) doesn't work even if I use event delegation?
Thank you
This is not working because you have conflicting name to textarea(name="post") with the form properties.
As from jquery documentation:
jquery submit
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.
If you append the whole form dynamically then you'll have to attach the submit listener to something that already exists when the page loads. Something like this:
$('body').on('submit', '#newpost', function(event) {
event.preventDefault();
});
EDIT:
I might have misread the question. The part you said doesn't work cant work because you don't submit a ".click" button, but the form that your ".click" button is in.
The right form is
$( "#newpost" ).submit(function( event ) {
event.preventDefault();
});
Later edit:
I understood now what you want.Try a new approach.Presuming that id is 23 and rek is value "add" you have the following:
HTML
<div class="editor" align="left">
<textarea name="post" cols="50" rows="5" id="post"></textarea>
<div class="submit" align="right">
<input class="send" value="." title="Send" type="button" id="23" data-rek="add">
</div>
</div>
JS ( can be used in external file also):
//get the answer based on id-s and classes
$("body").on("click", ".send", function() {
//get what is at attribute id of the clicked link
var ID=$(this).attr("id");
//get the text from the form with id "fasttext"
var thetext = $("#post").val();
//take the value of rek ( don't know what means :) )
var therek = $(this).attr("data-rek");
//create the string that will be posted
var theString = 'post=' + thetext;
//post the form using ajax and without reloading the page
$.ajax(
{
type: "POST",
url: "/forum/addpost/"+ id +"/"+ therek,
data: theString,
cache: false,
success: function(html)
{
//do what you want to do as success - html is the returning response
//you can also make this div disappear or display a success message
}
});
});
});
May be problem is here
<div class="submit" align="right">
<input class="send" value="." title="Send" type="submit">
try to remove class="submit" from div tag
<div align="right">
<input class="send" value="." title="Send" type="submit">
Related
Why my page reloads even I used ajax to it and it also disappears my input text after clicking the submit button. I already used show to solve it but it doesn't work.
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="text" name="name" id="name">
<span id="namenotif" style="color:red;"> <span>
<br>
<input type="text" name="price" id="price">
<span id="pricenotif" style="color:red;"> <span>
<br>
<input type="submit" name="submit" id="save"><br>
</form>
<script>
$(document).ready(function() {
$(document).on("click","#save",function(){
var name = $("#name").val();
var price = $("#price").val();
if(name==""){
$("#namenotif").html("Enter a name");
$("#name").show("fast");
$("#save").show("fast");
}
else if(price==""){
$("#pricenotif").html("Enter a price");
$("#price").show("fast");
$("#save").show("fast");
}else{
$.ajax({
url:"addproduct.php",
type:"POST",
data:{name:name,price:price},
success:function(data){
alert("Successful");
}
});
}
});
});
</script>
add return false to end of function, that handle click event
Two solutions:
Change the button type='submit' to type='button'
or ( and preferably )
Change the event listener to listen for the form's onSumbit event then call event.preventDefault or in jQuery, I think you just do return false in the callback.
The form is being submitted I think, because it is the default behavior of submit button to submit the form, no matter if you used ajax or not. so you can prevent the default behavior by simple adding a code in jquery. Modify the code like this:
$(document).on("click","#save",function(e){
e.preventDefault();
...............
Rest of the codes can remain same. so only prevent the default action, it should work.
Its because of type="submit"
Use
<input type="button" name="submit" id="save"><br>
Or
<a href="javascript:void(0) id="save">
or
jquery's preventDefault();
There's an email subscription form in a web page, When someone enters his email and clicks on submit button, We don't want this page to be redirected to form action url, We just want it's submit button text value to be converted to another text, something like "Thank You!". How is it possible? Should I go through ajax? or javascript?
Here's the form:
<form class="ml-block-form" action="//app.mailerlite.com/webforms/submit/myownID" data-code="myownID" method="POST" target="_blank">
<div class="form-group ml-field-email ml-validate-required ml-validate-email">
<input class="newsletter-email" type="email" name="fields[email]" placeholder="Email*"/>
</div>
<input type="hidden" name="ml-submit" value="1" />
<p>
<input class="newsletter-submit" type="submit" value="Get Updates!"/>
</p>
For starters remove target="_blank" from your form tag.
Then, within your jQuery, do something along the lines of this:
$(".ml-block-form").submit(function(){
var vals = $(this).serialize();
$.ajax({
url: "postpage.php",
method: "POST",
data: vals,
success: function(data) {
$("#formsubmit").val("Thank you!");
}
});
return false; // prevent from submit
});
I've altered your HTML as well, as it was originally very messy. You can of course add the other elements back if you need:
<form class="ml-block-form" action="" data-code="myownID" method="post">
<input id="mainval" type="email" name="fields[email]" placeholder="Email*">
<input id="hiddenval" name="ml-submit" value="1" />
<input id="formsubmit" type="submit" value="Get Updates!"/>
</form>
You can simply remove target="blank" because blank value opens the linked document in a new window.
Instead of
<input class="newsletter-submit" type="submit" value="Get Updates!"/>
use
<button id="newsletter-submit" value="Get Updates!"/>
(note that I changed class for id)
And then use jQuery to handle the click on the button:
$("#newsletter-submit").click(function () {
$(this).prop("value", "Thank You!");
// do something else with the input values e.g. send them via ajax to a server script
});
I have a lot of buttons, each opens its form . How do I get the input value of form opened at the moment, and post it on my server, like post("/addOrders", valueOfinputs)?
https://jsfiddle.net/ave6uvez/21/
<div class="rows">
<div class="row">
<button class="open">Buy</button>
<form id="myform" action="/index" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="namee" name ="name" >
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="phone" name = "phone" >
</div>
<button class="ave" >Close</button>
<INPUT type="submit" id = "submit" class = "close" value="Submit">
<!---- <button id="submit" class="close"></button>-->
</form>
</div>
</div>
try this,
$("#submit").click(function(e){
$.post("/addOrders",$("#myForm").serialize());
return null;
})
.serialize() will put all form elements data into the request
Also you need to give different id for different Forms submit button and you have to do the above code for each submit button
Hope this works for you.
This is a simple reference:
// this is the id of the forms, set the form ids accordingly.
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
I would like to create a form with multiple submit link buttons. I know it can be done by using and specifying the name of <button> or <input type="button"> something like this:
In HTML:
<form action="" method="get">
Other form elements here...
<button type="submit" name="activated">Activated</button>
<button type="submit" name="pending">Pending</button>
<button type="submit" name="suspended">Suspended</button>
</form>
In PHP:
<?php
if(isset($_GET["activated"])) {
Activated codes here...
}
elseif(isset($_GET["pending"])) {
Pending codes here...
}
elseif(isset($_GET["suspended"])) {
Suspended codes here...
}
?>
I want the submit buttons to be done by using link, not <button> or <input type="submit"> something like this:
Activated
Pending
Suspended
I heard that it can be done by using JavaScript or JQuery but I don't know how, anyone knows?
Update: What I want to happen is when I clicked the "Activated" link for example, I want only to process the logic under isset($_GET["activated"]).
The reason behind:
The reason why I want to have a submit link buttons instead of normal submit button tags is that, I want to use this bootstrap dropdown button style to change the status of user(s) on table:
and it is based on links, so that's why.
PS: Sorry for bad English, not my native language.
You could use data attributes on your anchors, then load that attribute into a hidden field to check in your PHP code.
<form action="" method="post">
Activated
Pending
Suspended
<input type="hidden" id="actionName" name="actionName" value="" />
</form>
$('.anchor-btn').click(function(e) {
e.preventDefault();
$('#actionName').val($(this).data('name'));
$('form').submit();
});
<?php
if($_POST['actionName'] == "activated") {
Activated code goes here
}
...etc.
?>
Yes you can submit the form using jquery just add a class to your buttons and add a click handler
$(document).ready(function() {
$( ".buttons_class" ).click(function() {
$( "#target_form" ).submit();
});
});
so your buttons will look like this
<button type="button" name="activated" class="buttons_class">Activated</button>
<button type="button" name="pending" class="buttons_class">Pending</button>
<button type="button" name="suspended" class="buttons_class">Suspended</button>
if using anchors
Activated
Pending
Suspended
And in javascript
$(document).ready(function() {
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
$("#target_form").attr("action", "yourphpfile.php?"+$(this).text()+"=true"); //This will send the text inside the anchor as a GET param.
$( "#target_form" ).submit();
});
});
However if I were you I would consider using POST instead of GET for this. and do something like this
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
var paramName = $(this).text(); //get text inside anchor
$( "#target_form" ).submit(function(eventObj) {
$('<input />').attr('type', 'hidden')
.attr('name', paramName);
.attr('value', "something")
.appendTo('#form');
return true;
}); //Add hidden field
});
Change your isset to $_POST instead of $_GET, it will then use the name attributes.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['test1'])) {
###
} else if ($_POST['test2']) {
###
}
}
<form method="post">
<input name="test1" type="submit" value="TEST 1" />
<input name="test2" type="submit" value="TEST 2" />
</form>
I am using jQuery to send a request to my server and then render the results. However, now I want to use a button, so that the request would only be sent after clicking on the send button, not like my previous code where I used an "onkeyup" which is uncontrollable; because I want to send my request after finishing typing my request and not before.
<script>
function Search(query_text)
{
$.get( "http://localhost:9000?query="+query_text, function( data ) {
$(\"#div2\").empty()
..............
$(\"#div2\").append("</table>")
}, "json")
.fail(function() {
$("#rep")
.append('<br/><p style="color:red">Oops! Error with XMLHttpRequest</p>')
});
;
}
</script>
This is the input that calls the jQuery function:
<input id="queryText" type="text" onkeyup="Search($(this).val())" /><br>
I've tried to add a simple button and then call the jQuery function like this, but it didn't work because the page reloads and I don't get the results I need:
<form class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="queryText" placeholder="Your text">
</div>
<button type="submit" class="btn btn-primary" onclick="Search($('#queryText').val())">Find courses</button>
</form>
I don't know if there is a way to keep using GET requests instead of using a form and sending that time a POST request.
Thank you in advance!
Correct the id you are using its queryTexte and not queryText and instead of double quotes use single quotes in jQuery selector as shown :-
<button type="button" class="btn btn-primary" onclick="Search($('#queryTexte').val())">Search</button>
Instead of using type=submit button make it type=button as shown above.
I would do something like this to keep JS and HTML separated and avoid quote issues:
$("button").on("click", function(){
Search($("#queryTexte").val());
});
And if your script is loaded before the DOM element, wrap it like this to wait for the DOM to be ready:
$(function){
$("button").on("click", function(){
Search($("#queryTexte").val());
});
});
HTML:
<input id="queryTexte" type="text" /><br>
jQuery:
<script>
jQuery(document).ready(function($){
$('.btn-primary').click(function(){
var query_text = $('#queryTexte').val();
$.get( "http://localhost:9000?query="+query_text, function( data ) {
$('#div2').empty();
..............
$('#div2').append("</table>");
}, "json")
.fail(function() {
$("#rep")
.append('<br/><p style="color:red">Oops! Error with XMLHttpRequest</p>')
});
});
});
</script>