Jquery Ajax Request and PHP - php

New to Jquery, even newer to Jquery Ajax calls - here is my problem:
I have a small form - email address submit - that fires to a PHP file which inserts the email into a table.
I want to do the following:
Handle the form submission through Ajax so there is no refresh
After successfully writing to the table I want to change the submit button's text to "Success!" for 3 seconds and then back to
"Sign Up" with fadeIn and fadeOut effects.
Here is my code for the form:
<form action="" id="registerform" name="registerform" method="post" >
<input type="text" id="email" name="email" value="Email Address" onClick="empty()" onBlur="determine()" />
<button id="join" type="submit" name="join" onClick="validate()">Sign Up</button>
</form>
Here is my terrible attempt at handling the POST request through Jquery:
$('form').on('submit', function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Can anyone comment on how to make the Ajax request work (doesn't seem to be)?
Thanks in advance!
Update
Alright, the following block of Jquery adds the data to the table, however, my button text does not change:
$('form').on('submit', function(e) {
$.post('register.php', $("#registerform").serialize(), function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Any ideas now?

Here is an example of one of my ajax calls
details = "sendEmail=true&" + $("form").serialise();
$.ajax({
url: "yourphppage.php",
type: "post",
data: details,
success: function (data, textStatus, jqXHR) {
if (data == "false") {
console.log("There is a problem on the server, please try again later");
} else {
//Do something with what is returned
}
}
})
And on the server side
if (isset($_POST['sendEmail'])) {
//Do something with the data
}
Of course this is only an example, and you may need to alter this to suit your needs :)
One thing to note is what if (data == "false") does. Well on the server side i can echo "false" to tell the ajax call it was not successful.

You're not actually sending any data to the server. You need to use the 'data' parameter of $.post to send your data.
$('form').on('submit', function(e) {
$.post('register.php', $(this).serialize(), function() {
$('#join').html('Success!');
});
//disable default action
e.preventDefault();
});

Not sure, but does the POST request send anything at all? Try adding the data in the POST request.
$('form#registerform').submit(function() {
var email = $(this).find('input[name=email]').val();
$.post('register.php', {email: email}, function() {
$('#join').html('Success!');
});
return false;
});

Where you're pushing your form data to server in ajax call? change code to this.
var data = {$("#email").val()};
$('form').submit(data ,function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});

Related

My textarea sends empty values with ajax for my PHP codes

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">

i have a form i want to submitted form with post method with out refresh page but here post is not working

<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.

Refreshing div without reloading not working

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
}

Hiding div then posting form

I'm still working on my multi-stage form (http://jsfiddle.net/xSkgH/93/) and have incorporated the following solution to assist in ajax submit:
<script type="text/javascript">
$(document).ready(function() {
$("#postData").click(function() {
$("#last-step").hide(600);
$("#task5_booking").submit(function() {
$.post('resources/process2.php', function(data) {
$("#result").html(data);
});
});
return false;
});
});
</script>
It fades out the last step well but when it comes to loading up the content ot process2.php which is simply an array of all the form fields:
<?php
print_r($_POST);
?>
Nothing seems to happen at all. The div remains blank. Would really appreciate any help guys. Thanks in advance.
if you call a resource via ajax you should also pass the serialized form along the call. So assuming $("#task5_booking") is your form element
$("#task5_booking").submit(function(evt) {
evt.preventDefault();
$.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {
$("#result").html(data);
});
});
When you submit the form
stop the default event (submit) otherwise the form submission stops immediately the subsequent code and the ajax call never starts - this is done using preventDefault() method;
make a post call, passing the form serialized with serialize() method (see http://api.jquery.com/serialize/).
Please also note that as pointed out by Jack your form in the fiddle has camperapplicationForm id and not task5_booking
I think you should remove your submit function:
<script type="text/javascript">
$(document).ready(function() {
$("#postData").click(function() {
$("#last-step").hide(600);
$.post('resources/process2.php', function(data) {
$("#result").html(data);
});
return false;
});
});
</script>
$(document).ready(function() {
$("#postData").click(function(e) {
e.preventDefault();
$("#last-step").hide(600);
$("#task5_booking").submit(function() {
$.post('resources/process2.php', $(this).serialize(), function(data) {
$("#result").html(data);
});
});
});
});

event.preventDefault() on submit a form

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:)

Categories