form fill and submit without waiting for an event? - javascript

Using http://en.allexperts.com/q/Javascript-1520/create-form-submit-fly.htm as reference, I create the following form and it can be submitted by an onclick event or any other user-event? Is there a way to execute this when the page loads or do I have to wait for the user event always?
<script>
var params = something
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
var newElement = document.createElement("<input name='"+elementName+"' type='hidden'>");
inputForm.appendChild(newElement);
newElement.value = elementValue;
return newElement;
}
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
createNewFormElement(submitForm, "field1", params.data1);
createNewFormElement(submitForm, "field2", params.data2);
submitForm.name= "submitpost";
submitForm.action= "some URL";
submitForm.submit();
}
</script>

If I understood correctly you want to do something like the following. Right?
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var params = ["1","7"];
createFormAndSubmit();
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
var newElement = document.createElement("INPUT");
newElement.name = elementName;
newElement.type = 'hidden';
newElement.value = elementValue;
inputForm.appendChild(newElement);
return newElement;
}
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
createNewFormElement(submitForm, "field1", params[0]);
createNewFormElement(submitForm, "field2", params[1]);
submitForm.name= "submitpost";
submitForm.action= "show.jsp";
submitForm.submit();
}
});
</script>

Related

How to refer on dynamically created variables

I want to know if it is possible to refer to an dynamically created variables and if yes how?
I create on this site many forms which have p elements on the bottom is one button and if I click that button I want to transmit the variable(IdJB) which was created specific in this form.
I marked the variable with a command in the code.
$(document).ready(function() {
var Id = sessionStorage.getItem('Id');
var status = 0;
var nummer = 0;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
status: status
},
success: function(data) {
var anzahl = data;
status = 1;
while (anzahl > nummer) {
nummer++;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
nummer: nummer,
status: status
},
success: function(data) {
var Daten = JSON.parse(data);
var Ausgabebereich = document.getElementById('main');
var IdJB = Daten.id;
window.IdJB = IdJB; //This Variable !!!!!!!!!!!!!
var f = document.createElement("form");
var pInhalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.inhalt);
pInhalt.appendChild(Inhalt);
f.appendChild(pInhalt);
var pDatum = document.createElement('p');
var Inhalt = document.createTextNode(Daten.datum);
pDatum.appendChild(Inhalt);
f.appendChild(pDatum);
var pUhrzeit = document.createElement('p');
var Inhalt = document.createTextNode(Daten.uhrzeit);
pUhrzeit.appendChild(Inhalt);
f.appendChild(pUhrzeit);
var pGehalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.gehalt);
pGehalt.appendChild(Inhalt);
f.appendChild(pGehalt);
var pDauer = document.createElement('p');
var Inhalt = document.createTextNode(Daten.dauer);
pDauer.appendChild(Inhalt);
f.appendChild(pDauer);
var pAdresse = document.createElement('p');
var Inhalt = document.createTextNode(Daten.adresse);
pAdresse.appendChild(Inhalt);
f.appendChild(pAdresse);
var pNam_ersteller = document.createElement('p');
var Inhalt = document.createTextNode(Daten.nam_ersteller);
pNam_ersteller.appendChild(Inhalt);
f.appendChild(pNam_ersteller);
var bInhalt = document.createElement('button');
var Inhalt = document.createTextNode("Senden");
bInhalt.appendChild(Inhalt);
bInhalt.setAttribute("type", "button");
bInhalt.setAttribute("onclick", "zuJB()");
f.appendChild(bInhalt);
Ausgabebereich.appendChild(f);
$(document).on('click', 'button', function() {
sessionStorage.setItem('IdJB', IdJB); //Here !!!!!!!!!!!!!
alert(IdJB);
window.location = "http://localhost/jQuery&PHPnew/JobBlock.html";
});
}
})
}
}
})
$("#sub").click(function() {
window.location = "http://localhost/jQuery&PHPnew/Markt.html";
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jobs</title>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<button id="sub">Update</button>
Alle Jobs
Meine Jobs
Einstellungen
<main id="main">
</main>
</body>
</html>
This is how the Programm looks like
Don't use a global variable. Put IdJB in an attribute of the button. You can use the jQuery .data() method for this.
Also, don't add the event handler every time through the loop. When you use event delegation, you should just add the handler once.
$(document).ready(function() {
$(document).on('click', 'button', function() {
var IdJB = $(this).data("IdJB");
sessionStorage.setItem('IdJB', IdJB);
alert(IdJB);
window.location = "http://localhost/jQuery&PHPnew/JobBlock.html";
});
var Id = sessionStorage.getItem('Id');
var status = 0;
var nummer = 0;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
status: status
},
success: function(data) {
var anzahl = data;
status = 1;
while (anzahl > nummer) {
nummer++;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
nummer: nummer,
status: status
},
success: function(data) {
var Daten = JSON.parse(data);
var Ausgabebereich = document.getElementById('main');
var IdJB = Daten.id;
window.IdJB = IdJB; //This Variable !!!!!!!!!!!!!
var f = document.createElement("form");
var pInhalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.inhalt);
pInhalt.appendChild(Inhalt);
f.appendChild(pInhalt);
var pDatum = document.createElement('p');
var Inhalt = document.createTextNode(Daten.datum);
pDatum.appendChild(Inhalt);
f.appendChild(pDatum);
var pUhrzeit = document.createElement('p');
var Inhalt = document.createTextNode(Daten.uhrzeit);
pUhrzeit.appendChild(Inhalt);
f.appendChild(pUhrzeit);
var pGehalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.gehalt);
pGehalt.appendChild(Inhalt);
f.appendChild(pGehalt);
var pDauer = document.createElement('p');
var Inhalt = document.createTextNode(Daten.dauer);
pDauer.appendChild(Inhalt);
f.appendChild(pDauer);
var pAdresse = document.createElement('p');
var Inhalt = document.createTextNode(Daten.adresse);
pAdresse.appendChild(Inhalt);
f.appendChild(pAdresse);
var pNam_ersteller = document.createElement('p');
var Inhalt = document.createTextNode(Daten.nam_ersteller);
pNam_ersteller.appendChild(Inhalt);
f.appendChild(pNam_ersteller);
var bInhalt = document.createElement('button');
var Inhalt = document.createTextNode("Senden");
bInhalt.appendChild(Inhalt);
bInhalt.setAttribute("type", "button");
bInhalt.setAttribute("onclick", "zuJB()");
f.appendChild(bInhalt);
$(bInhalt).data('IdJB', IdJB);
Ausgabebereich.appendChild(f);
}
})
}
}
})
$("#sub").click(function() {
window.location = "http://localhost/jQuery&PHPnew/Markt.html";
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jobs</title>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<button id="sub">Update</button>
Alle Jobs
Meine Jobs
Einstellungen
<main id="main">
</main>
</body>
</html>
I may be misunderstanding your question, but if not: In order to reference dynamically created elements, the click handler just needs to be instantiated after the element is created and put in the DOM. An easy way to handle this is by having a function generate your tag like so:
function appendTag(parent, child){
parent.append(child)
child.click(function(){
//Click code here
});
}
So it looks like when you are adding the button click event dynamically you are adding it to all the buttons on the page. This is why when you click one it runs 3 times.
This can be seen by the button text in this line of code:
$(document).on('click', 'button', function() {
.....
});
To address this problem you need to make the click listener specific to the button. You can do that by making a more specific button selector. Although it's not a perfect solution one way to do this is to give each button a unique I'd. Something like button-## where ## here is a different number each time you create a new button. You can then do:
$(document).on('click', '#button-##', function() {
.....
});
Again replacing ## with the corresponding Id value.
Edit: actually you can use the answer #Laif posted by rather than using the $(document).on( call just simply do b.click()

Discord Webhook Embeds with JavaScript POST Requests

I tried to create an embed message using a discord webhook and a javascript post method.
Here's the method I use:
function requestWithoutAjax( url, params, method ){
params = params || {};
method = method || 'post';
// function to remove the iframe
var removeIframe = function( iframe ){
iframe.parentElement.removeChild(iframe);
};
// make a iframe...
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.onload = function(){
var iframeDoc = this.contentWindow.document;
// Make a invisible form
var form = iframeDoc.createElement('form');
form.method = method;
form.action = url;
iframeDoc.body.appendChild(form);
// pass the parameters
for( var name in params ){
var input = iframeDoc.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = params[name];
form.appendChild(input);
}
form.submit();
// remove the iframe
setTimeout( function(){
removeIframe(iframe);
}, 500);
};
document.body.appendChild(iframe);
}
When I try to call this method with this JSON: {"content":"Some message"} the webhook sends "Some message" into my discord chat.
But when I try to use an embed (https://discordapp.com/developers/docs/resources/webhook#execute-webhook & https://discordapp.com/developers/docs/resources/channel#embed-object), with this JSON: {"embeds":[{"title":"A title","description":"A description","color":3447003}]} it just doesn't send the embed message.
Am I formatting the JSON wrong, or is it something other?
Maybe someone of you can solve my problem.

Form validation does nothing to the form, NO HTML, ONLY JS

I am trying to learn JS so i am writing code only in JS (there is only up to the body tag in my html code that uses the script).
I am trying in the condition mentioned above, to write a login form and validate it with a validation function.
For some reason nothing happens when I submit the form (I believe its not even calling the validate function, since I put an alert in the beginning of it).
My code:
function validateLogin() {
alert("CHECK");
var username = document.getElementById('username').value;
var pass = document.getElementById('pass').value;
if (username === "admin" && pass === "admin") {
return true;
} else {
alert("Wrong username or password!");
return false;
}
}
var loginDiv = document.createElement('div');
loginDiv.className = 'loginDiv';
var loginForm = document.createElement('form');
loginForm.className = 'loginForm';
loginForm.onsubmit = "return validateLogin()";
var username = document.createElement('input');
username.id = 'username';
var pass = document.createElement('input');
pass.id = 'pass';
pass.type = 'password';
var subm = document.createElement('input');
subm.type = 'submit';
loginForm.appendChild(document.createTextNode("Username:"));
loginForm.appendChild(username);
loginForm.appendChild(document.createElement('br'));
loginForm.appendChild(document.createTextNode("Password:"));
loginForm.appendChild(pass);
loginForm.appendChild(document.createElement('br'));
loginForm.appendChild(subm);
loginForm.action = "#";
loginForm.method = "post";
loginDiv.appendChild(loginForm);
document.body.appendChild(loginDiv);
edit I found that changing
loginForm.onsubmit = "return validateLogin()";
into
loginForm.onsubmit = validateLogin;
solved it for me, for some reason.
First of all you're targeting the DOM object, not the value.
Instead of:
var username = document.getElementById('username');
use:
var username = document.getElementById('username').value;
Of course this is not a good way to build an authentication system, but since it's for learning purposes, we'll go on with it. I would also not recommend using all these "appendChild" functions to create HTML.
There are better ways of doing it. Look into things like MuschacheJS and how they do rendering.
Edit:
You also need to call the function validateLogin();
You could do it like this:
document.getElementById("submitButton").addEventListener("click", function(e) {
validateLogin();
});
This code assumes that there is a button with id submitButton, but you already know how to create that.
Change your button code to the following:
var subm = document.createElement('button');
subm.innerHTML = 'click me';
subm.onclick = validateLogin();
subm.type = 'submit';
Your onsubmit attribute is not added to your form. To fix this, use .setAttribute as you can see in the code below.
A second problem is, that you don't get the value of your input fields, but the full node. For that, you need to append .value.
If you don't want that the page reloads (or redirects to any page given in the action attribute of your form when true login credentials, prepend event.preventDefault() to your validateLogin().
function validateLogin() {
alert("CHECK");
var username = document.getElementById('username').value;
var pass = document.getElementById('pass').value;
if(username === "admin" && pass ==="admin"){
return true;
} else{
alert("Wrong username or password!");
return false;
}
}
var loginDiv = document.createElement('div');
loginDiv.className = 'loginDiv';
var loginForm = document.createElement('form');
loginForm.className = 'loginForm';
// .setAttribute() allows to set all kind of attributes to a node
loginForm.setAttribute("onsubmit", "return validateLogin()");
var username = document.createElement('input');
username.id = 'username';
var pass = document.createElement('input');
pass.id = 'pass';
pass.type = 'password';
var subm = document.createElement('input');
subm.type = 'submit';
loginForm.appendChild(document.createTextNode("Username:"));
loginForm.appendChild(username);
loginForm.appendChild(document.createElement('br'));
loginForm.appendChild(document.createTextNode("Password:"));
loginForm.appendChild(pass);
loginForm.appendChild(document.createElement('br'));
loginForm.appendChild(subm);
loginForm.action = "#";
loginForm.method = "post";
loginDiv.appendChild(loginForm);
document.body.appendChild(loginDiv);

How to retrieve input value before submit

I have to retrieve three input values before submitting so I can use ajax to fill in the form depending on the information inside these boxes.
I first check that the three boxes have text using this script:
<script>
jQuery(document).ready(function () {
var flag = false;
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
var direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
}
});
});
</script>
What I need is that when these three fields have a value to retrieve that value so I can pass it through a URL in PHP before submitting (ajax maybe?)
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$value .'&sensor=false';
$value would be the variable (direccion) which is in the script.
If you need more information please let me know.
You need to set the variable as global to access it outside.due to declaring it in change, the scope of variable remains within change function only. so declare the variable outside change event.like this:
<script>
jQuery(document).ready(function () {
var flag = false;
var direccion="";//declare variable
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');//define variable on every on change
}
});
});
</script>
On your form you can add an onsubmit attribute which will define an action to take when the form is submitted.
eg :
<form method='GET' action='' onsubmit='doAjax();return false;'>
<input type='text' id='inp_name' value='hello'/>
</form>
<script>
function doAjax(){
alert("this form won't be posted!");
return false;
}
</script>
you need to make a ajax call to the url which is constructed
jQuery(document).ready(function () {
var flag = false;
jQuery(".validation").change(function () {
flag = true;
var direccio="";
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
}
$.ajax({
url: "target.php",
data:{'value':direccion},
success: function(response) {
//process the data received from server script
});
});
});
PHP CODE(target.php):
$value=$_POST['value'];
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$value .'&sensor=false';
//further processing of data at server end and finally echo the data to client
You need to do it with your last desired input tag. Suppose you want data up to the 3rd input tag then you need to Call your custom function in the 3rd input tag with onkeyup="myFunction()"
In myFunction() you can check if the fields are populated or not and can also do the ajax to transfer the data to server

Creating form using JavaScript

Here is my code below,
var mapForm = document.createElement("form");
mapForm.target = "_blank";
mapForm.method = "POST";
mapForm.action = "delete";
// Create an input
var mapInput = document.createElement("input");
mapInput.type = "hidden";
mapInput.name = "uploaded";
mapInput.value = file.name;
// Add the input to the form
mapForm.appendChild(mapInput);
// Add the form to dom
document.body.appendChild(mapForm);
// Just submit
mapForm.submit();
it does work, but after submitting the value, it opens the action URL in a new window because i have given mapForm.target = "_blank"; , is it possible to submit the form without opening any windows i mean it should stay in the same window but it should not go to "delete page"?, not by using ajax...
You could send your data to an hidden iframe:
var mapForm = document.createElement("form");
mapForm.target = "myIframe";
mapForm.method = "POST";
mapForm.action = "delete";
//Create an iframe
var iframe = document.createElement("iframe");
iframe.src = "response.php";
iframe.name = "myIframe";
iframe.style.width = '1px';
iframe.style.height = '1px';
iframe.style.visibility = 'hidden';
iframe.style.position = 'absolute';
iframe.style.right = '0';
iframe.style.bottom = '0';
mapForm.appendChild(iframe);
// Create an input
var mapInput = document.createElement("input");
mapInput.type = "hidden";
mapInput.name = "uploaded";
mapInput.value = file.name;
// Add the input to the form
mapForm.appendChild(mapInput);
// Add the form to dom
document.body.appendChild(mapForm);
// Just submit
mapForm.submit();
// Remove mapForm
document.body.removeChild(mapForm);
You can check the new FormData HTML5 feature. It's let you send a form by Ajax (a real form like it was a normal ) : https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
If u dare using JQuery u can use AJAX to trigger a request to the serverside, in this case i assumed delete.php, very easily.
In the head of your HTML file add the following line to include the latest JQuery API.
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
In your JS create your form straightforward, convert the DOM element to a JQuery object with the $ (JQuery) method and create a AJAXForm with the ajax() method of the newly created JQuery object.
<script type="text/javascript">
var mapForm = document.createElement("form");
mapForm.method = "POST";
mapForm.action = "delete.php";
// Create an input
var mapInput = document.createElement("input");
mapInput.type = "hidden";
mapInput.name = "uploaded";
mapInput.value = file.name;
// Add the input to the form
mapForm.appendChild(mapInput);
document.body.appendChild(mapForm);
var frm = $(mapForm);
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
return false;
});
</script>
This will prevent yoor FORM from triggering a redirect to another page and instead use an asynchronious request to a server script to handle the data and push a response, that you can process within the success function of the AJAXForm.

Categories

Resources