Ajax form submission and storing the data from response? - javascript

I have form which is used for sending sms now am sending the data on submit to sms.php page and executing the process. Now I need to submit the data in form without moving to sms.php page. It should be executed in the form page itself by using ajax method I have done that but also it redirects to sms.php. I need it to be done and the same page and the json response obtained should be stored in the database.
How can I do this? Help me Thanks in advance.
Form used for sending sms:
<form role="form" method="POST" action="sms.php">
<div class="form-group row">
<label class="col-sm-4 form-control-label">Select Date Range<span class="text-danger">*</span>
</label>
<div class="col-sm-7">
<div class="input-daterange input-group" id="date-range">
<input type="text" class="form-control" name="start" />
<span class="input-group-addon bg-custom b-0">to</span>
<input type="text" class="form-control" name="end" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 form-control-label">Select Brand<span class="text-danger">*</span>
</label>
<div class="col-sm-7">
<select class="form-control" name="brand" id="brand" required>
<option value="">Select Brand</option>
<option value="3">test1</option>
<option value="2">test2</option>
<option value="1">test3</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-8 col-sm-offset-4">
<input type="submit" class="btn btn-primary btn-sm" value="Submit">
</div>
</div>
</form>
Ajax used to send data
$('sms').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'sms.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
sms.php
<?php
if(isset($_POST['submit'])){
$senderid =$_POST['senderid'];
// echo $senderid;
$message = rawurlencode($_POST['message']);
$mobile = isset($_POST['mobilenumber']) ? $_POST['mobilenumber'] : '';
sendSMS($mobile,$message,$senderid);
}
function sendSMS($mobile,$message,$senderid){
$user = "asdhaskbdjasdjbfjk";
$url = 'http://login.smsgatewayhub.com/api/mt/SendSMS?APIKey='.$user.'&senderid='.$senderid.'&channel=2&DCS=0&flashsms=0&number='.$mobile.'&text='.$message.'&route=16;';
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,"");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,2);
$data = curl_exec($ch);
print($data); /* result of API call*/
}
?>
Response obtained:
{"ErrorCode":"000","ErrorMessage":"Success","JobId":"112591825","MessageData":[{"Number":"0123456789","MessageId":"mU9WfV6hLEyNAQQI63BzNw"}]}

Your selector in jquery code $('sms') is wrong. And to stop changing the page, you should use click event and stop actually submitting the form like this:
$('.btn-sm').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'sms.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
You can see from the above given code snippet that, I have used click event of the submit button, and also written e.preventDefault() in first line, so it will stop the form to submit but it will just initiate ajax call. So SMS will be sent and you will be on the same page. No redirection will be there.

In your code I found that you added action in your page:
<form role="form" method="POST" action="sms.php">
remove that action and post from form as because you included inside your script tag

Related

I want to reload the page on button click and perform the route action in new tab

<form action="{{ route('payForEveryVoucherAndInvoice') }}" method="post" >
#csrf
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<select id="payment_method" class="form-control" name="payment_method" required>
<option value="" selected="selected" disabled="disabled">Payment</option>
<option value="cash">Cash</option>
<option value="credit">Credit</option>
<option value="debit">Debit</option>
</select>
</div>
</div>
<div class="col-sm-1">
<input type="text" name="driver" value="{{$voucher_driver}}" hidden>
</div>
<div class="col-sm-5">
<button class="btn btn-primary" style="background-color: #262533; border-color: #262533" onClick="refreshPage()" formtarget="_blank">All Entries Paid</button>
</div>
</div>
</form>
This is my form. I am using onClick="refreshPage()" to refresh my page.
<script>
function refreshPage(){
window.location.reload();
}
</script>
This is the script. But when i press the button. It just reloads the page and also not going on the route. I want to reload the page and open another tab to perform the route action.
Any Help? Thanks in advance.
You need to call submit event for that.
<script>
function refreshPage(){
$("form").submit();
window.location.reload();
}
</script>
I would recommend don't do this. use ajax as below.
$('body').on('submit', 'form', function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
data: new FormData(this),
type: 'POST',
contentType: false,
cache: false,
processData: false,
success: function (data) {
window.location.reload();
},
});
});

How to get php page to receive ajax post from html page

I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.
Here is my code.
Form:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.
In this case, you have:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.

Bootstrap Popup on sending form data to mail

I am working as junior web master maybe that's why I have come with a simple question here. I have designed a single page application for client which has contact form at the end of page, validation is done using bootstrap but to send form data to mail id only method I know is using php with action directing different page. since my website is single page application i would like a popup on successful submission to mail id
Below is the HTML code for the contact form
<form class="form-inline" data-toggle="validator" role="form" method="post" id="enquiry" action="index.php">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Name</label>
<input type="text" class="form-control" name="name" id="exampleInputEmail3" placeholder="Name" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Mobile Number</label>
<input type="text" class="form-control" id="exampleInputPassword3" name="mobile" placeholder="Mobile Number" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Email Id</label>
<input type="email" class="form-control col-lg-12" id="exampleInputPassword3" name="email" placeholder="Email Id" required>
</div>
<br/> <br/>
<div class=" col-lg-12 form-group">
<textarea cols="80" placeholder="Enter query Here" class="form-control" name="query" id="address" data-error ="Please Enter Your Query" required></textarea><br/><br/>
</div>
<button style="background-color:#f15a24; color:#FFF;" name="submit" id="submit" type="submit">Submit</button>
</form>
Can use php to send form data and still get a pop up in same page?
Or do I need to use jquery to send data and pop-up?
It would be great if somebody helps me out with code, thanks in advance
Updated
below(index.php page) i have added the code what you have given,
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.easing.min.js"></script>
<script src="js/jquery.fittext.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/creative.js"></script>
<script src="js/validator.js"></script>
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success"){ alert("Success"); }else{ alert("Failed"); }
//Failure message if ret is false
});
}
});
});
</script>
Add this js to your script
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success")
{
alert("Success");
} else {
alert("Failed");
}
}
});
}
);
});
submit.php contains the code to send and exit it with the success (true) or failure (false) message. That will be caught in ret variable.
Edited
This will be more detailed answer I was looking for, I thought it be would be helpful for somebody so I have answered my own question as an alternative solution, check out the links below.
Show submitted form response on the same page. (No Reload)
http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html

Issue with multipart/form-data, ajax and textarea with TinyMCE

I'm working with html/php/ajax/jquery and today I pointed out a little issue that is driving me crazy.
I've got an html form:
<form method="POST" enctype="multipart/form-data" name="myForm" id="myForm" action="">
<label class="form-label">Nome</label>
<input name="nome" type="text" class="form-control"><br>
<label class="form-label">Descrizione</label>
<textarea name="descrizione" id="text-editor" placeholder="" class="form-control" rows="10"></textarea>
<label class="form-label">Stato</label>
<select name="stato" id="source" style="width:30%">
<option value="1">Abilitato</option>
<option value="0">Disabilitato</option>
</select>
<h4>Foto profilo</h4>
<input type="hidden" name="MAX_FILE_SIZE" value="20400000" >
<input style="border:0px;" type="file" name="user_foto" id="file">
<div class="form-actions">
<div class="pull-right">
<button type="submit" class="btn btn-success btn-cons"><i class="icon-ok"></i>Inserisci</button>
<button type="button" class="btn btn-white btn-cons" onclick="window.location.href='index.php'">Indietro</button></a>
</div>
</div>
</form>
I'm working with a JQuery+Ajax script that is able to fire a php script without reloading page, and insert form's data into a table in my database:
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
var formData = new FormData(this);
$.ajax({
url:'inserisciProfessionisti.php',
data: formData,
type:'POST',
async: false,
cache: false,
contentType: false,
processData: false,
success:function(data){
window.location = 'listaProfessionisti.php'
},
error:function(data){}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
Here my php code:
<?php
session_start();
session_cache_limiter('nocache');
if(!isset($_SESSION['mail'])){
header("location:login.php");
}
include("include/connect.php");
$conn=mysql_connect($HOST, $USER, $PASSWORD);
$db_ok=mysql_select_db($DB, $conn);
$nome=$_POST['nome'];
$descrizione = $_POST['descrizione'];
....
$comando="INSERT INTO professionisti('nome','descrizione',...)VALUES('$nome','$descrizione',...)";
$ris=mysql_query($comando, $conn) or die("Errore connessione database: " . mysql_error());
...
Everything works like a charm apart textarea content. It seems that textarea content wouldn't be passed to my php script.
Issue solved.
I add this onclick="tinyMCE.triggerSave(true,true);" to submit button and everything works like a charm.
I think It should be a tinyMCE bug.

Sending HTML form via AJAX to PHP server

I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html

Categories

Resources