How convert this jquery object - javascript

Hello I use the jquery library for the first time.
Jquery:
function habdleProductSubmitRequest(event) {
//no reload page
event.preventDefault()
var productId = $(this).find('[name="id"]').val();
var productName = $(this).find('[name="name"]').val();
var productPrice = $(this).find('[name="price"]').val();
$.ajax({
url:'/api/ajaxrest/post' ,
method: 'POST',
processData: false,
contentType:"application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
id: productId,
name: productName,
price : productPrice
}),
complete: function(result){
console.debug(result)
$('#result3').text(result);
}
})
}
form
<h2>Add a new task</h2>
<form
class="datatable__row datatable__row--add"
method="POST"
action="http://localhost:8080/v1/task/createTask"
data-product-add-form=""
>
<fieldset class="datatable__row-section datatable__row-section--input-section">
<label class="datatable__input-label">
Product Id
</label>
<input type="text" name="id" placeholder="Insert a task name" th:required="required" />
</fieldset>
<fieldset class="datatable__row-section datatable__row-section--input-section">
<label class="datatable__input-label">
Task name
</label>
<input type="text" name="name" placeholder="Insert a task name" th:required="required" />
</fieldset>
<fieldset class="datatable__row-section datatable__row-section--input-section">
<label class="datatable__input-label">
Task content
</label>
<textarea name="price" placeholder="Insert task content" th:required="required"></textarea>
</fieldset>
<fieldset class="datatable__row-section datatable__row-section--button-section">
<button type="submit" data-task-add-button="" class="datatable__button">Add a task</button>
</fieldset>
</form>
<fieldset>
<span id="result3"></span>
</fieldset>
I do not know how to display this returned object. This function does not display me in the view of this object
$('#result3').text(object);
I tried:
$('#result3').text(object.name + object.price);
but displayed nothnig. so I checked this object using consol.debuger and here is a screenshot

There is no name nor price on that object. It says so on your screen-shot. There is however responseJSON, with name and price. So why not use those? (I also added space between the two, but you should format those as you like/need)
$('#result3').text(object.responseJSON.name + " " + object.responseJSON.price);

Related

JS - recaptcha v3 - how to verify captcha and submit form data to another file

I'm just starting with JS and like to implement a form that verifies for robots/humans by using captcha v3 on the client side and if verification succeeds the data should be submitted to another file.
This is what I got so far. I know it's wrong, but unsure what the correct logic is. Hope someone can shed a light. Thx!
<script src="https://www.google.com/recaptcha/api.js?render=6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></script>
<script type="text/javascript" src="/js/libs/jquery-1.11.3.min.js"></script>
<section class="cc-column-component regular-grid">
<form id="bank-form" class="form clear one-full cf-contact-form" action="?" method="POST" data-tracking="contact_sales">
<div>
<label class="label mandatory bank-color bank-label" for="firstName">First Name</label>
<input id="firstName" value="Pepe" type="text" class="one-full bank-color-grey bank-input" name="firstName" placeholder="First Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getFirstName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="lastName">Last Name</label>
<input id="lastName" value="Chanches" type="text" class="one-full bank-color-grey bank-input" name="lastName" placeholder="Last Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getLastName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="email">Email</label>
<input value="asdf#asdf.com" id="email" type="text" class="one-full bank-color-grey bank-input" name="email" placeholder="Email" autocomplete="off" data-validate="true" data-type="email" value="<?php isset($this) ? print $this->getEmail() : print ''; ?>">
<br/>
</div>
<div class="row inline one-full">
<br/>
<!-- <div class="g-recatpcha" data-sitekey="6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></div> -->
<button type="submit"
id="form-submit"
value="submit"
>
<a>Submit form</a>
</button>
<div class="field inline one-full">
<br/>
</div>
<!-- <input type="hidden" name="recaptcha_response" id="recaptchaResponse"> -->
</div>
</form>
</section>
<script>
$('#bank-form').submit(function(event) {
console.log('subtmitting');
event.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ', {action: 'submit'}).then(function(token) {
console.log('🚀 ~ grecaptcha.execute ~ token', token)
$('#bank-form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('#bank-form').prepend('<input type="hidden" name="action" value="submit">');
// $('#bank-form').unbind('submit').submit();
});;
});
CheckCaptcha(token)
});
function CheckCaptcha(token) {
var token = $("#token").val()
console.log('🚀 ~ token', token)
var action = $("#action").val()
var RECAPTCHA_V3_SECRET_KEY = "6Lc3UZkeAAAAAIG8bVZDpkheOxM56AiMnIKYRd6z"
$.ajax({
type: "POST",
url: "http://www.google.com/recaptcha/api/siteverify",
data: JSON.stringify([{secret: RECAPTCHA_V3_SECRET_KEY }, {response : token }]),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// __doPostBack('form-submit', '');
if(response["score"] >= 0.7) {
console.log('Passed the token successfully');
}
},
failure: function (response) {
// set error message and redirect back to form?
console.log('Robot submit', response);
}
})
return false;
}
</script>

Cannot get/set IFormFile object from <input> tag of View

I have an upload mechanism which looks like that in the View:
<div method="post" enctype="multipart/form-data">
<input type="hidden" id="ProjectId" name="ProjectId" value="#Model.ProjectId"/>
<input type="hidden" id="Name" name="Name" value= "" />
<input type="hidden" id="Id" name="Id" value="" />
<div class="col-md-10">
<div class="form-group">
<input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
<input type="submit" value="Upload" id="UploadInputFileButton" onclick="UploadInstallIntructions();"/>
</div>
</div>
</div>
This is my uploadinstructions() method, which gets called when the user pushes the 'Upload'button.
script>
function UploadInstallIntructions() {
var name = document.getElementById('SoftwareVersionName').value;
var id = document.getElementById("Id").value;
var iFormFile = document.getElementById("ChooseInputFile").files[0];
$.ajax({
type: "POST",
url: '#Url.Action("UploadInputFile", "SoftwareVersion")',
data: { projectId: #Model.ProjectId, Name: name, Id: id, inputFile: iFormFile},
cache: false,
success: function (response) {
window.location.href = response;
}
});
return data;
}
</script>
So this is a simple ajax call that calls a method on my controller with the specified arguments. My problem is that the last argument which should be the file data, of IFormFile type, so that I can work with it in my controller, doesn't get set. Is there a better way I can bind my IFormFile object in my view? Normally just the line :
input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
should have worked to bind the IFormFile.
Edit: Not a duplicate of how to append whole set of model to formdata and obtain it in MVC, because my question was not about binding with FormData, but IFormFile not automattically getting created from the View.
Once i have done upload a image file like this..
$('input[type="file"]').ajaxfileupload({
'action': 'uploadFile.jsp',
'cache': false,
'onComplete': function(response) {
$('#upload').hide();
BootstrapDialog.show({
title: 'Alert!',
message: 'Image Upload Successfully',
buttons: [{
label: 'Ok',
action: function(dialog) {
dialog.close();
}
}]
});
var img_src = "../profilepic/" + response;
setTimeout(5000);
$("#image").attr("src", img_src);
},
'onStart': function() {
$('#upload').show();
}
});
<input type="file" name="datafile" accept="image/*"/><br/>
<div id="upload" style="display:none;">Uploading..</div>
If you wish to upload files like this, visit this link for
jQuery.AjaxFileUpload.js
Try below code:
<form name="UpdateInstall" id="UpdateInstall" method="post" enctype="multipart/form-data">
<input type="hidden" id="ProjectId" name="ProjectId" value="#Model.ProjectId"/>
<input type="hidden" id="Name" name="Name" value= "" />
<input type="hidden" id="Id" name="Id" value="" />
<div class="col-md-10">
<div class="form-group">
<input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
<input type="submit" value="Upload" id="UploadInputFileButton" onclick="UploadInstallIntructions();"/>
</div>
</div>
</form>
<script>
function UploadInstallIntructions() {
var formData = new FormData($("#UpdateInstall")[0]);
$.ajax({
type: "POST",
url: '#Url.Action("UploadInputFile", "SoftwareVersion")',
data: formData,
processData: false,
contentType: false,
success: function (response) {
window.location.href = response;
}
});
return data;
}
</script>

JQuery serialize ajax loaded form

The serialize() function returns an empty string , This is my code :
Code to return form :
$.ajax({
url: 'api/form',
type: 'get',
crossDomain: true,
}).done(function(response){
fields = JSON.parse(response);
html = '';
$.each(fields, function(index,field){
html += field;
});
html += '<div class="btn-clear"></div><button class="btn payment">Pay</button></div>';
$("#cart-content").html(html);
}).fail(function() {
console.log('Failed');
});
Javascript code executed after user clicks payment button :
$("body").on('click','.payment',function() {
var frmData = $("#customer").serialize();
console.log(frmData);
});
But it log an empty string !!
The form after it's ajax loaded :
<form id="customer"><div class="form-group">
<label class="control-label">Full name</label>
<input name="name" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">E-mail</label>
<input name="email" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Mobile</label>
<input name="mobile" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Country</label>
<select id="country" name="country" class="form-control" type="text"><!-- countries ... --></select>
</div></form>
Try your serialize like this
$("#form").submit(function () {
var data = $('#form').serialize();
Use the form ID as the target. Here I used #form. Submit the form, serialize the forms inputs.

Avoid Refreshing page submiting the form

Whenever using this form that I made (in Portuguese), refreshing removes all previously entered data from the page. Why does this happen, and how can I fix it? Thank you for your time.
<script type="text/javascript">
function submitForm(){
// Initiate Variables With Form Content
var nome = $("#nome").val();
var email = $("#email").val();
var telefone = $("#telefone").val();
var assunto = $("#assunto").val();
var mensagem = $("#mensagem").val();
$.ajax({
type: "POST",
url: "send-contact2.php",
data: "nome=" + nome + "&email=" + email + "&telefone=" + telefone + "&assunto=" + assunto + "&mensagem=" + mensagem,
cache:false,
success: function (data) {
alert(data);
}
});
}
</script>
<form id="myForm">
<div class="col col-md-6">
<input type="text" name="nome" id="nome" required value="" tabindex="1" placeholder="Nome">
<input type="text" name="email" id="email" required value="" tabindex="2" placeholder="E-mail">
<input type="text" name="telefone" id="telefone" required value="" tabindex="2" placeholder="Telefone">
<select id="assunto" name="assunto" required>
<option value="outros">Outros assuntos</option>
<option value="encomendas">Encomendas</option>
</select>
</div>
<div class="col col-md-6">
<textarea name="mensagem" id="mensagem" cols="29" rows="8" placeholder="Mensagem"></textarea>
</div>
<div class="col col-md-12 ">
<button name ="submit" type="submit" onclick="return submitForm();">Enviar</button>
</div>
</form>
Your function also needs to return false to stop the click event behaviour from submitting the form:
function submitForm(){
// your code...
return false;
}
Better still, hook to the submit event of the form directly and do away with the clunky onclick handlers, and use serialize() to gather the form data for you:
<button name="submit" type="submit">Enviar</button>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault(); // stop form submission
$.ajax({
type: "POST",
url: "send-contact2.php",
data: $(this).serialize(),
cache: false,
success: function (data) {
alert(data);
}
});
}
});
</script>
Try to change onClick action to onSubmit and add return false after method. Like this:
<button name ="submit" type="submit" onsubmit="submitForm(); return false;">Enviar</button>
Good practice will be add method="POST" to your form attributes.

Form doesn't submit on callback

I am trying to send an e-mail after an ajax call has been successfully completed. I do not have access to the file that I am making the AJAX call to.
I am preventing the first submit, making the ajax call and submitting the form again upon competition. When doing this, I can't seem to figure out why I have to press the submit button twice for the email to be sent.
Here is my code:
"use strict";
var submitted = '';
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
email = $('#email').val(),
phone = $('#primaryPhone').val(),
weight = $('#weight').val(),
origin = $('#originPostalCode').val(),
destination = $('#destinationPostalCode').val(),
notes = $('#whatsTransported').val()
if( submitted != 1 )
{
e.preventDefault();
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
crossDomain: true,
dataType: "json",
data: {"key": "my secret key","first": firstName, "last": lastName, "email": email, "phone": phone, "weight": weight, "origin_postal": origin, "dest_country": destination, "note": notes }
})
.done(function(data){
if(data[1][0][0] == 2)
{
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
})
.fail(function(data) { console.log(data); });
}
submitted = '1';
});
});
Here is the form HTML
<form action="<?php echo bloginfo($show='template_url').'/includes/form-email.php'; ?>" class="span6 offset1" id="quote" method="post">
<div class="row formRow">
<div class="firstName span3">
<label for="firstName"><?php _e('First Name:','StreamlinedService'); ?></label>
<input type="text" name="firstName" id="firstName">
</div>
<div class="lastName span3">
<label for="lastName"><?php _e('Last Name:','StreamlinedService'); ?></label>
<input type="text" name="lastName" id="lastName">
</div>
</div>
<div class="row formRow">
<div class="email span3">
<label for="email"><?php _e('Email Address:','StreamlinedService'); ?></label>
<input type="text" name="email" id="email">
</div>
<div class="primaryPhone span3">
<label for="primaryPhone"><?php _e('Phone Number:','StreamlinedService'); ?></label>
<input type="text" name="primaryPhone" id="primaryPhone">
</div>
</div>
<div class="row formRow">
<div class="weight span2">
<label for="weight"><?php _e('Weight (lbs):','StreamlinedService'); ?></label>
<input type="text" name="weight" id="weight">
</div>
</div>
<div class="row formRow">
<div class="originPostalCode span3">
<label for="originPostalCode"><?php _e('Origin:','StreamlinedService'); ?></label>
<input type="text" name="originPostalCode" id="originPostalCode">
</div>
<div class="destinationPostalCode span3">
<label for="destinationPostalCode"><?php _e('Destination:','StreamlinedService'); ?></label>
<input type="text" name="destinationPostalCode" id="destinationPostalCode">
</div>
</div>
<div class="row">
<div class="whatsTransported span6">
<label for="whatsTransported"><?php _e('What can we help you transport?','StreamlinedService'); ?></label>
<textarea name="whatsTransported" id="whatsTransported" rows="5"></textarea>
</div>
<input type="hidden" name="formType" value="quote" />
<input type="hidden" name="siteReferer" value="<?php echo $blog_id ?>">
<input type="submit" id="submit" name="submit" value="<?php _e('Get Freight Quote','StreamlinedService') ?>" class="btn btn-primary btn-large span3 offset3" style="float:right;">
</div>
</form>
My question is two-fold: Is there a more efficient way to do this? If not, why isn't this working?
Just use the .submit directly on the form node (note the [0])
$('#quote #submit').submit();
becomes
$('#quote')[0].submit();
this bypasses the jQuery bound event and forces a postback.
You use the wrong approach to Jquery
You miss the key : Write Less Do More, the heart of JQuery.
Anyway try this:
"use strict";
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var tis = $(this);
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
cache: true,
dataType: "json",
data: tis.serialize(),
success: function(data){
if(data[1][0][0] == 2){
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
},
error: function(data){console.log(data);}
});
e.stroPropagation();
e.preventDefault();
});
});
Last thin.. you CAN'T request a remote page that's not hosted on the same domain of the script.. For that ther's This answer

Categories