Google reCAPTCHA reset multiple captchas rendered by function call - javascript

I have many reCAPTCHA's who are rendered dynamically, sometimes there are 2 sometimes 50 depends on page.
I've done rendering with this:
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
var CaptchaCallback = function(){
$('.g-recaptcha').each(function(index, el) {
grecaptcha.render(el, {'sitekey' : 'myKey'});
});
};
And placed this where I want captcha to be displayed:
<div class="g-recaptcha" data-sitekey="myKey"></div>
I've got ajax call, that submits form data to process.php, and if form data isn't verified returns custom errors
$.ajax({
type : 'POST',
url : 'process.php',
data : $(this).serialize(),
dataType : 'json'
})
.done(function(data) {
if ( ! data.success) { ...
It works as intended, but now I want to show message to user as part of validation, if he forgot to solve captcha.
With
var response = grecaptcha.getResponse();
if(response.length == 0){
$('.result').append('Captcha incorrect, please click I am not robot');
}
and to reset captcha add this bellow
if ( ! data.success) {
grecaptcha.reset();
What does it do is: reset captcha if user didn't completed all forms valid.
This all works only on 1st occurrence of reCAPTCHA.
And I need it to somehow tell it to reset only captcha that is currently in use.
My best guess was to try with
var form = $(this); //get current form
grecaptcha.reset(form);
It won't work, since i need widget ID, and not form.
Can you assist me pls?

All credits to https://stackoverflow.com/a/41860070/7327467
reset is done with
var form = $(this); //store current form
var response = grecaptcha.getResponse(jQuery(form).find('#data-widget-id').attr('data-widget-id'));
if(response.length == 0){ //append error to result div
form.find('.result').append('<div class="alert alert-danger">' + "Captcha incorrect" + '</div>'); }
and to reset recaptcha, I've added this instead previous "grecaptcha.reset();"
grecaptcha.reset(jQuery(form).find('#data-widget-id').attr('data-widget-id'));
Hope this helps.

Related

How do I submit this form without page reload?

So basically I have this interest slider plugin that calculates the repayments on a loan over a certain period of time - https://loancalc.000webhostapp.com/
But the problem I am having is submitting the form without reloading the page, currently you enter your name and email.
I have included this ajax script on line 1146 of slider.js but the slider continues to reload the page when submitting the form.
I am told it could be because i'm not enqueuing the script (for wordpress) properly.
jQuery('.qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else if (email == ""){
$("input#youremail").focus;
return false;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}});
The full code is here (slider.js, quick-interest-slider.php, register.php) - https://github.com/Curnow93/quick-interest-slider/tree/master/quick-interest-slider
There's no submit event on the input. It should be on the form. Also, you need to pass the event to the callback function.
jQuery('.qis_form').on('submit', function(event) {
Also your selector doesn't select anything. I have updated it using the right selector.

codeigniter: I can't change view page

I'm having some problems changing the view page in the code. Note: i'm using ajax.
This is part of the controller function called "insert_inventario" after the information is saved in array_db it compares with the inventario_model and the result "true" or "false" is saved in obj_inv.
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
if($obj_inv){
$edit_view = $this->load->view(base_url()."inventario/edit",$array_db,TRUE);
$response = array('mensaje' => $edit_view,
);
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}
This is part of the view page called create, this is the submit button that executes the Javascript code that execute the controller function
<input type="submit" class="btn btn-danger" id="btn_enviar" value="Guardar">
The javascript Function
$("#btn_enviar").click(function(){
var r = confirm("Make sure the information you fill is correct");
if (r == true){
var url = base_url + "/inventario/insert_inventario";
$.ajax({
type: "POST",
url: url,
data: $("#form_inventario").serialize(),
success: function(data)
{
$("#contenido").html(data.mensaje);
}
});
}
return false;
});
The problem is, when i fill the form and press submit, the message box appears and when I click accept, it does nothing. I'm burning my brain so much to understand what I'm doing wrong, please help me.
The main problem is a error called jquery-2.1.4.min.js:4 POST http://161.196.112.19:8080/Inventario_Remedy/inventario/insert_inventario 500 (Internal Server Error) it happens when the code try to insert the array
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
So, in order to fix this, you have to check your database values and keep trying.

Laravel 5 attach with Ajax?

I have this laravel code in my controller detach function.
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return view('products.tagsdelete', [
'products' => $product,
]);
This works fine, it deletes the tag realation from my pivot table. The only thing that bugs me it that I don't want to reload the page everytime I press the delete button on my view.
( Of course I could make a selection of all tags the user want to delete, but I want to to this live with Ajax )
My problem is, I couldn't find anything that helps me with detachment from laravel + Ajax. I'm quite okay with Javascript and Jquery but Ajax is still a new thing for me..
So can anybody help me there? I'm really stuck.
Thanks for taking your time :)
#Wiriya Rungruang
current controller code:
public function detach()
{
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
}
my button:
<button type="submit" class="delete-tag-btn" data-product_id="{{ $product->id }}" data-tag_id="{{ $tag->id }}"><i class="glyphicon glyphicon-trash"></i></button>
at the bottom of the code the JS:
<script>
$(".delete-tag-btn").on('click', function(){
var url = "{{ route('detach') }}"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
alert("success");
});
});
</script>
First : You should create function detach tag from product in your controller and return status success or failure(or nothing)
In your controller
function detachTag(){
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return "Some state for checking it a success or not";
}
Second : Create javascript function for checking when you click on delete button send request with parameter to function that we created in the first step and rerender or remove that tag from your HTML page
**Parameter is mean product_id and tag_id that your want to detach it
In your js
$(".delete-tag-btn").on('click', function(){
var url = "localhost/deletetag?"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
// Do what you want
});
});
So when you click on .delete-tag-btn It will send request for detach it
While you can right a simple ajax call, send data and return html and replace it with the old html
lets begin :)
first step is to write ajax, and send it when form is submit or any button is clicked (as per your code)
this one is sample ajax, just fill in your data in it.
var BASEURL = window.location.origin + "/your_domain_name/";
$.ajax({
url: BASEURL + "your_route",
type: "POST/GET", //any_one
data: {
// Your data comes here (object)
},
beforeSend: function () {
},
success: function (response) {
console.log(response); // your html in return
},
complete: function (response) {
}
});
now a call will be send with your data to controller respective to specified route you mentioned, processing will be normal.
It will return only html. You can do whatever you want with this html.
One important problem you might face if considering these instructions is, right now the view you are returning is probably of whole page (because the page is been refresh every time), but if you are thinking to replace it with new html, your will only have to return that part of the page may be a single row or something like that. So break your view in many sub views. Php #include(//path) (blade) might come handy. Thats how I use to work. :)

Use jScript / AJAX to call PHP script but ONLY if form has been submitted?

This is kind of a follow up to this question.
I have this code:
var chpass = function()
{
var pass1 = encodeURIComponent($("#pass1").val());
var pass2 = encodeURIComponent($("#pass2").val());
$.ajax(
{
type: "POST",
url: "lib_ajax/somescript.php",
data: "pass1="+ pass1+"&pass2="+ pass2,
success: function(msg_pass)
{
$("#status_pass").ajaxComplete(function(event, request, settings)
{
if(msg_pass == 'empty pass1')
{
$("#pass1").removeClass('green');
$("#pass1").addClass("red");
}
});
}
});
}
$("#signup").ready(chpass);
$("#signup").change(chpass);
And in the php script:
$pass1 = trim($_POST['pass1']);
if(!isset($pass1)||empty($pass1)) die('empty pass1');
My problem is that I don't want the form to be validated with ready() the first time the page is loaded but every time the page is loaded after a submit.
I have tried to figure out how to set a default event for the handler and then use preventDefault but I've been completely unsuccessful so far.
Could part of the problem be that when the page is submitted some additional validation happens on the server and in some cases I use header('Location: ') to reload the page?
Any tips how I can work this out? Is there a way to change it to something like:
if ( FORM IS SUBMITED ) $("#signup").ready(chpass);
Or maybe:
if ( FORM IS SUBMITED && msg_pass == 'empty pass1')
{
$("#pass1").removeClass('green');
$("#pass1").addClass("red");
}
Can also add that I have tried to change ready() to submit() with no luck:
$("#signup").submit(chpass); // DO NOT WORK
I finally found a solution. Change the code:
$("#signup").ready(chpass);
to:
<?php if(isset($_POST['submit'])) { ?>$("#signup").ready(chpass);<?php } ?>
and that part of the jScript is left out unless the form is submitted!

Save 2 Forms At the Same Time MVC 3

Im planning to save 2 forms but the 1st form is where i get the Foreign key for the Second form
This is my Attempt to save this Using Javascript
$("#btnSave").click(function (e) {
e.preventDefault();
$('#workForm').submit();
$('#conttForm').submit();
});
But it errors on Contact Form Submit because the ID of Worker Form is still null while saving the contact form that is its Foreign Key
i also Tried this method
$("#btnSave").click(function (e) {
e.preventDefault();
if (Id != 0) {
$('#workForm').submit();
$('#contForm').submit();
} else {
$('#workForm').submit(); }
});
But it only go at Else because the ID is 0
I hope someone can help me here
Thanks :D
jQuery's submit function actually causes the browser to send a request, i.e. you're submitting the form. To accomplish this you'll need to uses ajax. Something like this should do the trick:
$.ajax({
method: 'POST',
url: $('#workForm').attr('action'),
data: $('#workForm').serialize(),
success: function(data) {
//grab whatever id you need here
var id_thing = $(data).find('#id_here').val();
//do something with id
$('#conttForm input[name="your-hidden-id-field"]').val(id_thing);
$('#conttForm').submit();
}
})

Categories

Resources