post form to iframe and echo result text on parent page - javascript

On my site I have a form that posts to an iframe, both parent and iframe window is on my page, domain, etc.
<iframe id="ifc1" style="display:none;" name="ifc"></iframe>
<div id="couponbox">
<form enctype="multipart/form-data" id="promo-form" class="form-inline" action="" method="post" target="ifc">
<div class="form-group">
<input type="text" name="..." placeholder="Enter Here" id="..." class="form-control" value="">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Apply Now" placeholder="">
</div>
</form>
</div>
The form is posting successfully, and on the iframe page there is a div that shows the alert/results.
<div id="alert" class="alert alert-success">.....</div>
I am trying to use JS or Jquery to find which text is showing in the alert (ie. fail, success, etc.), and then echo a message on the parent page.
// Attempt at a supposed solution
// reference to iframe with id 'ifrm'
var ifrm = document.getElementById('ifc1');
var base = document.getElementById('couponbox');
// using reference to iframe (ifrm) obtained above
var win = ifrm.contentWindow; // reference to iframe's window
// reference to document in iframe
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
// reference to form named 'demoForm' in iframe
var form = doc.getElementById('alert');
if (form === "Credits successfully deposited into your account") {
// Tried jQuery
$('#couponbox').append('success')
}
// jQuery attempt
if($("#ifc1").contents().text().search("successfully deposited")!=-1){
alert("found");
}
So far I haven't been able to get anything to work. Any help is appreciated.
UPDATE --
I am currently trying to use this code --
$('#ifc1').on('load', function() {
if($.trim($("#ifc1").contents().find("#alert").html()) === "Credits successfully deposited into your account"){
$("#couponbox").prepend("<b>Successfully Deposited</b>");
$("#buy").replaceWith( '<input type="submit" value="Publish" name="upsub" id="upsub" class="pubbtn action-button" placeholder="">'
} else {
$("#ifc1").contents().find("#alert").appendTo("#couponbox");
}
});
I've placed it at the end of my page. It's giving me errors with my other scripts though.
Commenting out the replacewith function, doesn't give the looping error ---
$('#ifc1').on('load', function() {
if($.trim($("#ifc1").contents().find("#alert").html()) === "Credits successfully deposited into your account"){
$("#couponbox").prepend("<b>Successfully Deposited</b>");
//$("#buy").replaceWith( '<input type="submit" value="Publish" name="upsub" id="upsub" class="pubbtn action-button" placeholder="">'
} else {
$("#couponbox").prepend("<b>Incorrect</b>");
}
});

To get the text of #alert div from iframe you can use
$(document).ready(function(){
$("#ifc1").contents().find("form#promo-form").on("submit",function(){
alert($("#ifc1").contents().find("#alert").html());
});
});
It will give you the text in #alert div.
Update
$('#ifc1').on('load', function() {
alert($("#ifc1").contents().find("#alert").html());
});
When you submit a form in iframe it also triggers load event of iframe. Check if you can get a value on load function?
Update 2
$('#ifc1').on('load', function() {
if($.trim($("#ifc1").contents().find("#alert").html()) === "success"){
alert("finish");
}
});
you can use $.trim to remove all white spaces around the string and the check if it matches with "success". TRIM

You're trying to get the contents of the form element, but you're not using innerHTML.
var ifrm = document.getElementById('ifc1');
var base = document.getElementById('couponbox');
var win = ifrm.contentWindow; // reference to iframe's window
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
var form = doc.getElementById('alert');
if (form.innerHTML.includes("Credits successfully deposited into your account")) {
$('#couponbox').append('success')
}

Related

Change button data-tooltip text using Jquery Ajax (Received from

This is my HTML code
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="ADD TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
// Same form as above
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="ADD TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
Jquery Code:
<script>
$(".addtowatchlistform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(form).children("button").css('color',data.watchlisticoncolor);
$(form).children("button").data('tooltip', data.addremove + " TO YOUR WATCHLIST"); // This line not working
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
</script>
PHP file insertwatchlist.php file
$response = new \stdClass();
$response->addremove = "REMOVE";//you can get the data anyway you want(e.g database)
$response->watchlisticoncolor = "red";
die(json_encode($response));
Output of PHP file insertwatchlist.php file
{"addremove":"REMOVE","watchlisticoncolor":"red"}
Expected Result:
1.)When someone clicks on add_box button, it submits the form without reloading the page (This one works fine)
2.) When someone clicks on add_box button, it's color changes. (works fine too)
3.) When someone click on add_box button, the data-tooltip="" value changes. (this one do not work)
So the 3rd point do not work as expected, what is wrong in my Jquery code? Console tab is empty, it shows nothing.
your jquery code should be like this
$(form).children("button").attr('data-tooltip',data.addremove + "TO YOUR WATCHLIST");
or
$('.material-icons').attr('data-tooltip',data.addremove + "TO YOUR WATCHLIST");

Google Invisible ReCaptcha not invisible

I just try to get Google Invisible ReCaptcha to work after submitting a form.
My problem is, the ReCaptcha is NOT invisible, it looks like the "old" recaptcha is popping up. I don't understand why. My site-key is for invisible recaptcha. Please help me.
First of all i'm loading the API:
<script src='https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad' async defer></script>
My form looks like this:
<form method="post" id="contact-form-face" class="clearfix" onsubmit="return false">
<input type="text" required name="name" value="name" onFocus="if (this.value == 'name') this.value = '';" onBlur="if (this.value == '') this.value = 'name';" />
<button type="submit" id="sendButton" data-size="invisible" class="g-recaptcha contact_btn" onclick="onSubmitBtnClick()" value="send" >send</button>
</form>
JS:
window.onScriptLoad = function () {
// this callback will be called by recapcha/api.js once its loaded. If we used
// render=explicit as param in script src, then we can explicitly render reCaptcha at this point
// element to "render" invisible captcha in
var htmlEl = document.querySelector('.g-recaptcha');
// option to captcha
var captchaOptions = {
sitekey: 'XXXXXXX',
size: 'invisible',
// tell reCaptcha which callback to notify when user is successfully verified.
// if this value is string, then it must be name of function accessible via window['nameOfFunc'],
// and passing string is equivalent to specifying data-callback='nameOfFunc', but it can be
// reference to an actual function
callback: window.onUserVerified
};
// Only for "invisible" type. if true, will read value from html-element's data-* attribute if its not passed via captchaOptions
var inheritFromDataAttr = true;
console.log("render now!");
// now render
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
// this is assigned from "data-callback" or render()'s "options.callback"
window.onUserVerified = function (token) {
alert('User Is verified');
console.log('token=', token);
};
// click handler for form's submit button
function onSubmitBtnClick () {
var token = window.grecaptcha.getResponse(recaptchaId);
// if no token, mean user is not validated yet
if (!token) {
// trigger validation
window.grecaptcha.execute(recaptchaId);
return;
}
var xhrData = {
'g-recaptcha-response': token
// more ajax body/data here
};
};
To make things clearer: This reCaptcha works fine, the callback loads, the verification works fine as well.... The only problem is, that this recaptcha must be invisibile, while it's not :/
I think your problem is that you are explicitly calling the render() method
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
if you want it to be invisible, you have to include this custom DIV
<div class="g-recaptcha"
data-sitekey="your_site_key"
data-callback="onSubmit"
data-size="invisible">
</div>
https://developers.google.com/recaptcha/docs/invisible
the recaptcha script will look for the div class element and bind it there, then execute the call back when the recaptcha verification is invoked.
to invoke the recaptcha verification use grecaptcha.execute();
follow the example in the googledev page, is pretty straight forward.
I hope that helped =)
I think you are missing the badge parameter in your "captchaOptions".
there are 3 possible values : bottomright (default), bottomleft and inline (which lets you customize the css of the recaptcha).
Looking at the JavaScript API docs,
https://developers.google.com/recaptcha/docs/invisible#js_api
You need to add a div with an id to render to, the class and data attributes are not required on the button element when you render the captchas with JavaScript.
Your HTML should be:
<form method="post" id="contact-form-face" class="clearfix"
onsubmit="return false">
<input type="text" required name="name" value="name" onFocus="if
(this.value == 'name') this.value = '';" onBlur="if (this.value ==
'') this.value = 'name';" />
<div id="recaptcha"></div>
<button type="submit" id="sendButton" class="contact_btn"
onclick="onSubmitBtnClick()"value="send">send</button>
</form>
And Your JS should be updated to:
// element to "render" invisible captcha in
var htmlEl = 'recaptcha'

Save form data in browser session

I have an div that is shown when a form is submitted, but when I refresh the page, my data disappears and I'm searching for a way to preserve my data on page refresh.
I know how to save data in a session, but not an entire form. How do I approach this issue? Is it even possible to save an entire form with Javascript?
function showHide() {
var div = document.getElementById("hidden_form");
if (div.style.display == 'none') {
div.style.display = '';
} else {
div.style.display = 'none';
}
}
<form name="product_form" id="product_form" enctype="multipart/form-data" action="admin_products.php" method="post" accept-charset="utf-8" onsubmit="showHide();
return false;">
<input type="textfield" id="title" name="title" value="" readonly>
<div id='hidden_form' style="display:none">
<input type="text" id="name" name="name" value="" placeholder="Product Name">
<label id="option_1" name="option_1">Option Name</label>
<input type="text" id="optionn" name="optionn" value="" placeholder="Product Name">
</div>
<input type="submit" id="add" name="add" value="Save" class="" <!--onclick="myFunction()-->">
When you hit submit, you'll reload the page and lose your data. By using localStorage and JSON.stringify() you are able to save the data locally in your browser and fetch it when you load your page.
Since localStoragecan only store strings, you'll have to convert your object to a string. That's where JSON.stringify() comes into play. And when you fetch it, you can use JSON.parse() to convert it back to an object.
$("#btnSubmit").click(function() {
var data = {};
data.Text = $("#myText").val();
data.isProcessed = false;
localStorage.setItem("myData", JSON.stringify(data));
});
//On load
var data = localStorage.getItem("myData");
var dataObject;
if (data != null) //There's stored data
{
dataObject = JSON.parse(data);
$("#myText").val(dataObject.Text)
localStorage.removeItem("myData"); //Remove data, otherwise it'll be there for a long time.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form method="post">
<input type="text" id="myText" />
<button type="submit" id="btnSubmit">Submit</button>
</form>
</div>
More information on localStorage: W3Schools
More information on JSON.stringify and JSON.parse: MDN
I don't know if the snippet will work, since it'll submit a post. Copy this snippet and try it on your local system.
EDIT
As I made a tiny mistake myself, I updated my snippet. But as I suspected, SO doesn't allow access to localStorage.
And ofcourse, you'll have to put this code in your $(document.ready(function() { ... }); for it to work. I did forget to add a <form></form> to my HTML snippet. And I just tested it on my local system and it's working fine.
You can try with localStorage. It's key-value storage that all modern browsers have. There're simple libraries to write to localStorage with fallback to cookies if you need old browser support (written by javascript instead of server side scripts).
I'll give you an example with localStorage:
//emulating that the form was showed (save clicked) and the value true stored on the localStorage
localStorage.setItem('displayedForm', true);
//initializing the state of the page
initialize();
function showHide() {
var div = document.getElementById("hidden_form");
if (div.style.display == 'none') {
div.style.display = '';
localStorage.setItem('displayedForm', true);//if the conditions are meet to display the form, store it on the localStorage
} else {
div.style.display = 'none';
localStorage.setItem('displayedForm', false);//if the conditions are **NOT** meet to display the form, store it on the localStorage as well
}
}
function initialize() {
if (localStorage.getItem('displayedForm') === true || localStorage.getItem('displayedForm') === 'true') {
var div = document.getElementById("hidden_form");
div.style.display = '';
}
}
Working Fiddle: https://jsfiddle.net/y0uep73e/
Facing this problem myself, I wrote a simple library to automatically handle saving and loading form data via local storage: https://github.com/FThompson/FormPersistence.js
Example which saves data upon unload and loads data upon load:
<script src='https://cdn.jsdelivr.net/gh/FThompson/FormPersistence.js#1.0.1/form-persistence.min.js' type='text/javascript'></script>
<script type='text/javascript'>
window.addEventListener('load', () => {
let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm)
})
</script>

Jquery on page load not working

I am doing a Get Request in PHP to get a certain value, I am then taking this value and inputting it into a textfield's value, I have that text-fields value then call a json request.
It works on input and change, but on page load. Here is the code below:
$(document).ready(function() {
var runningRequest = false;
var request;
$('input#asd3').on('load', function(e) {
var $q = $(this);
if(runningRequest){
request.abort();
}
runningRequest=true;
var myString = self.location.href;
var mySplitResult = myString.split("?");
request = $.getJSON('search',{q:$q.val()},function(data){
showResults(data,$q.val());
showResults2(data,$q.val());
runningRequest=false;
});
});
});
The html
<input type="text" id="asd3" name="asd3" value="<?php echo $name ?>" class="form-control" autocomplete="off" placeholder="Search Name..." class="input-block-level" placeholder="Search..." style="width:100%; display:none;" />
https://developer.mozilla.org/en-US/docs/Web/Events/load
The load event is primarily related to elements that pertain to external resources. The window document, images, iframes, etc. An input element does not rely on anything like that and would not have a load event.
If you want the logic to happen on 'page' load then you should bind to the window or document. Try changing...
$('input#asd3').on('load', ...
to
$(document).on('load', ...

Submit form interfering with others

I have this email subscribe form for newsletter which gets delivered to me by email using PHP. It is located in footer which means that it is available on all pages across the website.
JSFIDDLE DEMO
Form works ok now but the problem is that it is interfering with other parts of website where forms are included - it messes those up and causes error to show on other fields as well.
My question is how do I isolate this form and script only for this part of the code so it will be defined only for this part of the webpage? What am I doing wrong?
As noted in the comments above,, you need to replace the "id" attributes in the html with "class" attributes. Then, modify your jQuery finders to search by class, constrained within the #subscribe form.
The HTML
<form id="subscribe" name="subscribe" action="#" method="post">
<input name="email" type="email" class="email" placeholder="Your e-mail adresss">
<span><button class="send" type="button">Subscribe</button></span>
</form>
And the Javascript
$(document).ready(function () {
$("#subscribe").submit(function () {
return false;
});
$("#subscribe .send").on("click", function () {
$('#subscribe input.error').removeClass('error');
var emailval = $("#subscribe .email").val();
var mailvalid = validateEmail(emailval);
if (mailvalid == false) {
$("#subscribe .email").addClass("error");
}
var minlen = $('#subscribe input[minlength]').filter(function(){
return this.value.length < +$(this).attr('minlength')
}).addClass('error').length;
if (mailvalid == true && minlen == 0) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>");
$.ajax({
//you shouldn't need to change what you had here in the Fiddle; I didn't
//copy it for brevity's sake
});
}
});
});

Categories