I'm trying to submit a form via jquery so that the whole page won't reloads. I'm following the instruction on jQuery.post() guide but so far it's not working. Here's what I'm looking for to complete this task.
Submit the form to a ColdFusion proxy page and from their it will send the data as json via CFHTTP.
During the process of submitting the form, show a progress gif or status.
Somehow, hide or remove the form off of the page.
Show a success or thank you message on the page where the form used to be.
So far the form I have did not even find the values from the input. The error says that "TypeError: $form.find(...).value is not a function". Below is my JavaScript code thus far:
$(function(){
$("##frmComment##").submit(function(event){
event.preventDefault();
$("##submitResponse").append('<img src="http://st2.india.com/wp-content/uploads/2014/07/ajax-loader.gif" class="progressGif">');
// Cache $form, we'll use that selector more than once
var $form=$(this);
var data = $form.serialize(); //get all the data of form
//post it
$.post(
"/customcf/knowledgeOwl/proxyPost-KB.cfm",
data,
//console.log(response),
function(response){
// Success callback. Remove your progress gif, eg:
//$('body').removeClass('in-progress');
console.log(response);
// Remove the spining gif from the div
$("##submitResponse img:last-child").remove();
//Remove the feedback form
$("##frmComment").remove();
$form.fadeOut('slow', function(){
//Add response text to the div
$("##submitResponse").append("<h6>Thank you for your feedback.</h6>");
$("##submitResponse").html(response).fadeIn('slow');
});
});
});
})
Here's the project I've setup in JSFiddle. And here's the form.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<form data-abide id="frmComment">
<div class="row">
<div class="large-12 medium-12 columns">
<div class="row" data-equalizer>
<div class="large-4 medium-4 columns">
<div class="row">
<div class="large-12 columns">
<label>
<input type="text" placeholder="Name" name="name" required>
</label>
<small class="error">Name is required and must be a string.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>
<input type="text" placeholder="Email" name="mailfrom" required pattern='.*#.*\..{3}|.*#.*\..{2}'>
</label>
<small class="error">An email address is required.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<div class="g-recaptcha" data-sitekey="6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E"></div>
<noscript>
<div style="width: auto; height: 462px;">
<div style="width: auto; height: 422px; position: relative;">
<div style="width: auto; height: 422px; position: absolute;">
<iframe src="https://www.google.com/recaptcha/api/fallback?k=6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E" frameborder="0" scrolling="no" >
</iframe>
</div>
</div>
<div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: ##f9f9f9; border: 1px solid ##c1c1c1; border-radius: 3px; height: 100px; width: 300px;">
<textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 280px; height: 80px; border: 1px solid ##c1c1c1; margin: 10px; padding: 0px; resize: none;"></textarea>
</div>
</div>
<br /><br />
</noscript>
</div>
</div>
</div>
<div class="large-8 medium-8 columns">
<div class="row">
<div class="large-12 columns">
<textarea id="message" name="message" placeholder="Leave a comment...we love feedback!" rows="5" required></textarea>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<button type="submit" class="tiny right button">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="submitResponse"></div>
Okay, with some help, I managed to get the jQuery post to send the data to my proxyPost-KB.cfm page but it error out (505) when it hits that page. This is what I have in my proxyPost-KB.cfm page. None of the logs I setup in this CFM page is even get executed either.
<!---
Make the proxy HTTP request using. When we do this, try to pass along all of the CGI information that was made by the original AJAX request.
--->
<cflog text="CGI: #cgi#" type="Information" file="CGIparameters">
<cfhttp url="https://app.kb.com/api/head/comment.json" method="post" timeout="15" throwonerror="true">
<!---<cfhttpparam type="body" name="data"value="#serializeJSON(jsonString)#" />--->
<cfhttpparam type="url" name="_authbykey" value="56ec1f1232131c78636142d6">
<cfhttpparam type="url" name="project_id" value="55c4ffd123131c527e294fe6">
<!---<cfhttpparam type="url" name="article_id" value="#artID#">
<cfhttpparam type="url" name="content" value="#form.message#"/>
<cfhttpparam type="url" name="public_name" value="#form.name#"/>
<cfhttpparam type="url" name="public_email" value="#form.mailfrom#"/>--->
<cfhttpparam type="url" name="status" value="pending"/>
<!--- Pass along any URL values. --->
<cfloop item="strKey" collection="#URL#">
<!---<cfhttpparam type="url" name="public_name" value="#URL[strKey]#" />
<cfhttpparam type="url" name="public_email" value="#URL[strKey]#" />--->
<cflog text="URL: #URL[strKey]#" type="Information" file="CGIparameters">
</cfloop>
</cfhttp>
<!---
Get the content as a byte array (by converting it to binary,
we can echo back the appropriate length as well as use it in
the binary response stream.
--->
<cfset binResponse = ToBinary(ToBase64( objRequest.FileContent )) />
<!--- Echo back the response code. --->
<cfheader statuscode="#Val( objRequest.StatusCode )#" statustext="#ListRest( objRequest.StatusCode, ' ' )#" />
<!--- Echo back response legnth. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />
<!--- Echo back all response heaers. --->
<!---<cfloop item="strKey" collection="#objRequest.ResponseHeader#">
<!--- Check to see if this header is a simple value. --->
<cfif IsSimpleValue( objRequest.ResponseHeader[ strKey ] )>
<!--- Echo back header value. The cfheader tag generate the error "Complex object types cannot be converted to simple values"--->
<cfheader name="#strKey#" value="#objRequest.ResponseHeader[ strKey ]#" />
<cflog text="IsSimpleValue: #strKey#" type="Information" file="debugCFLoop">
</cfif>
</cfloop>--->--->
<!---
Echo back content with the appropriate mime type. By using
the Variable attribute, we will make sure that the content
stream is reset and ONLY the given response will be returned.
--->
<cfcontent type="#objRequest.MimeType#" variable="#binResponse#" />
Here's an example to do what you describe:
$("#frmComment").submit(function(event) {
event.preventDefault();
// Form has been submitted - now show your progress gif, eg:
// $('body').addClass('in-progress');
// or maybe:
// $('.spinner').show();
// etc - CSS can be whatever you want
// Cache $form, we'll use that selector more than once
var $form=$(this);
// Serialize all input from the form
var data=$form.serialize();
// Post it
$.post(
"your-proxy-url",
data,
function(response) {
// Success callback. Remove your progress gif, eg:
// $('body').removeClass('in-progress');
console.log(response); // show the proxy response on your console
// Now hide the form
$form.fadeOut('slow', function() {
// And show a result once it's gone
$(".result").html(response).fadeIn('slow');
});
}
);
});
I think you could use this code inside the $( "#frmComment" ).submit(function( event ) { function:
event.preventDefault();
var data = $('#frmComment').serialize(); //get all the data of form
var url = "yourUrl.php";
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
The PHP 'yourUrl' will recive the form inputs (you could use var_dump($_POST); to see the structure.
Related
I have form which has some inputs. I would like to show loading gif while submitting the form and hide when form is submitted.
I sent details using php and once submitted it shows response, but when submitting form, I would like to show gif as loading screen and hide when it is completed.
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#subject').val('');
$('#message').val('');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact" method="post" action="mailer.php" class="mu-contact-form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" id="name" name="name" value="Sagar Rawal" required>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Enter Email" id="email" value="searchbbc1881#gmail.com" name="email" required>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Message" id="message" name="message" required>This is message </textarea>
</div>
<button type="submit" name="submit" class="mu-send-msg-btn"><span>SUBMIT</span></button>
</form>
Okay, first of all you could use modal and add gif file on top of it. Or you can simply add the image where you want to add. Here, I will work with modal.
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
var result = $.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
});
// Here, you have to add, what you want to do right after data is sent.
$("#modal").css("display", "flex");
// Overflow of main body to hidden
$("body").css("overflow", "hidden");
result.done(function(response) {
// Now, you can hide modal or loading gif
$("#modal").css("display", "none");
// Overflow of main body to hidden
$("body").css("overflow", "auto");
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Reset form at once instead
$("#ajax-contact").reset();
});
});
});
#modal {
display: none;
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, 0.6);
justify-content: center;
align-items: center;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact" method="post" action="mailer.php" class="mu-contact-form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" id="name" name="name" value="Sagar Rawal" required>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Enter Email" id="email" value="searchbbc1881#gmail.com" name="email" required>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Message" id="message" name="message" required>This is message </textarea>
</div>
<button type="submit" name="submit" class="mu-send-msg-btn"><span>SUBMIT</span></button>
</form>
<!-- My modal for modal -->
<div id="modal">
<img width=200 src="https://thumbs.gfycat.com/BogusEmptyBrontosaurus-small.gif" alt="Loading-gif"/>
</div>
In js, I have added result as object of ajax. And, right after data are sent, we show our gif file. And, after we gave got data, we will again hide gif div. Feel free to ask!!!!!!!!
I'm using a super basic google form on my website. I'm using this website to extract the HTML to display it on my website - http://stefano.brilli.me/google-forms-html-exporter/
Once I hit submit, nothing happens. The page is just locked. I'm trying to resubmit it to another page. Here is my code
<div class="row">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSfJQ9EkDN8aggSL9AEB2PK4BGiZgBzLDbS1IPppfSkU1zy-oA/formResponse"target="_self" id="bootstrapForm" method="POST">
<div class="col-sm-6 col-md-3">
<input id="679075295" type="text" name="entry.679075295" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="897968244" type="text" name="entry.897968244" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="685661947" type="text" name="entry.685661947" class="form-control" >
</div>
<input id="503500083" type="hidden" name="entry.503500083" value="<%= #investment.id %>" >
<div class="col-sm-6 col-md-3">
<button type="submit" value"submit" class="btn btn--primary type--uppercase" >Get Started</button>
</div>
</form>
Here is the ajax script
<script>
$('#bootstrapForm').submit(function (event) {
event.preventDefault()
var extraData = {}
$('#bootstrapForm').ajaxSubmit({
data: extraData,
dataType: 'jsonp', // This won't really work. It's just to use a GET instead of a POST to allow cookies from different domain.
error: function () {
// Submit of form should be successful but JSONP callback will fail because Google Forms
// does not support it, so this is handled as a failure.
alert('Form Submitted. Thanks.')
// You can also redirect the user to a custom thank-you page:
window.location = 'http://reif.com.au/thankyou'
}
})
})
</script>
</div>
Feeling a little silly on this one. Essentially i didn't copy over all of the scripts. I was rushing through.. ALWAYS number 1 error!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js" integrity="sha256-2Pjr1OlpZMY6qesJM68t2v39t+lMLvxwpa8QlRjJroA=" crossorigin="anonymous"></script>
This is what i needed to add, it now successfully submits and redirects!
Trying to figure out why my code does not send over all POST data. The code is used on main page to get request information stored in db and used on separate page to post status updates made by me to DB. Its basically the same, except variable names.
Note: I have searched here a lot. Ive used var_dump that shows only 'content' data in the array. Im not fully comfortable with js but can follow some of it. Hence the code below is a template that Ive edited and tested on one page before trying to expand to another. Thats where the issue is. I am not sure why it works for one and not the other. Apologies if this is considered duplicate of anything, but I didnt find a good answer in similar post that would explain why.
admin.php:
<form action="insert.php" method="post" enctype="multipart/form-data">
<div class="share">
<div class="arrow"></div>
<div class="panel panel-default">
<div class="panel-body">
<div class="">
<img src="../logo.png" style="height:60px; width:60px; float:left; margin-right:3px;" />
<textarea name="content1" id="content1" cols="40" rows="10" class="form-control message" style="height: 60px; width:450px; overflow: hidden;"></textarea>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<div class="btn-group">
<select name="avatar" id="avatar" class="form-control-issue-avatar"> <----whats not sending
<option value="0" selected="selected">Author</option>
<option value="per1">P</option>
<option value="per2">W</option>
</select>
</div>
</div>
</div>
<div class="col-md-5">
<input type="submit" value="Post" class="post_button">
</div>
</div>
</div>
</div>
</form>
Here is the insert.php:
if(isSet($_POST['content1'], $_POST['avatar']))
{
$content1=$_POST['content1'];
$avatar=$_POST['avatar']; // <--- comes back NULL
$sql_in= mysqli_query($con,"SELECT comment,comment_id,status_time FROM comments order by comment_id desc");
$r=mysqli_fetch_array($sql_in);
}
and lastly the post.js that calls it:
$(function() {
$(".post_button").click(function() {
var element = $(this);
var test = $("#content1").val();
var dataString = 'content1='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content1').value='';
$("#flash").hide();
}
});
}
return false;
});
});
the var_dump etc:
Array ( [content1] => sass )
C:\wamp64\www\post\insert.php:32:
array (size=1)
'content1' => string 'sass' (length=4)
Add id attribute to the form and then use serialize() on the form to get all data from the form to pass via ajax to php
<form id='formid'>
$.ajax({
data: $('#formid').serialize(),
//other Ajax stuff
});
I am using ng-repeat, which is getting values from my db and putting it. Now i insert these values into input text which i update. Now i have a save button, which saves the updated values. I am not getting the updated values when i press the save button. Please guide me through this.
<div ng-controller="education" ng-init="getEducationDetails();">
<div class="col-md-12">
<div class="row" ng-repeat="values in education"
style="margin-left: 20px; margin-right: 20px; margin-top: 10px;">
<div class="col-md-6">
<h4>
<small>Degree</small>
</h4>
<input type="text" id="educationDegree" name="educationDegree"
value="{{values.education_degree}}" style="width: 90%;" />
</div>
<div class="col-md-6">
<h4>
<small>Year</small>
</h4>
<input type="text" id="educationYear" name="educationYear"
value="{{values.education_year}}" style="width: 100%;" />
</div>
<div class="col-md-12" style="margin-top: 10px;">
<h4>
<small>University</small>
</h4>
<input type="text" id="educationUniversity"
name="educationUniversity"
value="{{values.education_university}}" style="width: 100%;" />
</div>
</div>
</div>
<div class="col-md-12" style="margin: 20px;">
<button ng-click="educationSave();" class="btn btn-default">Save</button>
</div>
</div>
on educationSave() i save the values. But when i get the education array in the educationSave() method, i get the old array. How can i get the updated array, after i adjust some of the input types
Here is how i get the values:
$scope.getEducationDetails = function()
{
$http({
method : 'GET',
url : '/getEducationDetails'
}).success(function(data, status, headers, config) {
$scope.education = data.resultSet;
alert($scope.education);
}).error(function(data, status, headers, config) {
});
};
Here is my controller method:
$scope.educationSave = function() {
var educationArray = JSON.stringify($scope.education);
//I then save this educationArray
};
The problem is that you are not using ng-model to bind your actual input value to controller. From documentation:
HTML input element control. When used together with ngModel, it provides data-binding, input state control, and validation.
Try something like this in your markup for each input:
<input type="text" id="educationDegree" name="educationDegree"
ng-model="values.education_degree" style="width: 90%;" />
See little Demo
dynamically i generate a formular into a defined div-container and i would like grab the send-action for sending with ajax.
The generate HTML:
<div class="mhuntform">
<form action="/wp-admin/admin-ajax.php" method="POST">
<h2>Title</h2>
<p>A text</p>
<div id="form" style="padding: 5px 0px;">
<p>
<label for="email" style="display: inline-block; margin-right: 10px;">E-Mail</label>
<input type="email" name="email" id="email" placeholder="E-Mail" style="width: 60%;">
</p>
<p>
<button name="mhskl_send" id="mhskl_send">Anmelden</button>
</p>
</div>
</form>
</div>
The Formular is defined by the admin into the wordpress-page. In Javascript (jQuery) i know only the classname of the div-container (here .mhuntform). So in Javascript i try to catch the event:
// mhuntskl.options.container = '.mhuntform'
$(mhuntskl.options.container).find('form').submit(function(ev){
ev.preventDefault();
var email = $(mhuntskl.options.container).find('input[type="email"]').val();
var res = $.ajax(mhuntskl.options.ajaxurl,{async:false,data:{action:'subscribe',email:email},dataType:'json',type:'POST'}).responseText;
res = $.parseJSON(res);
if (res.success) {
$(mhuntskl.options.container).hide();
}
return false;
}
But unfortunately the submit-event will not catch and if i prints the containter with find into the console console.log($(mhuntskl.options.container).find('form')) it will received an empty object only.
What i make wrong here?
If console.log($(mhuntskl.options.container).length); is 1 and console.log($(mhuntskl.options.container).find('form').length); is 0 then there is only one possible reason. Your form is still not inside the .mhuntform div when you execute the code. Is that form generated by another javascript. If not, then is the js code wrapped in $(document).ready.