post data on WebAPI after save in php Using ajax - javascript

I have created the code for save data in my custom table using Ajax which is working fine.
After that I want to post these data on the asp.Net API using js/jQuery. How I can post same data on the aps.net.
Here is my HTML form and JS code:
<div id="inline1" class="audit-form" style="display: none;">
<form class="infusion-form" id="infusion-form">
<h3 style="color: #002046;">Sign Up For a Free Capability Audit </h3>
<div class="dis_block clearfix">
<div class="form-group">
<label>First Name *</label>
<input required class="form-control" id="inf_field_FirstName" name="inf_field_FirstName" type="text" />
</div>
<div class="form-group">
<label>Last Name *</label>
<input required id="inf_field_LastName" name="inf_field_LastName" type="text" class="form-control" />
</div>
<div class="form-group">
<label>Email *</label>
<input required id="inf_field_Email" name="inf_field_Email" type="email" class="form-control" />
</div>
<div class="form-group">
<label>Confirm Email *</label>
<input required id="inf_field_Phone1" name="inf_field_Phone1" type="email" class="form-control" />
</div>
<div class="form-group" style="text-align: center;">
<input type="hidden" name="action" value ="save_procurement_data" />
<input type="submit" id="frm_basic_info" class="btn custom-btn" value="NEXT" />
</div>
</div>
</form>
</div>
JS Code is here
<script type = "text/javascript">
jQuery(document).ready(function() {
jQuery(document).on('click', '#frm_basic_info', function(e){
jQuery("#infusion-form").validate({
rules: {
inf_field_FirstName: "required",
inf_field_LastName: "required",
inf_field_Email: "required",
inf_field_Phone1: {
equalTo: inf_field_Email
}
},
messages: {
inf_field_FirstName: "Please enter your firstname",
inf_field_LastName: "Please enter your lastname",
inf_field_Email: "Please enter your email",
inf_field_Phone1: "Please enter your confirm email correct",
},
submitHandler: function (form) {
e.preventDefault();
var frmd = new FormData();
var save_data = jQuery('form').serializeArray();
jQuery.each(save_data,function(key,input){
frmd.append(input.name,input.value);
});
jQuery.ajax({
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: frmd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
return false;
//window.location.href = "<?php echo site_url(); ?>/about-your-organization";
}
});
}
});
});
});
</script>
In the alert I getting alert data saved success fully.

Simply add one more ajax method after saving in your php Url.
See, in your above ajax success method, check the status then post to Asp.Net Web Api, just like my bellow code,
success: function(data){
//Here you can check the data and call your Web Api. For example
if(data == "data saved success fully")
{
//Write an ajax method to post data to Web Api
$.ajax({
url: 'YourWebApiUrlHere',
data: frmd,
type:'Post',
success: function (data) {
//Show an alert message here that data saved in Web Api blah blah
if(data == "Your response from Web Api goes here")//Edit this message
alert("Data saved using Web Api");
else
alert("Failed to save data using Web Api");
}
error: function(xhr, status, error) {
alert(xhr.responseText); //This is the exception if any issue with server
}
})
}
else
alert("Your data haven't saved in Php Url. Check with server");
return false;
}
Hope it helps!

Related

Ajax JQuery request doesn't get sent

It used to work fine, and I don't remember changing anything in these files, but now nothing happens when I click on submit form. What may cause the problem?
Snippet:
// And here's the ajax request file *auth_ajax.js*:
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $('form').serialize(),
success: function(response) {
if (response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
<!-- Here's my php file: -->
<h1 id="header">Enter your data here</h1>
<form>
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This route work?
url: 'check_user.php',
Try yourDomain/check_user.php, check your directory for a real path

Cannot POST / error when clicking Submit button

I am developing a login page for our mobile app using Phone gap. But whenever I clicked the Submit button, an error 'Cannot POST /' appears. Why is that so? Please see my code below.
index.html
<body>
<div class="main-info2">
<h3>Sign In</h3>
<div class="in-form">
<form id="login_form" method="post"">
<input type="text" placeholder="Username" required=" " id="email" />
<input type="password" placeholder="Password" required=" " id="password" />
<div class="check-sub">
<input type="submit" value="Login" id="login">
</div>
</form>
</div>
</div>
<div class="copy-right">
<p>Design by W3layouts</p>
</div>
</div>
<!-- //main -->
</body>
login.js
$(document).ready(function(){
do_login();
});
function do_login() {
$("#login").click(function () {
var email = $('#email').val();
var password = $('#password').val();
var dataString="email="+email+"&password="+password+"&login=";
if($.trim(email).length>0 & $.trim(password).length>0){
$.ajax({
type: 'POST',
url: "http://localhost:1234/cleverpro/login.php",
dataType: 'json',
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").html('Connecting...');},
success: function(data){
if(data == "success"){
console.log("hay nako!");
alert("hala");
}else if(data == "failed"){
$("#login").html('Login');
console.log("hastang sayupa");
alert("halajud");
}
}
});
}else{
return false;
console.log("walay sulod uy");
}
});
}
login.php
<?php
include "db.php";
if(isset($_POST['login'])){
$email=mysql_real_escape_string(htmlspecialchars(trim($_POST['email'])));
$password=mysql_real_escape_string(htmlspecialchars(trim($_POST['password'])));
$login=mysql_num_rows(mysql_query("select * from `user` where `email`='$email' and `password`='$password'"));
if($login!=0){
echo "success";
}else{
echo "failed";
}
}
?>
I didn't know where did I gone wrong with this. Please help me.
First of all it would be better to use on('submit', handler) instead on click. (see Whats the difference between onclick and onsubmit?)
When you clicks "Login", default form send action happens after your javascript code finishes. It means that form POST happens to 'action' of your form that is not set in your form and is '/' by default.
You need to preventDefault action, somethink like this
$('#login_form').on('submit', function(e) {
e.preventDefault();
//Your code
});

MailChimp Ajax Integration

I am trying to custom mailchimp signup form.
I want to the form not got to the mailchimp landing page, after the form submit. I want it reload the form and display the message, if the submission success or failed.
I have tried what have been discussed on https://stackoverflow.com/a/15120409, but it is failed.
This my html & javascript for the form :
//newsletter -start
var $form = $('#mc-embedded-subscribe-form');
if ( $form.length > 0 ) {
$('form button[type="submit"]').bind('click', function ( event ) {
if ( event ) event.preventDefault();
register_newsletter($form);
return false;
});
}
function register_newsletter($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: {EMAIL:.find('#mce-EMAIL').val()},
//data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result == "success") {
$( "#mc-embedded-subscribe-form .form-group, #mc-embedded-subscribe-form button" ).remove();
$( "#mc-embedded-subscribe-form" ).append('<p>Pendaftaran Anda berhasil.</p>');
} else {
$( "#mc-embedded-subscribe-form .form-group, #mc-embedded-subscribe-form button" ).remove();
$( "#mc-embedded-subscribe-form" ).append('<p>Pendaftaran anda <strong>gagal</strong>.</p>');
}
}
});
}
//newsletter -end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-sub">
<div class="row">
<div class="col-md-24 col-sm-24 col-xs-24">
<div id="mc_embed_signup">
<p><strong>Daftar & Dapatkan VOUCHER 75,000<br/>serta penawaran spesial dari MatahariMall</strong></p>
<form action="http://mataharimall.us10.list-manage.com/subscribe/post-json?u=ce402de87bc4303ab82a36695&id=912ec37292&c=?" class="form-search-opps" id="mc-embedded-subscribe-form" method="post" name="mc-embedded-subscribe-form" novalidate="" role="search" target="_blank">
<div class="form-group">
<input class="form-control" id="mce-EMAIL" name="EMAIL" placeholder="Masukkan email Anda di sini" type="text" value="" />
</div>
<button class="btn btn-red pria" id="mce-GENDER-0" name="GENDER" type="submit" value="Pria">Pria</button>
<button class="btn btn-red wanita" id="mce-GENDER-1" name="GENDER" type="submit" value="Wanita">wanita</button>
</form>
</div>
</div>
</div>
</div>
If success, mailchimp will produce this :
?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."})
If failed, mailchimp will produce this :
?({"result":"error","msg":"0 - An email address must contain a single #"})

How to validate form fields and post the form data to server using JQuery and Ajax?

I am trying to validate form fields like, Name (must not be blank), Email_id(must be valid), Mobile(Must be valid). After the filling the all info I have to send this information to server, and redirect response to different page. Here nothing is working,
my form.html
<form class="form-horizontal" id="scheduleLaterForm" name="scheduleLaterForm">
<div class="col-lg-8">
<div class="fieldgroup">
<label class="col-lg-3 control-label" for="userName">Name:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style=" height: 30px;" class="form-control" id="userName" name="userName"
placeholder="Full Name" value="" type="text" required>
</div>
</div>
<div class="fieldgroup">
<label for="email" class="col-lg-3 control-label">Email:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style="height: 30px;" class="form-control" name="email"
id="email" placeholder="you#example.com" value=""
type="text" required>
</div>
</div>
<div class="fieldgroup">
<label for="userContactNumber" class="col-lg-3 control-label">Mobile:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style="height: 30px; width:100%;" class="form-control" id="userContactNumber"
name="userContactNumber" placeholder="Mobile Number"
onkeypress="enableKeys(event);" maxlength="10" type="text" required>
</div>
</div>
<div class="fieldgroup">
<label class="col-lg-3 control-label"></label>
<div class="col-lg-7">
<input type="submit" value="Register" id="btnBooking" class="submit">
</div>
</div>
</div>
</form>
script for validating form and sending data
<script>
$(document).ready(function(){
$("#scheduleLaterForm").validate({
rules: {
userName: "required",
email: {
required: true,
email: true
},
userContactNumber: "required"
},
messages: {
userName: "Please enter your Name",
userContactNumber: "Please enter your Mobile number",
email: "Please enter a valid email address",
},
submitHandler: function(form) {
// get values from textboxs
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('#userContactNumber').val();
$.ajax({
url:"http://localhost/services/bookService4Homes.php",
type:"GET",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
alert("success");
//alert(JSON.stringify(response));
},
error: function(err){
alert("fail");
//alert(JSON.stringify(err));
}
});
return false; // block regular submit
}
});
});
</script>
Php code
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","root");
mysql_select_db("service4homes");
if(isset($_GET['type']))
{
if($_GET['type']=="booking"){
$name = $_GET ['Name'];
$mobile = $_GET ['Mob_Num'];
$mail = $_GET ['Email'];
$query1 = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mobile','$mail')";
$result1=mysql_query($query1);
}
}
else{
echo "Invalid format";
}
?>
You do not need an external click handler because the plugin automatically captures the click (of a type="submit") and blocks the submit.
You need an input or button in your form that is type="submit", otherwise the plugin will not be triggered at all.
You cannot have an external .ajax function while you have form.submit within the submitHandler of your .validate() method. This means the plugin is trying to submit the form while your click handler is trying to use ajax. They both cannot work at the same time. As per docs, any ajax belongs inside the submitHandler, and it's "the right place to submit a form via Ajax after it is validated".
You don't need to check form validity because when you use the built in submitHandler, this is also done automatically.
The jQuery4U code is nothing but complicated junk; everything can be simplified greatly. It serves no useful purpose other than to cause more confusion to those seeking guidance. It comes from a popular, yet poorly explained, online demo/tutorial by Sam Deering that is linked to/from many places.
$(document).ready(function(){
$("#register-form").validate({
rules: {
userName: "required",
email: {
required: true,
email: true
},
userContactNumber: "required"
},
messages: {
userName: "Please enter your Name",
userContactNumber: "Please enter your Mobile number",
email: "Please enter a valid email address",
},
submitHandler: function(form) {
// get values from textboxs
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('#userContactNumber').val();
$.ajax({
url:"http://192.168.1.11/services/bookService4Homes.php",
type:"POST",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
//alert(JSON.stringify(response));
},
error: function(err){
//alert(JSON.stringify(err));
}
});
return false; // block regular submit
}
});
});
DEMO: http://jsfiddle.net/mh6cvf2u/

Pass an image through AJAX [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:
Here's the form :
<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label col-md-4" for="societe">Company</label>
<div class="col-md-8">
<input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
<div class="col-md-8">
<textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
</div>
</div>
<div class="form-group" id="input_file">
<label class="control-label col-md-4" for="image_input_field">Logo</label>
<div class="col-md-8">
<div class="input-group uploaddiv">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Parcourir <input type="file" id="image_input_field" name="file">
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="form-actions col-md-9 col-md-offset-3 text-right">
<input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
<input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
</div>
</div>
</fieldset>
</form>
I can't seem to find what's the error in my code ! Here's the AJAX call :
jQuery(document).on("click", "#submit", function(e) {
e.preventDefault();
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
jQuery.ajax({
url: "ajax.php",
type: "post",
data: {
'file': file,
'module' : 'ajax_data_form',
'societe': societe,
'message': message
},
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// jQuery('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
});
And here's the ajax.php:
<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
var_dump($_FILES);
}
$.ajax({
type: "POST",
url: pathname,
data: new FormData($('#devis')[0]),
processData: false,
contentType: false,
success: function (data) {
$("#divider").html(data);
}
});
and get the file data normally in $_FILES[];. Because FormData is automatically handles the multipart header in an ajax request.
can you try it
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "file="+file,
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// $('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
}); });
</script>
In ajax.php
just write
echo 'something';
As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.
You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).
Here is the link:
https://github.com/dogzworld/iframe-post-form
Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."
As mentioned you can send response from the server and display updates on your webpage accordingly.
There has to be a demo page but it is not working as of now.
You can also use it for file uploads.
Calling Example:
jQuery('#frmId').iframePostForm({
json : true,
post : function () {
//return true or false
return true;
},
complete : function (response) {
//complete event
console.log(response);
}
});
Using a Jquery Plugin Called Jquery Form plugin Link
I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.
$("#devis").ajaxSubmit(options);
return false;
The you can easily get the file in the php page like this
$ImageTempname = $_FILES['ImageFile']['tmp_name'];
$ImageFilename = $_FILES['ImageFile']['name'];
$ImageType = $_FILES['ImageFile']['type'];
and so on.....

Categories