I've been having some trouble with an AJAX form today. I've tried lots of things, yet can't get it to work.
My jQuery should prevent the form to submit. It has to go through AJAX. Yet, it seems to ignore event.preventDefault(); and just submits the form.
The form is part of 'single-page'. Single-page is a page which is loaded via AJAX. The form is a standard form with POST method.
Question:
Why does event.preventDefault() not work and how do I fix this issue?
Form:
<form id="comment-form" action="commentsystem.php" method="post">
<input type="text" placeholder="Write a comment..." name="commentTxt" />
<input type="hidden" value="'.$row['id'].'" name="postID" />
<div class="submit-btn">
<img src="assets/images/checkmark.svg" />
<input type="submit" value="" />
</div>
Jquery:
$('#comment-form').on('submit', function (event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $('#comment-form').serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: formData,
success: function (response) {
$('.comment-container').append(response);
}
});
});
Commentsystem.php:
$sql = "INSERT INTO comments (postID, userID, comment) VALUES ('$_POST[postID]', '$_SESSION[id]', '$_POST[commentTxt]')";
if ($conn->query($sql)===TRUE){
echo '<p><span class="username">'.$_SESSION[id].'</span>'.$_POST[commentTxt].'</p>';
} else{
echo 'Something went wrong while sending your comment.';
}
Late to the party! I recently had this issue, hoping this will help someone else. I'm not sure why this happened, but on my localhost the following worked fine but on production preventDefault wasn't working.
$(document).ready(function() {
$(document).on('submit', ".edit-form", function(event) {
event.preventDefault(); // Stop form from submitting normally
var url = $(this).attr("action"); // where to post to
// more code
return false; // added for good measure(might not need)
});
});
Apparently the .on() doesn't like being in $(document).ready(), and from some reading it doesn't need to be. Which is great if you are using it like I was, because I was replacing forms that also needed it.
So all you need to do is remove the $(document).ready(){}; and see if it works just like this.
$(document).on('submit', ".edit-form", function(event) {
event.preventDefault(); // Stop form from submitting normally
var url = $(this).attr("action"); // where to post to
// more code
return false; // added for good measure(might not need)
});
As I said I'm not sure why this works, I haven't messed with jQuery in a long time, all I know is that it on my localhost preventDefault worked as expected and on production it ignored it. If anyone could point me in the the right direction of why it would work on local and not production? It would be appreciated. Maybe the hosting companies PHP settings? (haven't a clue, grasping at straws at this point)
I've figured it out myself. Am posting my own answer because it might help out someone else.
I changed:
$('#comment-form').on('submit', function (event) {
to:
$(document).on("click",".comment-submit", function(event) {
Note that I added a class to my submit button in the form.
I have no idea why this is working, but it does. If anyone could explain, that'd be appreciated.
Related
I'm trying to change my form action to another link during submit using jquery. Please view the following code:
javascript
$(document).ready(function(){
$("form[name='search']").submit(function(e){
var submit=$(this);
submit.attr('action','?search='+submit.find("input[name='tsearch']").val());
});
});
HTML/PHP
<form name="search" method="post">
<input class="inputbox" type="text" name="tsearch" value="<?php echo $text_search; ?>" />
Though i can't seem to get it working. Any help here will be appreciated.
Here's a working example: http://jsfiddle.net/RmKDT/4/
You can see by the alerts that the action is changing. You just need to resubmit the form as well.
Edit: Fixed potential infinite loop
$(function(){
var submitted = false;
$('form').submit(function(e){
if (submitted == true) {
return;
}
e.preventDefault();
var action = $(this).attr('action');
alert(action);
$(this).attr('action', 'two.php');
action = $(this).attr('action');
alert(action);
submitted = true;
// resubmit the form
$(this).submit();
});
});
Your code seems to be fine. There are a few things you can try to get this working.
Be sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file else in the html head section
Be sure that you've included the datatale script after you've included jQuery, as it is most certainly dependant upon that.
Check whether jQuery is included properly and once only.
Watch out for jQuery conflicts. There is some other library which is overridding $, so your code is not working because $ is not an alias for jQuery anymore. You can use jQuery.noConflict() to avoid conflicts with other libraries on the page which use the same variable $.
alert('?search='+submit.find("input[name='tsearch']").val()) see whether you are getting the value you want.
i am trying to create a form submit when checkbox is changed
my code is given below. . my problem is nothing happens on
gotofile.php
file but //dosomething
on the sucess function is executed
the jquery:
$("#container input[type=checkbox]").change(function(e){
if($(this).attr('checked'))
{
var cnType=$(this).attr("id");
$.ajax({
type: "POST",
url: "gotofile.php",
data: "typID="+cnType ,
cache: false,
success: function(){
//do something
}
});
}
});
the php:
include '../dbconnection/dbconfig.php';
$typeID=$_POST['typID'];
$qryConnections="INSERT INTO ...";
$rslt1 = mysql_query($qryConnections);
the html
<form id="cnct" method="POST">
<div id="container" style="">
<ul style="list-style: none;">
<li><input type="checkbox" id="1" />A</li>
<li><input type="checkbox" id="2" />B</li>
</ul>
</div></form>
Can any one help me what i am doing wrong?
A couple of security issues
Always keep in mind that your JS is viewable to anyone that navigates to your site. Using:
data : "typID="+cnType
Would make me think that typID is the field in your SQL. You have no CSRF filter, therefore I could write an ajax script to spoof valid requests and update all of your fields from an external location. Something to keep in mind, I recommend you read up on CSRF or Cross Site Request Forgery.
Why doesnt your script work
If the success function is firing, then the script has run. Debug it by outputing the value of $_POST['typID'] in your PHP. You will see the variables value in the console if it sent correctly.
As well as this it's always good to have your PHP echo out a JSON response for your success function to validate that all went well.
echo json_encode(array('response' => 'success'));
or ('response' => 'failed') or whatever you need. You can then evaluate the JSON in your success function.
I hope this helps.
The first thing is you should use click instead of change event for the checkbox in your Jquery code.
The second thing, you did not provide any value to the checkbox in your html code.
Kindly ask if it not worked for you.
Try
$("#container input[type='checkbox']").click(function(e){
var cnType=$(this).attr("id");
$.ajax({
type: "POST",
url: "gotofile.php",
data: "typID="+cnType ,
cache: false,
success: function(){
//do something
}
});
});
I'm about to pull the hair out of my head with this one.
I'm sure the problem is simple, I'm new to Ajax with Jquery and I'm just overlooking something. But Man this is annoying. Every time the form is submitted, the page refreshes and .ajax throws error:. What could be causing this? I know I'm getting my form values to the Jquery for sure. And newcomment.php is working. I can post regular forms to it, but not with jquery.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
EDIT: Here's my html form:
<form>
<textarea id="comment" placeholder="Post Comment..."></textarea>
<input id="album" type="hidden" value="<?php echo "$a"?>"/>
<input id="photo" type="hidden" value="<?php echo "$p.$ext"?>"/><br/>
<button id="photo-comment-submit" onclick="postPhotoComment()">Post</button>
</form>
I also noticed that if I give the inputs names, Chrome puts them into the url bar like GET variables. And after every page refresh, it adds the ? at the end of the url. So, it seems like its trying to submit the form regularly.
Are you returning false to stop the browsers default action?
$('form').submit(function(){
var dataString = $(this).serialize(); // shortcut
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
});
return false;// cancels the default action
});
If the function where you're calling the AJAX form submission code is the onSubmit method of the form, you'll need to stop the default action from happening -- that is, you want to stop normal submission.
To accomplish this, use the preventDefault method of the event object:
function postPhotoComment(evnt) {
evnt.preventDefault();
// existing code continues...
}
You may also return false from your event, but be aware that doing so has different effects in different browsers, and that it is not as explicit or reliable as calling preventDefault or stopPropagation directly.
Edit
Also, the error handler is probably getting called because your code initiates the XHR request, but when the browser starts the default action (submitting the form), it cancels any pending XHR requests. This is causing the error handler to be triggered.
Edit 2 I have created a jsFiddle with a working demonstration: http://jsfiddle.net/wXrAU/
Documentation
event.preventDefault method on MDN - https://developer.mozilla.org/en/DOM/event.preventDefault
Make sure that you return false; to the form when submitting, otherwise it will still submit as a "normal" form without using Ajax and reload the page.
EDIT: After reading the comments I think that this would be most appropriate for you:
<form action="url.php" onsubmit="return false;"></form>
jsFiddle with appropriate code: http://jsfiddle.net/SO_AMK/ZVgNv/
The PHP messes things up a little, but it works.
I actually fixed this by simply removing the <form> tags. I didn't need them anyways. But everything seems to work now.
Make sure you write a valid, HTTP-accessible url instead of just a path to a script, e.g.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "http://yoursite.com/whatever/newcomment.php", // here
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
Because JavaScript is a client-side language. It knows nothing about your filesystem structure or anything of that kind. And AJAX request is based on HTTP protocol.
I am trying to run this tutorial
i did not implement the validation part yet, but my problem shouldn't be based on this. Here is my code:
<script type="text/javascript">
$("#submitbutton").click(function () {
var content = $.("#contentarea").val();
$.ajax({
type: "POST",
url: "addArticle.php",
data: content,
success: $.("#addArticle").append("<p>ok</p>")
});
return false;
})
</script>
As seen in the demo, it should not refresh the page because of the return false statement and also should do a post instead of get. But neither it does. It will continue to reload the page and also append the given content to the url as an argument. How do i prevent this / where is my failure?
Here is the whole thing
The tutorial you have followed is incorrect. There are more ways to submit a form than just clicking on its submit button (for example, you can press return while in a text field). You need to bind your code to the form's submit() event instead of the button's click() event.
Once you have done this, use your in-browser debugger to check whether the code is actually being run when you submit the form.
Also, the success parameter needs to be a function:
submit: function() { $("#addArticle").append("<p>ok</p>") }
EDIT : also, you have written $.( instead of $( several times. This will cause a runtime error, which may cause the code that blocks the submission to fail.
Well well well...
A few less nerves later, it works.
I decided to use the jquery form plugin
But, and i bet you'll love that, i have no idea why it is working:
<script>
$(document).ready(function() {
$('#addForm').ajaxForm(function() {
alert("ok");
});
});
</script>
<div id="addArticle">
<form id="addForm" method="post" action="addArticle.php">
<textarea id="contentarea" required="required" name="content"> </textarea>
<br />
<input type="submit" id="submitbutton">
</form>
</div>
I guess the author has done pretty good work, just wanted to tell my solution to that future guy who is searching on google for that problem.
This is my form:
<form id="submitsearch" action="Classes/system/main/searchresult.php" method="POST">
Search by <span style="font-size:15px;">(developer, specialization, profession,major)</span>
<input type="text" name="searchbox" id="searchbox" />
in
<select style="text-align:center;" name="countrysearch" id="countrylist">
<option selected="selected" value="0">None</option>
<option value="1">USA</option>
</select>
<input style="margin-left:25px;" id="submitSearch" type="submit" value="Search"/>
</form>
and this is the Ajax jquery code:
$("#submitSearch").click(function(){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#submitsearch').find('#pagePanel').html(response);
});
Why isn't it working ? The php file is returning the correct result normaly.
But i want it to load inside another div with an id "pagePanel" without reloading, using ajax.
Any help ? I'm new to Ajax.
Edit:
$("#submitbutton").click(function(){
$.ajax({type:'POST', url: 'Classes/system/main/searchresult.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
}})});
This worked out with me.
Thanks for all your help.
If you have a input of type submit, it will, guess what :), submit the form, and therefore reload the page. Turn it into:
<input style="margin-left:25px;" id="submitSearch" type="button" value="Search"/>
Then make sure you actually have a pagePanel element in your html.
And now a couple of suggestions:
don't id your form #submitsearch and the button as #submitSearch... confusion may arise
you can use AJAX's .load() instead of .ajax() to get directly the result in the DIV:
So:
$("#pagePanel").load('Classes/requests/search.php', {$('#submitsearch').serialize()});
If you want to use ajax in the form submition you'll need to cancel it.
$("#submitSearch").click(function(event){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
});
event.preventDefault();//prevents submitting of the form
}
First you need to stop the default form submittal. return false in the submit handler to stop default. Just use the ID of the element without using find() to insert data into. The elemnt you are trying to find doesn't appear in your html though within the form where your code suggests it should be
$("#submitSearch").click(function(){
$.ajax({type:'POST',
url: 'Classes/requests/search.php',
data:$('#submitsearch').serialize(),
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
})
return false;
});
After pushing the submit button, the default behaviour is to submit the form and indeed go to the action URL you provided to your form. Now, you want to prevent that behaviour. This means, you'll have to look at the onsubmit event of the form, and prevent the actual submission. jQuery has a preventDefault() method to do this.
In your case, all you'll have to do is add the following code:
$(document).ready(function() {
$("#submitsearch").on("submit", function (e) {
e.preventDefault();
});
});
And here is a jsFiddle to demonstrate it.
You can obviously do the same thing to your submit button, just add the e variable as the argument to your click event and use e.preventDefault() to cancel the actual submit (but you can still perfectly do the AJAX request).
First of all, you are missing a few closing parenthesis and curly brackets. Be sure to run your dev tools in your browser to check console for errors like that. I normally don't use $.ajax...I usually use $.post, but using what you have so far, I would rewrite to something closer to:
$("#submitsearch").submit(function(){
var submitData = $(this).serialize();
$.ajax(
{
type:'POST',
url: 'Classes/requests/search.php',
data: submitData,
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
}
);
return false;
});
Instead of sending back loads of HTML to the page, you could just send results in form of a set of JSON objects and then dynamically create the HTML based on the results, this means a lot less data being sent back to the browser which is quicker and more efficient.