Form not submitting without redirecting - php

I want to send sms on click without page reload and redirecting but the form not working without redirecting to action page. Here is my code.
Page containing form
<div class="blog">
<form method="post">
<input type="hidden" name="message" value="whatever">
<input type="text" name="tono" maxlength="10">
<input type="submit" value="SEND SMS" id="sendit">
</form>
<script>
$(document).ready(function(){
$("#sendit").click(function(){
$.ajax({
type: "POST",
url: "./example.php",
data: $(form).serialize();
}).done(function(response) {
alert(response);
});
return false;
});
});
</script>
</div>
example.php
<?php
error_reporting(E_ALL);
ob_implicit_flush(true);
include_once "class.curl.php";
include_once "class.sms.php";
include_once "cprint.php";
$smsapp=new sms();
$smsapp->setGateway('way2sms');
$myno='XXXXXXX';
$p='XXXXXXXX';
$tonum=$_POST['tono'];
$mess=$_POST['message'];
cprint("Logging in ..\n");
$ret=$smsapp->login($myno,$p);
if (!$ret) {
cprint("Error Logging In");
exit(1);
}
print("Logged in Successfully\n");
print("Sending SMS ..\n");
$ret=$smsapp->send($tonum,$mess);
if (!$ret) {
print("Error in sending message");
exit(1);
}
print("Message sent");
?>
This reloads the page but doesn't submit the form and if i add action attribute to form it redirects to example.php and successfully sends sms.

I see you are returning false in the handler, which is basically the same as using event.preventDefault(), but this is not working because you have a syntax error (a semicolon that should not be there):
$(document).ready(function () {
$("#sendit").click(function () {
$.ajax({
type: "POST",
url: "./example.php",
data: $(form).serialize() // You have ";" here, and it's causing the rest of the code to fail.
}).done(function (response) {
alert(response);
});
return false;
});
});

Related

Submit Form Without Reloading Page and Get Output [PHP, jQuery]

Hellow,
I've been trying to submit a form without reloading and getting PHP output on the same page. The main objective is to submit the form values to a PHP file and get the output sent by the PHP file.
To understand it better, let's take a look on following code snippet:
HTML & jQuery Code:
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'on.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input id="name" name="name"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP Code:
<?php
if (isset($_POST['submit'])){
$name=$_POST['name'];
if($name == 'Johny'){
echo "Welcome Johny";
}
else{
echo "I Dont Know You";
}
}
?>
What I Want:
When user enter value in the Input box and submit it, the page should display output value e.g ECHO value without reloading the webpage.
To be more specific on my first comment, you have to put an exit statement after you echo the response so the rest of the code doesn't execute, also to check whether the form was sent or not you can add a hidden input in your form with the value "1" (<input name="formSent" type="hidden" value="1">) that gets checked in your PHP :
<?php
if (isset($_POST['formSent'])){
$name=$_POST['name'];
if($name == 'Johny'){
echo "Welcome Johny";
exit;
}
else{
echo "I Dont Know You";
exit;
}
}
?>
and then get the response from the ajax request in the success's callback parameter, also specify the method: 'POST' because jQuery's $.ajax function uses the method GET by default:
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'on.php',
method: 'POST',
data: $('form').serialize(),
success: function (message) {
alert(message);
}
});
});
});
</script>

Callback message for php form

I just want to know how i can send a "callback" message for "success" or "error".
I really don't know much about jquery/ajax, but, i tried to do this:
I have a basic form with some informations and i sent the informations for a "test.php" with POST method.
My send (not input) have this id: "#send". And here is my JS in the index.html
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
$(".message").load('teste.php');
});
});
And, in my PHP (test.php) have this:
<?php
$name = $_POST['name'];
if($name == "Test")
{
echo "Success!";
}
else{
echo "Error :(";
}
?>
When i click in the button, the message is always:
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/sites/port/public/test.php on line 3
Error :(
Help :'(
This is your new JS:
$(document).ready(function()
{
$("#send").click(function(e) {
e.preventDefault();
var form_data = $("#my_form").serialize();
$.post('teste.php', form_data, function(data){
$(".message").empty().append(data);
});
});
});
This is your new HTML:
<form id="my_form">
<input type="text" name="name" value="" />
<input type="button" id="send" value="Send" />
</form>
The problem is you have not passed name data to your PHP Use My Javascript Code.
Problem in understanding please reply
$(document).ready(function() {
$(document).on('click','#send',function(e)
{
var params={};
params.name="Your Name ";
$.post('test.php',params,function(response)
{
e.preventDefault();
alert(response); //Alert Response
$(".message").html(response); //Load Response in message class div span or anywhere
});
});
});
This is somewhat more complicated by you can use it more generally in your project. just add a new callback function for each of the forms that you want to use.
<form method="POST" action="test.php" id="nameForm">
<input name="name">
<input type="submit">
</form>
<script>
// wrap everything in an anonymous function
// as not to pollute the global namespace
(function($){
// document ready
$(function(){
$('#nameForm').on('submit', {callback: nameFormCallback },submitForm);
});
// specific code to your form
var nameFormCallback = function(data) {
alert(data);
};
// general form submit function
var submitForm = function(event) {
event.preventDefault();
event.stopPropagation();
var data = $(event.target).serialize();
// you could validate your form here
// post the form data to your form action
$.ajax({
url : event.target.action,
type: 'POST',
data: data,
success: function(data){
event.data.callback(data);
}
});
};
}(jQuery));
</script>

Jquery ajax form not submitting. going straight to error function

I have a form where users can sign up to a newsletter but i can't get it to submit properly.
When i click the submit button, i get an alert saying "Failure" so the ajax request is going straight to the error catchment in the ajax request.
In my php, I get all the $_POST variables and insert them into the database and I know that script is working. I just want to return the message back to the ajax success so that the message can be displayed to the user.
I have looked everywhere for a solution and can't find one.
<?php
echo "done";
?>
and the form with jquery
<html>
<head>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mlbutton').click(function() {
var name = $('#mlName').val();
var email = $('#mlEmail').val();
$.ajax({
type:'POST',
url: 'storeAddress.php',
data:$('#addressform').serialize(),
success: function(response) {
$('#addressform').find('#response').html(response);
alert(response);
},
complete: function() {
$('#addressform').each(function() {
this.reset();
});
},
error: function(){
alert('failure');
}
});
});
});
</script>
</head>
<body>
<form id="addressform">
<div class="textl1"><label id="namLbl" for="mlName">Name</label><input type="text" id="mlName" name="mlName" /></div>
<div class="textl1"><label id="emlLbl" for="mlEmail">Email</label><input type="text" id="mlEmail" name="mlEmail" /></div>
<div class="textr1"><input type="submit" id="mlbutton" name="mlbutton" value="dffhfdh" class="button-signup" /></div>
<p id="response" style="text-align: left"> </p>
</form>
</body>
</html>
Update
Added e.preventDefault(); //call prevent default on event
This now stops the failure message but it appears that the php file is not called. I have tested the php file and because no email address supplied I get a message i was expecting. If i just click the form without entering an email address, I am expecting the same message but nothing. If i do enter an email address, I would expect the email to be in database but nothing happens. It is like the php file is not being called
The could should prevent the default action of the form.
$('#mlbutton').click(function(e) { //added event as argument
e.preventDefault(); //call prevent default on event
var name = $('#mlName').val();
var email = $('#mlEmail').val();
$.ajax({
type:'POST',
url: 'storeAddress.php',
data:$('#addressform').serialize(),
success: function(response) {
$('#addressform').find('#response').html(response);
alert(response);
},
complete: function() {
$('#addressform').each(function() {
this.reset();
});
},
error: function(){
alert('failure');
}
});
});
You need to prevent your button from submitting the page, so that the AJAX can run.
$('#mlbutton').click(function(e) {
e.preventDefault();
....

Ajax doesn't show server response

I'm trying to build a subscribe form. I can't run php on my site and I don't want the user leave the main site to subscribe the newsletter. I'm using this example as server side.
If you try to put in you email you will get redirected and the error message shows up even if the e-mail was added to the mailchimp list.
<div id="email">
<span>Your email..</span>
<form action="http://simondahla.com/jolliassets/notify.php" id="notify" method="POST">
<input type="text" placeholder="your#email.com" name="email" id="address" data-validate="validate(required, email)"/>
<span>We'll never spam or give this address away</span>
<button type="submit">ยป</button>
</form>
<span id="result"></span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#notify').submit(function() {
var action = $(this).attr('action');
$.ajax({
url: action,
type: 'POST',
data: {
email: $('#address').attr('value')
},
success: function(data){
$('#result').html(data).css('color', 'green');
},
error: function() {
$('#result').html('Sorry, an error occurred.').css('color', 'red');
}
});
});
});
</script>
live example of the problem
You need to return false from your submit handler. This is to prevent the browser from executing the default action, i.e. to submit the form the normal way.
$('#notify').submit(function() {
// .. your ajax call
return false;
});
From your PHP function you're going to return the values you want given the success or failure of the code.
Succeeded:
print json_encode(array("status"=>"success","message"=>'Successfully added'));
Failed:
print json_encode(array("status"=>"error","message"=>'There was an error'));
Then in the HTML you return that message like this:
success: function(data){
$('#result').html(content.message).css('color', 'green');
},
error: function() {
$('#result').html(content.message).css('color', 'red');
}

POST php form using jquery

I need any jQuery code to send form data without refreshing the page.
Method (POST): after submit form show "loading..." message or "loading image". If process.php = 1 (true) hide form and display ok message, and if process.php = 2 ( false ) not hide form and display any error message.
var data = new Object();
data['formData'] = $('#form').serializeArray();
$.ajax({
type: 'post',
url: 'process.php',
dataType: 'json',
success: function(response) {
if (response.result == 1) {
$('#form').hide();
} else {
alert('error');
}
}
});
process.php:
//...
echo json_encode(array('result' => 0)); // OR 1
You need to add form ID or any other identificator.
so, if your form is
<div id="message"> </div>
<form method="post" action="" id="myForm">
<input type="submit" name="send" id="sendData" />
</form>
jQuery:
$(document).ready(function() {
$("#sendData").click(function() {
$("#message").html("loading ...");
$.post("process.php", {
submit: 1 //and any other POST data you separate with comma
}, function(response) {
if(response == 1) {
$("#myForm").hide();
$("#message").html("OK");
} else {
$("#message").html("error message");
}
});
});
});
now, after submit form you will get message "loading ..." while posting "process.php", then if process.php returns 1 the form will be hide and display OK else you get an error message.

Categories