I was trying to call jQuery.submit() function after ajax response. Where ajax response contains a form. But it couldn't call jQuery.submit() function when i submit the form without refresh.
I prepend the form with the existing code after successfull ajax response
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
},
error: function(data) {}
So after adding the form to the existing code. When i tried to submit the form it's got refresh instead of calling the function. How to make jQuery.submit() workable from ajax response?
$(".replyName").submit(function(event) {
alert(event.currentTarget[0].value);
});
You should place the submit event after you prepend the form. Because event's are only binded to the elements after the DOM is loaded.
And because the prepend the form dynamically, jQuery doesn't know which element it has to submit, because it didn't exist at the time it binded the event.
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$( ".replyName").submit(function( event ) {
alert(event.currentTarget[0].value);
event.preventDefault();
});
},
error: function(data) {}
Since the form is not created in the document, you cant listen to submit event, unless you put the event listener after you prepend form into the dom
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$(".replyName").submit(function(event) {
alert(event.currentTarget[0].value);
});
},
error: function(data) {}
You can also handle the event from body dom
$('body').on('submit', '.replyName', function(e){
// code here
});
There are two thing you can do:
Either you can rebind the click function like this:
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$('button').bind('click', function (event) {
event.preventDefault();
alert(event.currentTarget[0].value);
});
},
error: function(data) {}
or you can try this
$('button').on('click', function(e){
// code here
});
Related
I'm submitting a form using jQuery Ajax.
The data is submitted successfully but there's a little problem. When I add the commented statements in this code, the success: function(){} doesn't run (location is not changed).
Q. 1 When I remove those statements, it runs. I don't understand this logic. When does it actually executes and how does checking for xy affects this?
Here's my Ajax code:
$(document).ready(function(){
$("#button").click(function(){
**//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result){
$(location).attr('href', 'login2.php');
},
error: function(){
alert(error);
}
});
// }
});
});
Here's concerned input tag:
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />
......
Q.2 When I write event.preventDefault(); to stop the default action of submit button, the required atrributes of input fields don't work. Why is it so? Can it be solved?
To Question 2:
If you call preventDefault for the event of the click on the submit button, then the default behaviour (initiating the submit) is prevented, so the input fields are not checked.
You have to listen on the submit event of the form instead and prevent the default behaviour of this, because the submit event is send after the input elements are checked and before the form is submitted.
$(document).ready(function() {
$("#signupform").on('submit', function(e) {
e.preventDefault();
//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result) {
$(location).attr('href', 'login2.php');
},
error: function() {
alert(error);
}
});
// }
});
});
When you use jquery ajax there is two types of result:
400 - OK status which be capture by the success function
402 or 500 are internal errors and those will be capture by the error function.
Now, in your error function youre trying to print an error variable that does not exist.
Also, when you use preventDefault you have pass variable that handles de event too cancel.
<form target="_blank" method="POST" action="somePage.php" id="myForm">
<input type="hidden" name="someName" value="toBeAssignedLater"/>
<button type="submit">Proceed</button>
</form>
At the beginning, the value of someName is not determined yet, I want to execute an Ajax to get and assign the value to it before the form is actually submitted.
I tried:
$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
});
});
But the form would have already submitted before the Ajax is finished, how can I ensure the form would be submitted after the Ajax is finished.
I want to keep the form submit event initiated by the user instead of code, such as $("#myForm").trigger('submit');, since I don't want the new window tab to be blocked by browsers.
$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
// submit form without triggering jquery handler
$this[0].submit();
});
// cancel the current submission
return false;
});
Why don't you ajax the value at page load and than submit the data?
$(function(){
someAjaxFunction(function (data) {
$('input[name="someName"]').val(data.value);
});
$("#myForm button").on('click',function(){
$(this).submit();
});
});
or place the ajax call on click event and submit whan the values is updated:
$(function(){
$("#myForm button").on('click',function(e){
e.preventDefault();
$.ajax({
url:url, //other params
success:function(data){
//thing to do before submit
$('input[name="someName"]').val(data.value);
$(this).submit();
}
});
});
});
So I'm trying to get some data from the server with php but as soon as it's loaded onto the page it seems to reload the page and make it disappear again.
My html:
<form id="searchForm">
<input name="searchValue" type="text" id="search">
<input type="submit" name="Submit" value="Zoek op klant" onclick="getKlanten()">
</form>
<div id="klanten">
</div>
My js:
function getKlanten(){
var value = $("#search").val();
$.ajax({
url:'includes/getKlanten.php',
async: false,
type: 'POST',
data: {'searchValue':value},
success: function(data, textStatus, jqXHR)
{
$('#klanten').html(data);
},
error: function () {
$('#klanten').html('Bummer: there was an error!');
}
});
}
Can anyone help? It gets put into the div but then instantly disappears again.
Firstly, avoid inline click handlers. The page reloads because by default a form submits the form content to the url specified in action attribute.
Instead attach an event to the form and use preventDefault to avoid the page from refreshing. Do something like this
$('#searchForm').on('submit', function(e){
e.preventDefault();
// your ajax request.
});
Or attach an event to input button like this
$('input[type="submit"]').on('click', function(e){
e.preventDefault();
// your ajax request
});
Read more about preventDefault here
I have the following button and when clicked it's invoking a function,
Is there a way to know in the controller that this button was clicked ?
$("#RemoveFile").on("click", RemoveFile);
<button class="btn" style="height: 25px" type="button" id="RemoveFile"><p >Remove File</p></button>
As Edurado Says this the implementation which you asked to him
First set hidden field in html page (razor view/ aspx page)
<input type="hidden" id="StakeholderId" name="stakeholderId" />
Then add script like below
$( "#buttonID" ).click(function() {
$( "StakeholderId" ).val(true);
});
And get the value and posting the value to controller like below
var hidden= $('StakeholderId').val();
$.ajax({
type: "post",
url: "Controller/Method",
data: {
hiddenField1: hidden,
hiddenField2: "hiddenValue2",
},
success: function() {
alert("yay")
},
error: function(e) {
console.log(e);
}
});
Hope this helps....
When you click in the button, add an onclick event to this very button and save the clicked status in a hidden field. Then, whenever you send data to the controller, send this hidden field value, stating whether the button was clicked.
UPDATED:
Here is the HTML
<input id="hdnRemoveClicked" type="hidden" value="false" />
And here is the javascript which adds the click event in the button with ID="RemoveFile", and set the hidden field value as true, to show it is clicked.
$( "#RemoveFile" ).click(function() {
$( "hdnRemoveClicked" ).val(true);
// do other things, if needed
});
The only way I know of to so this in MVC is to make an Ajax call to the server via an anonymous function in the JQuery component. Example:
$("#RemoveFile").on("click", "RemoveFile", function () {
// tell server
var jqxhr1 = $.ajax({ type: 'POST', url: "/myControllerUrl",
data: { buttonID: "RemoveFile" } });
$.when(jqxhr1).done(function (response, textStatus, jqXHR) {
if (textStatus != "success") {
alert("Error, please try later");
return false;
}
// update the user interface
});
});
Make an ajax call to a method in Controller where a session keeps track if button was clicked.
The following code is intended to do a purely ajax POST request, instead it seems to do the POST via ajax and then the browser navigates to the response.
The HTML...
<div id="bin">
<form class="add" method="post" action="/bin/add/">
<p>I'm interested! Save for later.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Save">
</form>
<form style="display:none;" class="remove" method="post" action="/bin/remove/">
<p>I changed my mind--I'm not interested.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Unsave">
</form>
</div>
The jQuery...
$('#bin form').submit(function() {
$.post($(this).attr('action'),{
success: function(data) { $(this).hide().siblings('form').show() },
data: $(this).serialize()
});
return false;
})
As far as I understand it, the return false; line should mean that no matter what, any calls to the submit function or clicks on the 'Submit' button or the hitting of enter means that my function will execute and the browser will not navigate to /bin/add or /bin/remove. But for some reason, the browser is changing pages.
Any idea what I'm doing wrong here? Thanks.
It could be your JavaScript is failing, so the default behaviour is being executed.
Try to examine the XHR in a tool like Firebug.
Also, you could try event.preventDefault() (where the first argument to your event callback is event).
my bet it's because of the $(this), try it this way....
$('#bin form').submit(function() {
var $this = $(this);
$.post($this.attr('action'), {
success: function(data) {
$this.hide().siblings('form').show()
},
data: $this.serialize()
});
return false;
});
demo no error
demo with the error
Use event.preventDefault() to prevent the default action of the event. One benefit is that you can place this before the Ajax request, so that if it fails, you will still have prevented form submission.
Your code is failing because the value of this in your success callback is the global window object. Your attempt to hide it fails. You probably want this to refer to the form, like this:
$('#bin form').submit(function(ev) {
var _this = this;
ev.preventDefault();
$.post($(this).attr('action'), {
success: function() {
$(_this).hide().siblings('form').show();
},
data: $(this).serialize()
});
})
See a working example.
Is the $(...).submit(...) inside a $(document).ready(function(){ code here }); ?
should be like:
$(document).ready(function() {
$('#bin form').submit(function() {
$.post($(this).attr('action'), {
success: function(data) { $(this).hide().siblings('form').show(); },
data: $(this).serialize()
});
return false;
});
});