I have a problem with my page refreshing after ajax posts, I've tried like 6 differing variations and at one point I was getting the proper result but couldn't stop the page from refreshing and after searching the net and around on this site now none of it is working and it's still refreshing...
current code is:
$('#submit_btn').click(function() {
/*event.preventDefault();*/
var curPassword = $("input#curPassword").val();
var newPassword = $("input#newPassword").val();
var new2Password = $("input#new2Password").val();
/*var params = 'curPassword='+ curPassword + '&newPassword=' + newPassword + '&new2Password=' + new2Password; */
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
$.ajax({
type: "POST",
url: "testAjax.php",
data: params,
success: function(msg){
alert(msg);
}
});
return false;
});
the form is:
<form method="post" action="" name="confirmChange" class="confirmChange">
<label for="curPassword">Current Password:</label>
<input type="password" name="curPassword" id="curPassword" value="" />
<label for="newPassword">New Password:</label>
<input type="password" name="newPassword" id="newPassword" value="" />
<label for="new2Password">Confirm New Password:</label>
<input type="password" name="new2Password" id="new2Password" value="" />
<br />
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change" />
Appreciate any help in getting this to work =/
Update:
Took out the other non-directly-related code as it kinda cluttered the question. Also updated code to refelect latest revision.
I changed the ajax url to a simple textAjax.php with a simple echo hello world nothing else, where I'm still getting nothing.
Update 2
Tried changing javascript code to:
$('#submit_btn').click(function() {
alert('Button Clicked');
});
And I'm getting nothing... If that is the form below how is it possible the click function isn't working at all?
You don't need to use the type="submit" for your input. Just use type="button" and call the ajax function on the button's click event.
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change">
$('#submit_btn').click(function() {
(ajax code here)
});
preventDefault() would also work, but, in my opinion, why prevent an event from naturally occurring when you can just avoid using the submit button altogether?
Update: I just realised that using the submit would allow users to hit enter to trigger your actions, so perhaps there's also some merit in that. In any case, here's a similar question that contains elaborations into preventDefault().
Update 2: You need to fix your parameters in the ajax function. Use an array instead of trying to build a query string:
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
Encapsulate your AJAX call within the following code block
$('form.confirmChange').submit(function(event) {
event.preventDefault();
#Rest of your code goes in here
});
preventDefault() will prevent the default action of an event from triggering.
Try this
<script>
function refreshpage(){
(ajax code here)
return false;
}
</script>
<form onsubmit="return refreshpage();">
<input type = "submit" value="submit_btn">
</form>
I think I fixed it by using:
$('#submit_btn').live('click', (function() {
I at least started getting a response when clicking, but I'm not updating or getting any echo's back from the php file but hopefully that'll be easier to debug. :)
I had the same problem. Just like you, I had wrapped my <input> tags inside a <form> tag pair. Even though there was no <submit>, I found that when I clicked my button to trigger the Ajax call, it was refreshing the page - and actually submitting the form to the page.
I ended up removing the <form> tags and this behaviour stopped, but the Ajax still works as expected. I hope this helps anyone else that is experiencing this.
Use a loop to run the ajax call only once.
var i;
for(i=0;i<1;i++){
//ajax code here
}
So, then it will not call again and again..
Related
I spent quite a bit of time looking for this and maybe I'm not approaching this correctly, but I'm trying to .submit and .post after clicking a submit. In other instances I have been able to get the ajax submit to work properly without the refresh, but when I do it in this manner it just doesn't work. I'm curious to know why.
Form
<form id="search" action="process.php" method="post">
Name: <input id="search_text" type="text" name="name" />
<input type="submit" value="Submit" />
</form>
Ajax
$('#search').submit(function() {
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
$('#page_nav').html(data.html_page_nav);
$('#results').html(data.table_html);
},
"json"
);
return false;
});
This works and it will submit without reloading just fine
Below is where I have the problem.
On the php server side I am sending back html that I want to be able to submit, which the initial search will put into the original html page.
$html_page_nav = "
<ul>
";
for($i=1; $i <= get_query_pages(get_query_count($query), 50); $i++) {
$html_page_nav .= "
<li>
<form id='page_".$i."' action='process.php' method='post'>
<input type='hidden' name='action' value='change_page'/>
<input type='hidden' name='page' value='".$i."'/>
<input type='submit' value='".$i."'>
</form>
</li>
";
}
$html_page_nav .= "
</ul>
";
I try to do the same thing as above, but the submit does not work properly
$(document).ready(function() {
$('#page_1').submit(function() {
console.log("this will not display");
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
},
"json"
);
return false;
})
...other jquery
});
This submit will not work properly, the function() will not execute and it will submit like the regular submit and go to the url rather then execute without refreshing the entire page.
Any suggestions or approaches would be much appreciated.
Thanks in advance!
Delegate the submit action to execute on content which will be loaded in future. By default the normal event handlers attached to the content loaded on DOM but not the one which will gets loaded in future, say through Ajax. You can use jQuery "on" function to delegate the action on content which will load in future.
eg.
$('body').on('submit', '#page_1', function() {
// do it here
});
I had a similar problem using ajaxForm n all. I jus used $("#Form").validate();
for it and the page doesnt get refresh
I'm clearly doing something wrong here, but I can't figure out why the Ajax isn't firing and instead insists upon a page load. The newBatable() fires fine, I just can't seem to get the vote to respect the ajax call.
HTML - not sure how to put html in here as code :/ - I feel dumb.
<form class="form-horizontal" id="batable1" action="vote.php" method="GET">
<div id="success-vote-1"></div>
<input type="radio" name="batableResult" value=" include ()" /> include ()<br/>
<input type="radio" name="batableResult" value="require ()" />require ()<br/>
<input type="radio" name="batableResult" value="both of above" />both of above<br/>
<input type="radio" name="batableResult" value="None of above" />None of above<br/>
<button class="btn btn-primary" onClick="vote(1)">Vote</button>
<input type="hidden" name="batableId" id="batable-id" value="1"/>
</form>
JS - the console display everything I want, the php script processes everything nicely and functions perfectly, it is just it has to load the php in the browser so it's not using AJAX
/***************************************/
function newBatable() {
var batableData = $('#new-batable').serialize();
//console.log(batableData);
$.ajax({
url: "process.php",
data: batableData,
success: function(data){
$('#success-new-batable').html(data);
}
});
}
/***************************************/
function vote(poll_id) {
//console.log(poll_id)
var batableId = "#batable" + poll_id;
//console.log(batableId)
var pollData = $(batableId).serialize();
//console.log(pollData);
$.ajax({
url: "vote.php",
data: pollData,
success: function(data){
var batable_success_id = "#success-vote" + poll_id;
$(batable_success_id).html(data);
}
});
}
The submit button fires the JavaScript and then immediately submits the form.
If you are using onclick, then return false to stop that.
You would be better off using a more modern event binding technique though.
how about attaching a click event via jquery to the button?
$(".btn").on('click', function(e){
e.stopPropagation()
e.preventDefault();
vote(1);
});
this would usually be placed in document .ready jquery in an external file or somewhere near the bottom of your page inside script tags.
Does this help?
Since you're already using jQuery, as SubstanceD, you should use jQuery's on() method and stop the event propagation and prevent the default action (submitting the form).
I also noticed a possible bug in your code. It looks like there is a typo. You have
var batable_success_id = "#success-vote" + poll_id;
and <div id="success-vote-1"></div>. You have a dash after vote in the div's ID while you are concatenating batable_success_id into #success-vote1, for example. So even if the AJAX call is made, it probably won't update your HTML like you're expecting.
I'm having great issues making this contact form that can be seen on the below visual. What I want the contact form to do is display on submit a thank you message or a message of confirmation instead of redirecting to the contact.php file where there isn't any styles you can see this in action on the provided link.
I've found some information that I can do this with Jquery Ajax that I've also tried displayed below, but I still can't seem to get it to work on submit to show a message in the pop up.
Does anyone know an easier way to do this or maybe point me in the right direction as this is something that I've been trying to fix for god knows how long.
Thank you for any help
Visual:
http://madaxedesign.co.uk/dev/index.html
PHP & HTML:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form id="submit_message" class="hide_900" method="post" action="/contact.php" onsubmit="javascript: doSubmit();">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div class="submit">
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
Jquery:
function doSubmit(){
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
You can add return false; at the end of your doSubmit function or the following code to prevent the form to redirect the user to the action page.
var doSubmit = function (event) {
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
event.preventDefault();
}
$(function () {
$('#submit_message').submit(doSubmit);
});
Modified HTLM
<form id="submit_message">
...
</form>
What is this code doing ?
First, we are defining a function to submit the form data.
Notice the event argument in the function. The first variable in this function is all the form values serialized in a ajax-complient request string. The .ajax() function is sending all the datas to your server. Note that as you did not set the type argument in the .ajax() function, the data are going to be send using the GET HTTP method.
Finally, event.preventDefault() prevents the submit event to be triggered in the browser. When the browser detect a submit event, it will try to submit the form based on the action and the method parameters in the <form> html tag. Usually, this submission performs an user redirection to the action page. This event.preventDefault() will disable this redirection. Note that the event argument is going to be set automatically by jQuery.
Last part, the $(function() { ... }); part means "execute this part when the document is fully loaded." It ensures that the element with sumbit_message id exists before calling the .submit() method. This last method is an event binder. It means that when the submit event is fired on the submit_message form, the function doSubmit will be called.
I hope you have a better understanding of this script. This is a pretty basic one, but if you understand clearly the mechanics, it will help you do become a better jQuery programmer. :)
Fiddle Demo
1.<form onsubmit='confirm()'>
function confirm()
{
alert("Thank You");
}
2.in contact.php call the page that is displayed again
You need to prevent the default event of the form. To do this, add the e.preventDefault(); function to the top of your function in order to prevent this event from firing.
Also notice that we are passing the e parameter to your function. This represents the event that has been fired.
function doSubmit(e){
e.preventDefault();
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
}
Try this
change your form with
<form id="submit_message" class="hide_900" method="post">
and in script put it
$("#submit_message").submit(function(e){
e.preventDefault();
//call your ajax
});
Greetings from some noob trying to learn JQuery,
I am attempting to make it when you type something in a box below a div layer it reloads that layer upon submission of the form with a php get of the text box in the form. Expected behavior is it would reload that box, actual behavior is it don't do anything. Can someone help me out here.... Below is the code.
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
<input type="submit" name="submit" class="button" id="submit_btn" value="New City" />
</form>
<script>
/* attach a submit handler to the form */
$('form[name="changewx"]').submit(function(event) {
/* get some values from elements on the page: */
var $form = $( this ),
city = $('#city').val()
/* Send the data using post and put the results in a div */
$('#currentwxdiv').load('http://api.mesodiscussion.com/?location=' + city);
return false;
});
</script>
Its giving the Javascript Console Error Error....
"XMLHttpRequest cannot load http://api.mesodiscussion.com/?location=goodjob. Origin http://weatherofoss.com is not allowed by Access-Control-Allow-Origin."
You are using POST method? is impossible to post to an external url because with ajax, the url fails the "Same Origin POlice".
If you use GET method, is possible to do that.
Another solution is to make a proxy. A little script that recive the params and then... using CURL or another thing you have to post to the external URL... finally, you jquery have to do the post thing to the proxy:
For example:
$.ajax({
url: '/proxy.php?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});
I do it so:
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
</form>
<script>
$('#city').keyup(function() {
var city = $('#city').val()
$.ajax({
url: 'http://api.mesodiscussion.com/?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});
});
</script>
To help you out, i need to test this.
What's the url address of your html code working ?
http://api.mesodiscussion.com/?location= doesn't work... only list the directory content... maybe that's de problem?
Greatings.
My problem:
I have index.html:
<form action="toload.php" method="post">
Input: <input type="text" name="something" value="" /><br />
<input type="submit" value="Submit!" />
</form>
toload.php is something like:
<?php
echo "Your input was: " . $_POST["something"];
?>
The question is quite simple.
When I press the Submit! button, I would like to dynamically load the content toload.php in index.html without the need of a refresh.
Thanks in advance! please comment for any needed clarification.
EDIT, a more verbose explanation:
I'm not sure I'm being clear (or maybe I'm not understanding the answers do to my lack of technical skills) so I'll give it another go. (re-write)
I have an HTML for with a submit button that sends a variable through POST method.
This variable is used by a PHP file and after a certain process, it inserts and update a MySQL database and echoes out some other stuff.
This is working JUST FINE.
But now I want to improve it by avoiding the page "reload" (going to the .php).
I want the HTHL that comes as an output of my HTML file to be dynamically shown in my HTML page.
Is it more clear now?
something like this with jQuery!:
<form action="toload.php" method="post">
Input: <input type="text" id="something" name="something" value="" /><br />
<input type="submit" value="Submit!" onclick="submitme()" />
<div id="something2"></div>
</form>
and function to submit:
function submitme(){
var tosend=document.getElementById("something").value;
$.ajax({
type: 'POST',
url: 'toload.php',
data: 'something='+tosend,
success: function(msg){
if(msg){
document.getElementById("something2").innerHTML=msg;
}
else{
return;
}
}
});
}
You must use AJAX (XMLHttpRequest) for that - http://www.w3schools.com/XML/xml_http.asp.
(You've said simply - as long loading 100KB of jQuery is not simply IMHO, I suggested pure JavaScript solution)
In your case you can use $.post()DOCS. If you gave your form an id="myForm" then you could load the return data into the form's parent in the callback as follows:
$('#myForm').submit(function(e){
e.preventDefault();
$.post("toload.php", $("#myForm").serialize(), function(data) {
$(this).parent().html(data);
});
});