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.
Related
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.
I have a problem with my jquery script, it is returning error when I try to send the date value from my form, when I leave it in blank, it doesn't show me an error.
<div class="field-wrap">
<input type="date" name="fecha_nacimiento" required autocomplete="off" maxlength="30" placeholder="Fecha de nacimiento">Fecha de nacimiento</input>
</div>
<script>
$(function(){
$('#entrarBt').click(function(){
$.ajax({
url: 'registro_dpb.php',
type: 'POST', // GET or POST
data: $("#miForm").serialize(), // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is: " + data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!");
}
});
});
});
</script>
Your problem was pretty subtile... Making it hard to find.
But the solution is really simple.
You use a <button> inside a <form> which is absolutely correct.
But you have to know that in HTML5, if the type of a <button> is not explicitly defined as "button", its default type is "submit".
Reference here.
This was the issue...
Since you want to submit using an ajax request, which allow to receive a response without reloading the page, you have to "prevent" this normal behavior of a <button>.
The submit made by the button was not sent to your PHP script, but to your HTML page (there was no other action defined in the <form> tag, so the default is "self".
So the page reloads... Making your ajax request to fail.
So there is two ways to fix this:
1: Define the button type as "button":
<button type="button" id="entrarBt" [+ other attributes]>Entrar</button>
or
2: Prevent this default behavior using prevent.default() in you click handler.
$('#entrarBt').click(function(e){
e.preventDefault();
$.ajax({
//...
I think the second one is more evident for another programmer who could review your code, but the first is ok too.
For the benefit of the other SO readers:
We *(me and Javier)* checked almost every other error possibilities [in chat][3].
I finally found the cause when, for a test, I commented out the whole ajax block and then noticed that the page was still submitting.
Fixing this completely resolved the issue.
This is a tricky thing to absolutely know!
In short, a <button> within a HTML5 <form> is a submit by default!
I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});
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.
Hello I have the next code into my website:
<input type="text" id="name" name="name" width="25px"/>
Add User
I need that when I click "newUser" the value of the name is saved into my mysql database without refreshing the page.
Any exemple of how to do this?
If you don't want to use a <form> and a submit button which would be the absolutely correct way to do this, you will need to use javascript and AJAX:
Subscribe for the onclick event of the anchor
Send an AJAX request to the server passing the value of the name entered in the textbox
Cancel the default action of the link
Add User
and the insert function could be defined in a separate javascript file:
function insert() {
var name = document.getElementById('name').value;
// TODO: send an AJAX request to the server
return false;
}
http://api.jquery.com/jQuery.ajax/
$('#newUser').click(function(ev){
$.ajax(...);
ev.preventDefault();
});
This can be done on the client side with jquery's ajax libraries to create the refreshless submit.
Here's an example of some html and javascript
<html>
<head>
<script type="text/javascript" src="jq/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
function adduser()
{
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "adduser.php",
data: data,
dataType: "html",
});
}
</script>
</head>
<body>
<form id="adduserform" name="adduserform">
<fieldset>
<input type="text" id="name" name="name" width="25px"/>
</fieldset>
</form>
Add User
</body>
</html>
On the php side just code like you would if you were submitting a form via post.
I haven't had time to try it, but I hope it works :)
Like the others have suggested, look on the jquery site for more info.
You can do an Ajax call with JQuery that will send the name to the server. In your PHP code you will be able to create the Insert Query in your user table.
You can use JavaScript for that. Take a look at jQuery ajax: http://api.jquery.com/jQuery.ajax/
note: next time try googling, or at least provide what you have tried