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', ...
Related
Here's what I'm essentially trying to do:
<input type="text" class="form-control" value="window.location.hash">
What's the proper way to insert the window.location.hash into the input's value?
Note: I've found several ways to do this when people are required to click a button, but nothing that explains how to do it automatically when the page loads.
You'll need to assign this after the page loads, or at least the element
<input type="text" class="form-control" id="hash" value="">
<script>
window.onload=function() {
document.querySelector("#hash").value = window.location.hash
}
</script>
Just get the element and change its value using JavaScript. In this Snippet, I'm redirecting to a different hash, just for example purposes.
const input = document.querySelector("input.form-control");
// Redirect to different hash for example
window.location.hash = "abcdef";
input.value = window.location.hash;
<input type="text" class="form-control" />
You need JS script for that:
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('location');
input.value = window.location.host; // change .host to .hash
})
<input id="location">
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')
}
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>
I've got some code that sends an ajax request when a form is being submitted. This works the first time the form is submitted (it's a search module), but only once. I've added an effect to highlight the table when data is returned, and you can only see it once (the data changes only once as well).
When I look at the response in the chrome dev tools, I can see it contains the data of the new search query but this isn't shown. Why can I only display results once?
JS:
$(function () {
// Creates an ajax request upon search form submit
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-nn-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect("highlight");
});
// Prevent default action
return false;
};
$("form[data-nn-ajax='true']").submit(ajaxFormSubmit);
});
HTML:
<form method="GET" action="#Url.Action("Index", "Show")" data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
<div class="input-append mysearch">
<input type="search" class="span5 search-query" name="query" data-nn-autocomplete="#Url.Action("AutoComplete")" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="contentlist">
#Html.Partial("_Shows", Model)
</div>
I think you should use html() instead of replaceWith() method:
$target.html($newHtml);
just an idea... try
$target.html(data);
instead of
$target.replaceWith($newHtml);
By replaceWith, you might actually remove the div that you want to fill your content in. Then, the second time, it doesnt find the div to insert the content into.
In the window.onbeforeunload event is there a way to detect if the new request is a POST (on the same page) or a GET (going to a page)? It would also be great to see the new document.location.
window.onbeforeunload = winClose;
function winClose() {
//Need a way to detect if it is a POST or GET
if (needToConfirm) {
return "You have made changes. Are you sure you want?";
}
}
This is how I just did it:
$(document).ready(function(){
var action_is_post = false;
$("form").submit(function () {
action_is_post = true;
});
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (!action_is_post)
return 'You are trying to leave this page without saving the data back to the server.';
}
});
Sounds like something you'd need to attach to a form, or specific links. If the event is raised by a link, and there is a request string full of variables, it will act as a GET. If it's a form, you'll have to check the METHOD, and then figure the URL based on the data being submitted in the form itself.
No method
GET method
<form method="GET" action="thisPage.php">
<!-- This is a GET, according to the method -->
<input type="text" name="usrName" value="jonathan" />
</form>
<form method="POST" action="thisPage.php">
<!-- This is a POST, according to the method -->
<input type="text" name="usrName" value="jonathan" />
</form>
So the detection would take place not in the window method, but in the click method of your links, and form submissions.
/* Check method of form */
$("form").submit(function(){
var method = $(this).attr("method");
alert(method);
});
/* Check method of links...UNTESTED */
$("a.checkMethod").click(function(){
var isGet = $(this).attr("href").get(0).indexOf("?");
alert(isGet);
});