I need your help. I created this simple script. My goal is to update my database with the text inside the textarea of this form. The problem is that the script works only the second time i press the submit button. For some unknown reason (at least for me) it doesn't work the first time.. May you help me, please?
<script>
$(document).ready(function(){
$("#form_dove").submit(function(e){
e.preventDefault();
$("#click_dove").click(function(){
testo = $("#textarea_dove_2").val();
alert(testo);
data = 'testo='+testo;
$.ajax({
type:"POST",
url:"php/update_dove.php",
data: data,
cache: false,
success: function(html){
$('#textarea_dove_2').val(html);
alert('Aggiornato!');
}
});
});
});
});
</script>
<form name="form_dove" method="post" id="form_dove">
<div id="textarea_dove">
<textarea rows="17" cols="90" name="textarea_dove_2" id="textarea_dove_2" >
<?php echo("$testo_dove"); ?>
</textarea>
</div>
<div id="form_submit_dove">
<input type="submit" value="SALVA E AGGIORNA" id="click_dove">
</div>
</form>
The $("#click_dove").click is inside the submit.
This means the click becomes active only after the form is submitted. The code is clear :)
In your case the ajax call is done in the button click handler, but the button click handler is registered in the form submit handler, so only after the first form submit(triggered by the submit button click) the click event handler which is doing the ajax call will get registered.
Solution: You don't need the click event handler, move the ajax call to the submit event handler
$(document).ready(function () {
$("#form_dove").submit(function (e) {
e.preventDefault();
testo = $("#textarea_dove_2").val();
alert(testo);
data = 'testo=' + testo;
$.ajax({
type: "POST",
url: "php/update_dove.php",
data: data,
cache: false,
success: function (html) {
$('#textarea_dove_2').val(html);
alert('Aggiornato!');
}
});
});
});
You don't need two functions here. The $("#form_dove").submit function gets called when the form is submitted and the $("#click_dove").click function is invoked when the button is clicked.
Because you put the definition of the click function inside the submit function, the click function was not declared (ie didn't exist) until the form was submitted (ie. the first time you clicked the button). Then the second time the button was pressed, the click function did your ajax stuff.
In this case, it's most straightforward just do the processing you want in the submit function - it's what you want to happen when the form is submitted. Use the click function if you need to do some checking to see if the form has been filled in properly before submitting it.
<script>
$(document).ready(function(){
$("#form_dove").submit(function(e){
e.preventDefault();
testo = $("#textarea_dove_2").val();
alert(testo);
data = 'testo='+testo;
$.ajax({
type:"POST",
url:"php/update_dove.php",
data: data,
cache: false,
success: function(html){
$('#textarea_dove_2').val(html);
alert('Aggiornato!');
}
});
});
$("#click_dove").click(function(){
//put some validation in here if you want
});
});
</script>
Related
i have created a textarea & i wanna send the values of my textarea with ajax to the database, but it sends it to database without any value and with reloading, where is my problem ?
html codes :
<form>
<textarea></textarea>
<button type="submit">ارسال</button>
</form>
ajax codes :
$(document).ready(function(e){
var text=$('textarea').val();
$('button').click(function(e){
$('.loading').css('display','block');
$.ajax({
url:'insertText.php',
type:'POST',
data:{'text':text},
beforeSend : function(){
$('.loading').html('فرستادن ...');
},
error : function(request) {
alert(request);
},
success:function(data){
alert(data);
}
});
});
});
and this is my pdo and mvc for informations , i put last layer :
$obj=new Get;
$obj->InsertText($_POST['text']);
Place the line var text=$('textarea').val(); inside click event of the button, Otherwise it will take only the initial value at the time of dom ready.
$(document).ready(function(e) {
$('button').click(function(e) {
var text = $('textarea').val();
$('.loading').css('display', 'block');
$.ajax({
url: 'insertText.php',
type: 'POST',
data: {
'text': text
},
beforeSend: function() {
$('.loading').html('فرستادن ...');
},
error: function(request) {
alert(request);
},
success: function(data) {
alert(data);
}
});
});
});
You have two problems:
You are getting the value from the textarea at the wrong time
You are submitting the form
Your line of code:
var text=$('textarea').val();
Is inside the ready handler but outside the click hander. This means you get the value at the time the DOM becomes ready and not at the time the button is clicked.
Move it inside the click handler.
To stop the form submitting, you need to tell the browser not to perform the default action for clicking a submit button:
$('button').click(function(e){
e.preventDefault();
Note that, in general, it is better to react for the form being submitted rather than a specific submit button being clicked:
$('form').submit(function(e){
e.preventDefault();
It is also preferred that the form should still work when the JavaScript fails (for whatever reason):
<form action="insertText.php" method="POST">
and
<textarea name="text">
<script type="text/javascript">
$(document).ready(function() {
$('#form1').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({ type: 'POST',
url: 'car1.php',
data: $('#form1').serialize(),
success: function () {
// alert('form was submitted');
$("#allyears").hide();
$("#clickresult").show(); } }); });});
</script>
//year show
while($row_year1=mysql_fetch_array($result_year1))
{ ?>
<input type="submit" class="submitbutton1" tabindex="-1" name="submitbutton" value="<?php echo $row_year1['years']; ?>" id="show<?php echo $row_year1['years']; ?>" />
<?php } ?>
//result
<?php
if(isset($_POST['submitbutton']))
{
$submitbutton=$_POST['submitbutton'];
echo $submitbutton;
}
?>
I don't know why people are downvoting this question, but your problem is your event listener. You are checking if the form has been clicked other than if the form has been submitted. If you want to use the click event listener, you would bind it to the submit button instead. But this isn't suggested since sometimes the submit button isn't clicked and the user presses enter instead to trigger the form to submit. So stick with the submit event listener on the form.
http://jsfiddle.net/gaQK3/
$(document).ready(function () {
$('#form1').bind('submit', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'car1.php',
data: $('#form1').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
Also just a few notes about your other code.
1) Stop using the mysql_ functions. They are now deprecated. You should use PDO or MySQLi. I prefer PDO and believe it will have better future support.
2) Make your nested code even. In your Javascript you close all of the tags on the very last line all together. This is very hard to follow. In my code example you can see exactly what happens.
3) Separate your Javascript and PHP. I don't know if you combined them for the question's purpose, but don't have them in the same file.
4) Add error handling for the Ajax request along with the success handling. At one point or another the request is going to fail and you will want to alert the user to try again.
I'm "fighting" with this for hours now, I hope you could help me with the solution. So I've got a basic form with an empty div that will be then filled:
<form method='post' action='/shoutek.php'>
<input type='text' id='shout_tresc' name='shout_tresc' class='shout_tresc' />
<input type='submit' id='dodaj' value='Dodaj' />
</form>
<div class='shoutboxtresc' id='shout'></div>
<span class='loader'>Please wait...</span>
The shoutek.php contains the queries to do after submission of the form and functions to populate the div.
Here goes my jquery:
$(function() {
$(\"#dodaj\").click(function() {
// getting the values that user typed
var shout_tresc = $(\"#shout_tresc\").val();
// forming the queryString
var data = 'shout_tresc='+ shout_tresc;
// ajax call
$.ajax({
type: \"POST\",
url: \"shoutek.php\",
data: data,
success: function(html){ // this happen after we get result
$(\"#shout\").toggle(500, function(){
$('.loader').show();
$(this).html(html).toggle(500);
$(\"#shout_tresc\").val(\"\");
$('.loader').hide();
});
return false;
}
});
});
});
The problem in that is that it directs me to shoutek.php, so it does not refresh the div in ajax.
As you can see, I used return false; - i also tried the event.preventDefault(); function - it did not help. What is the problem and how to get rid of it? Will be glad if you could provide me with some solutions.
EDIT
Guys, what I came up with actually worked, but let me know if that's a correct solution and will not cause problems in the future. From the previous code (see Luceous' answer) i deleted
$(function() {
(and of course it's closing tags) and I completely got rid of the:
<form method='post' action='/shoutek.php'>
Leaving the input "formless". Please let me know if it is a good solution - it works after all.
$(function() {
$("#dodaj").click(function(e) {
// prevents form submission
e.preventDefault();
// getting the values that user typed
var shout_tresc = $("#shout_tresc").val();
// forming the queryString
var data = 'shout_tresc='+ shout_tresc;
// ajax call
$.ajax({
type: "POST",
url: "shoutek.php",
data: data,
success: function(html){ // this happen after we get result
$("#shout").toggle(500, function(){
$('.loader').show();
$(this).html(html).toggle(500);
$("#shout_tresc").val("");
$('.loader').hide();
});
return false;
}
});
});
});
For readability I removed your escapes. You've missed the preventDefault which prevents the form from being submitted.
You need to prevent the default action on submit button click:
$("#dodaj").click(function(event) {
event.preventDefault();
// your code
}
I am using cakephp and jquery with the form (file-field with submit button) to upload picture.
All I need to do is to do AJAX image upload form. I don't want to refresh the page. So I bind event.preventDefault on submit the form. But I am not sure that the $_FILE['y'] is stopped by the event.preventDefault.
I wonder if the form is submitted ,and I bind event.preventDefault on submit the form.
Do the superglobal,such as $_REQUEST['x'] , $_FILE['y'] ,$_POST['x'] ,$_GET['x'] still there?
if not there , how to do this?
thankyou.
<script type="text/javascript">
$(document).ready(function() {
var getAjax=function(event){
$.ajax({
'url':'<?php echo $this->webroot;?>vehiclePictures/addImageAjax/',
'data': {'x': 33,'y':44},
'dataType': 'json',
'type': 'GET',
'success': function(data) {
if (data.length) {
$.each(data, function(index, term) {
alert(term[1]);
});
}
}
})
event.preventDefault();
};
$('#imageUploadForm').submit(getAjax);
});
</script>
If you're using a button to submit the form, I'd just add return false to the button and have it run the ajax-call instead. Not sure if this is what you were wondering tho?
Like this:
<form method="post" action="someFile.php">
//Form here
<input type="submit" id="buttonToPostForm" />
</form>
function ajaxCall() {
$.ajax({
//Ajax data goes here
});
}
$("#buttonToPostForm").click(function() {
ajaxCall();
return false;
});
And fill in so the data from the form is sent like in you original code.
Hope I understood the question correctly, if not I apologize:)
i have form and i am using jquery validate jquery.validate.pack.js
its work fine when i press submit button, i just add following code
$(document).ready(function(){
$("#contactform").validate();
});
and class="validate" for text box
but i want to call php file with Ajax after validate is complete.
like
$.ajax({
type: "POST",
url: "email_feedback.php",
etc
how can i do this ?
Thanks
See the submitHandler callback option in http://docs.jquery.com/Plugins/Validation/validate#options
$("#contactform").validate({
submitHandler: function(form) {
//$(form).ajaxSubmit(); // for the default ajax submission behavior
$.ajax({ type: "POST", url: "email_feedback.php"})//, etc... for your own
}
})
This will submit the form to the URL that is in the action attribute of the form via AJAX though:
$("#contactform").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
})
Here's an additional link for you as well: http://www.malsup.com/jquery/form/#api
Thanks,
Orokusaki