I am trying to create a form that has an action to a URL. But it requires ajax submission first and then it should submit to the action.
It should send me an email (within the newsletter.php).
<script type='text/javascript'>
$(function () {
$("#signup").on('submit', function( e, response ) {
if (response.errors == false) {
$.ajax({
type : 'GET',
url : 'newsletter.php',
data: {
name : $('#os0').val(),
email: $('#os1').val()
},
success : function(data) {
$('#subscribe').submit();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
// error handling
}
});
return false;
}
return true;
});
});
</script>
HTML
<form name="signup" id="signup" action="" method="GET">
<input type="text" id="os0" name="Email" />
<input class="text" id="os1" type="text" name="cd_FULLNAME" />
<input type="Submit" name="Submit" id="subscribe" value="Subscribe" />
</form>
<script type='text/javascript'>
$(function () {
$("#signup").on('submit', function( e, response ) {
$.ajax({
type : 'GET',
url : 'newsletter.php',
data: {
name : $('#os0').val(),
email: $('#os1').val()
},
success : function(data) {
$("#signup")[0].submit();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
// error handling
}
});
return false;
});
});
</script>
Note the difference between $("#signup")submit(); and $("#signup")[0].submit();.
Related
The following code is working fine when the form is submitted correctly with all valid data in the first attempt. If there is any server side error after submitting the form then when user resubmits the form the recaptcha does not reset.
Following is the sample code:
html-form
<script src="https://www.google.com/recaptcha/api.js"></script>
<div>
<form name="signupForm" method="POST" action="/signup">
<div class="form-group mobile-number">
<input type="tel" id="mobileNo" class="form-control" name="mobileNumber" maxlength="10"
autofocus>
<label for="mobile"> Your Mobile no. </label>
</div>
<div class="g-recaptcha"
data-sitekey="{key}"
data-callback="setResponse"
data-badge="inline"
data-size="invisible">
</div>
<input type="hidden" id="captcha-response" name="captcha-response"/>
<button id="submitButon" type="submit">Sign me up!</button>
</form>
</div>
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function setResponse(response) {
document.getElementById('captcha-response').value = response;
submitForm();
}
function submitForm() {
var $form = $("form");
var data = JSON.stringify($form.serializeObject());
var myJsonObject = JSON.parse(data);
data = JSON.stringify(myJsonObject);
$.ajax({
type: "POST",
url: "dummy url",
contentType: "application/json",
xhrFields: {withCredentials: true},
data: data,
success: function (data, textStatus, request) {
// success
},
error: function (xhr, err) {
// logics here
grecaptcha.execute();
setResponse;
}
});
}
</script>
<script>
jQuery(document).ready(function () {
//homepage form
$('form[name="signupForm"]').validate({
onfocusout: function (element) {
$(element).valid();
},
rules: {
mobileNumber: {
required: true,
minlength: 10,
maxlength: 10
}
},
// Specify validation error messages
messages: {
mobileNumber: "A valid mobile number is of 10-digit",
},
//submit handler
submitHandler: function (form) {
submitForm();
}
});
});
</script>
I think the error is in ajax call but not able to figure out why the captcha is not resetting again.
I want it to only "reload" into the #searchuserc. I have searched so much information but I can't solve the problem.
$(document).ready(function() {
$("#onlineusers").load("online.php");
$("#searchuserc").show();
setInterval(function() {
$("#onlineusers").load("online.php");
}, 5000);
$(".search").click(function() {
$("#onlineusers").hide();
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'searchuser.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data) {
$('#searchuserc').fadeOut('slow', function() {
$('#searchuserc').fadeIn('slow').html(data);
});
})
.fail(function() {
alert('Ajax Submit Failed ...');
});
});
});
this is my HTML file
<form method="POST">
<input type="text" id="searchuser" name="searchuser" placeholder="Sök efter en användare..." />
<input type="submit" class="search" name="searchbtn" value="Sök" />
</form>
<div id="searchuserc">
</div>
Instead of
$(".search").click(function() {
...
use
$(".search").closest("form").submit(function(e) {
...
Code inside the handler can stay the same.
I have two radio buttons. When I click into one of them to change the form fields, the captcha version 1 does not show anymore.
So, I have to click the refresh button to generate a new captcha image.
<input type="radio" name="data[Form][sv]" id="FormV1" value="1" /> V1
<input type="radio" name="data[Form][sv]" id="FormV2" value="2" checked="checked" /> V2
The jquery code is:
$(document).ready(function () {
$("#FormV1").bind("change", function (event) {
$.ajax({async:true,
beforeSend:function (XMLHttpRequest) {
$('#loading').show();
},
complete:function (XMLHttpRequest, textStatus) {$('#loading').hide()},
data:$("#FormularioSituacaoVeiculo1").closest("form").serialize(),
dataType:"html",
evalScripts:true,
success:function (data, textStatus) {
$("#search").html(data);},
type:"post",
url:"\/mysite\/theurl\/"});
return false;
});
$("#FormV2").bind("change", function (event) {
$.ajax({async:true,
beforeSend:function (XMLHttpRequest) {
$('#loading').show();
},
complete:function (XMLHttpRequest, textStatus) {
$('#loading').hide()
},
data:$("#FormV2").closest("form").serialize(),
dataType:"html", evalScripts:true, success:function (data, textStatus) {
$("#search").html(data);
},
type:"post",
url:"\/mysite\/url\/"});
return false;
});
function showRecaptcha(element) {
Recaptcha.create('hjfsdjklsdjklfsdjklfsdjklfjksdl', element, {
lang : 'en-gb',
theme : 'custom',
custom_theme_widget: 'recaptcha_widget',
callback: Recaptcha.focus_response_field
}
);
}
showRecaptcha('recaptcha_div');
How can I switch the form fields (V1 to V2) and generate the captcha automatically without having to click on the refresh button?
Today the captcha is not generated when I do click on the radio button. So I have to click on the refresh button to regenerate a captcha image.
Please check this working example (I have tried my best to make this example as close as possible to your situation):
$('input[name="data[Form][sv]"]').change(function(e) {
$.ajax({
async: true,
beforeSend: function(XMLHttpRequest) {
$('#loading').show();
},
complete: function(XMLHttpRequest, textStatus) {
$('#loading').hide()
},
data: $(this).closest("form").serialize(),
evalScripts: true,
success: function(data, textStatus) {
$("#search").html(data);
Recaptcha.reload();
},
dataType: "html",
type: "POST",
url: "https://httpbin.org/post"
});
return false;
});
function showRecaptcha(element) {
Recaptcha.create('6Ld3TPkSAAAAAPckREYZuVQ6GtjMQsD-Q5CkzNxj', element, {
lang: 'pt-BR',
theme: 'white',
custom_theme_widget: 'recaptcha_widget',
//callback: Recaptcha.focus_response_field
});
}
$(function() {
showRecaptcha('recaptcha');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<div id="recaptcha"></div>
<h4>Radio Inputs: </h4>
<form>
<input type="radio" name="data[Form][sv]" id="FormV1" value="1" />V1
<input type="radio" name="data[Form][sv]" id="FormV2" value="2" checked="checked" />V2
</form>
<h4>Ajax Post Result <span style="display:none" id="loading">Loading...</span>: </h4>
<div id="search">
</div>
Refresh codes are what you are looking for?
for v1:
Recaptcha.reload();
for v2:
grecaptcha.reset();
handleCommentSubmit:function(comment)
{
console.log('pohach gaye bhaiyaa');
var request = {
'request':{
'ActorSId':667275,
'ParentPostId':null,
'PostStatus':null,
'Action':'Operate',
'PostRecipients':[],
'PostRecipientsAction':'DonotOperate',
'PostAttributes':[],
'PostAttributesAction':'DonotOperate',
'PostTags':[],
'PostTagsAction':'DonotOperate',
'PostAssetAttachments':[],
'PostAssetAttachmentsAction':'DonotOperate',
'PostContent':[{comment:""}],
'PostContentAction':'DonotOperate'
}
};
$.ajax({
url:'http://kmserver28:3535/Alto/Post/PostWS.asmx/AddKonnectPost',
dataType:'json',
type:'POST',
data:JSON.stringify(request),
success:function(data){
this.state.data.push(data);
this.setState({data:this.state.data})
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
var CommentForm = React.createClass({
myFunction:function(e)
{
console.log('9999999999999999999999');
e.preventDefault();
var comm =(React.findDOMNode(this.refs.text).value.trim());
console.log(comm);
this.props.onCommentSubmit(comm);
**
// i'm trying to call the function handleCommentSubmit() from here and
// it is giving error as : "Object expected". Request structure is in the above function**
},
render:function(){
return(
<form className="commentForm" onSubmit={this.myFunction}>
<input className="inputText1" type="text" placeholder="Please Enter Your Comment Here ...." ref="text" /><br /><br />
<input className="Submit1" type="submit" value="Post" />
</form>
);
}
});
contentType: 'application/json; charset=utf-8',
Adding this line inside the ajax request simply did the trick,
Sorry for inconvenience.
Hello everyone I am newbie in java-script so i hope you can help me with my issue. So I have the form, it look something like this:
<form method="post">
Field1: <input type="text" name="field1"><br>
Field2: <input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
I need to take data from the form and make xml request, the xml request should look like this
<root>
<header section>
<section>data</section>
</header section>
<data section>
<field1>data</field2>
<field2>data</field2>
</data section>
</root>
After that i have to display xml response on the page.
I made xml request
<script>
$('.button').click( function() {
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
success: function(xml) {
$(xml).find('root').each(function(){
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
But I don't know how to take data from the form and make request. Can you help me with it? Thanks a lot.
// You can use jQuery to build XML document:
function buildXmlFromForm(form) {
var xml = $('<XMLDocument />');
xml.append (
$('<header-section />').append(
$('<section />').text('data')
)
).append (
$('<data-section />').append(
$('<field1 />').text(form.find("input[name='field1']").val())
).append(
$('<field2 />').text(form.find("input[name='field2']").val())
)
);
return xml.html();
}
// you should use POST or PUT method (not GET) to post xml-data to server side
$( "#form1" ).submit(function(event) {
event.preventDefault();
$("#results").append("<ul></ul>");
var xmlString = buildXmlFromForm($(this));
$("#xmlSrc").val(xmlString);
$.ajax({
type: "POST",
dataType: 'xml',
url: 'response.xml',
data: xmlString,
success: function(respData) {
$("<li></li>").html("ok: "+respData).appendTo("#results ul");
console.log(respData);
},
error: function(errorData) {
$("<li></li>").html("error: "+errorData.statusText).appendTo("#results ul");
console.log(errorData);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form1">
Field1: <input type="text" name="field1" value="***v1***"><br/>
Field2: <input type="text" name="field2" value="***v2***"><br/><br/>
<input type="submit" value="Submit">
</form>
<hr/>
<textarea id="xmlSrc" cols="70" rows="5"></textarea>
<div id="results"/>
Try this:
serialize will return formData of current form
You must have unique identifier for your form to be used as querySelector
$('#myForm').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
data: formData,
success: function(xml) {
$(xml).find('root').each(function() {
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="myForm">
Field1:
<input type="text" name="field1">
<br>Field2:
<input type="text" name="field2">
<br>
<input type="submit" value="Submit">
</form>