[jQuery]Page refreshes after appending html with .html() - javascript

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

Related

jQuery .submit() not working after ajax response

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
});

How to stop duplicate data in jquery mobile after navigationg between pages

I am creating a chat application in jQuery Mobile.The problem is that when you navigate between pages and come back to the chat page when submitting data the data is resent according to the number of times one has navigated between other pages
When i perform a full page refresh data is sent only once as required.
I have tried adding data-ajax = false to the href of the link(button) but still it doesnt work?
The html code:
<form id="form_message_user" method="post"
action="#user_requestmoreinfo_page
">
<div data-inset="true">
<label for="requestmessage" class="ui-hidden-accessible"></label>
<textarea cols="40" rows="6" name="requestmessage"
id="text_user_message" placeholder="Type message to send "></textarea>
</div>
<input type="submit" value="submit" id="submitmessage" />
</form>
The form is on a page with
<div data-role="page" id="user_requestmoreinfo_page" data-theme="e">
The submission code:
$(document).on('pageshow', '#user_requestmoreinfo_page',function(e){
var id_from = localStorage.loggedin_id;
var id_to = localStorage.user_schoolls_id;
var message = $("#text_user_message").val();
$('#form_message_user').on('submit', function(e){
e.preventDefault();
if(message > 0 ){
// Send data to server through the Ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: '127.0.0.1/php/send.php',
data: {message:message,id_from:id_from,id_to:id_to},
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
console.log(result);
},
error: function (error) {
// This callback function will trigger on unsuccessful action
console.log(error);
}
});
} else {
alert('Please enter the message');
}
return false; // cancel original event to prevent form submitting
});
});
On success the console.log() displays the json data according to the number of page navigations before getting to the page(#user_requestmoreinfo_page);
Example:
If i had to navigate between other pages 3 times the console.log() will show output of 3 times
I can think of two reasons why you experience this behaviour.
1) Code multiplication. Bind the code to pagecreate, not pageshow, as the latter event is triggered every time the page is displayed, duplicating the submit code and causing multiple events.
2) Page duplication. This is a well-known bug in jQM that is described here. In short, the first page (and its form) is duplicated in DOM under certain circumstances. To fix it, describe the path to the HTML document with the attribute data-url, and place it within the page div. Example code:
<div data-role="page" data-url="mysite/path/index.html" id="user_requestmoreinfo_page">
Here is a rework of your code with added buttons for page navigation:
Example code:
$(document).on('pagecreate', '#user_requestmoreinfo_page', function(e) {
$('#form_message_user').on('submit', function(e) {
//Cancel default action (https://api.jquery.com/event.preventdefault/)
e.preventDefault();
//var id_from = localStorage.loggedin_id;
//var id_to = localStorage.user_schoolls_id;
var message = $("#text_user_message").val();
//Validate
if(message == "")
alert('Please enter the message');
// Send data to server through the Ajax call
// action is functionality we want to call and outputJSON is our data
alert("Thank you for your comment.");
$.ajax({
url: '127.0.0.1/php/send.php',
data: {
message: message,
id_from: id_from,
id_to: id_to
},
type: 'post',
async: 'true', //<- true is default
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function(result) {
console.log(result);
},
error: function(error) {
// This callback function will trigger on unsuccessful action
console.log(error);
}
});
return false; // cancel original event to prevent form submitting
});
});
<html>
<head>
<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" data-url="<mysite>/index.html" id="user_requestmoreinfo_page">
<div data-role="content">
<form id="form_message_user" data-ajax="false">
<label for="requestmessage">Message:</label>
<textarea data-inline="true" id="text_user_message" placeholder="Type message to send"></textarea>
<input type="submit" value="Submit" data-inline="true" />
</form>
Next page
</div>
</div>
<div data-role="page" id="second">
<div data-role="content">
<p>
Second page
</p>
First
Third
</div>
</div>
<div data-role="page" id="third">
<div data-role="content">
<p>
Third page
</p>
First
</div>
</div>
</body>
</html>
My guess is that you're binding the event handler to the #form_message_user element each time the #user_requestmoreinfo_page event is handled. I'd try adding
$('#form_message_user').off('submit');
directly before
$('#form_message_user').on('submit', function(e){
// function body continues
You could also try using .one:
$('#form_message_user').one('submit', function(e){
// function body continues
According to the docs, that should have the same affect as .off() followed by .on():
http://api.jquery.com/one/

When and when doesn't success: value executes in jQuery Ajax method? (Header location not changed)

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.

Javascript/JQuery: On form submit, don't reload full page (only a div), and still submit form data

I've got the following code that I use on my links. This prevents the page from reloading and loads the content from the href tag in a div.
$("a[rel='right']").click(function(e){
e.preventDefault();
pageurl = $(this).attr('href');
$.ajax({url:pageurl.replace('index.php', 'rightcolumn.php')+'&rel=right',success: function(data){
$('#WMS_NEW_right').fadeOut(500, function(){ $('#WMS_NEW_right').html(data).fadeIn(1000); });
}
});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
My Question:
I need the use the same concept behind this, except on form submit, it needs to not reload the page, but submit the form only inside a div #WMS_NEW_right. How can I do this? I don't need push state or anything, just need to be able to control that form with class="formrelright" to only reload a div and get the url from the form action. I will also need all data from the form method="POST" on the new page (inside div)
From my understanding, you want to use ajax to post a form without reloading the page during the form submission. So I would consider the following:
$('.formrelright').submit(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: 'POST',
data: $(this).serialize(),
success: function(data) {
// Whatever you want
}
});
});
Either use target and an IFrame, or JQuery to submit the form in the background. The latter is preferable if you want to use the contents of the response.
JQuery post()
Maybe try it like this:
HTML:
<!-- Notice there is no 'form' element -->
<div id="myform">
<input type="text" name="firstName"><br>
<input type="text" name="lastName"><br>
<button type="button" id="submit_myform">Submit</button>
</div>
<div id="resultArea"></div>
<!-- the biggest critique about this method might be that
yes, it is not very semantic. If you want to use a form,
just throw in an 'e.preventDefault()' in your jQuery -->
jQuery:
$('#submit_myform').on('click',function() {
var firstName = $('input[name="firstName"]').val(),
lastName = $('input[name="lastName"]').val();
$.ajax({
type: "POST",
url: 'form.php',
data: {
firstname: firstName,
lastname: lastName
},
//the success function is automatically passed the XHR response
success: function(data) {
$('#resultArea').html(data);
},
});
});

jQuery Submit Refreshing Page

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;
});
});

Categories

Resources