Is there a way to check if a form is submitted using an if statement?
I am trying to write a function that no matter what the user does, information is always recieved and displayed to them. But if they user submits a form, it sends that data to the database and updates it first.
I've been trying to find events or methods to help me with this, but couldn't seem to find anything helpful.
function getData(){
if ( FORM SUBMITTED ) {
//POST and send
request.open("POST", url, true);
request.onreadystatechange = useResponse;
request.send(str);
}
//GET and display
request.open("GET", url, true);
request.onreadystatechange = useResponse;
request.send(null);
}
EDIT: I am not refreshing the page. I forgot to mention that I am doing this using AJAX. When the page loads, this function runs initially (which displays the form data). But I do not want the form to send any data since I'm just loading the page and not actually submitting anything.
After the page is loaded and I click submit, this function is called. What I need is AJAX to send the form data via POST, then redisplay it (the script above outlines the function).
The form when submitted just calls the function:
action="javascript:getData()"
I don't quite understand what you're asking because if a form is submitted then the browser is loading a new HTTP response which may or may not know anything about an HTML form which led to its generation.
[Edit]
It looks like the "getData" function is doing too many things, I would create separate functions to handle the "get" and "post" requests, for example:
<body>
<form name="form" action="#">...</form>
<script type="text/javascript">
var getData = function() {
// XHR GET data and update DOM...
};
getData();
var sendData = function() {
// XHR POST form encoded data from form input elements...
};
document.form.onsubmit = function() {
sendData();
getData();
return false; // Block the actual form submit event.
};
</script>
</body>
The jQuery serialize() function demonstrates what is needed to encode the form data programmatically.
Hmm, I hope I'm understanding you correctly. You basically want to (conditionally) POST to one URL and GET from another one (or the same one) in serial?
If that's the case, your code would look something like...
var get = function(callback) {
var req = new XMLHttpRequest();
req.open = req.open('GET', url);
req.onreadystatechange = function() {
if (...) {
callback(req.responseText);
}
};
req.send();
};
var exec = function(callback) {
if (FORM_SUBMITTED) {
var req = new XMLHttpRequest();
req.open('POST', url);
req.onreadystatechange = function() {
if (...) {
get(callback);
}
};
req.send();
} else {
get(callback);
}
};
exec(function(data) {
console.log('request(s) complete, here's the response: '+data);
});
Since XHR is only really worth-while when using it asynchronously, you have to nest some callbacks to make sure everything happens in serial, otherwise, the GET may complete before the POST.
Related
I have an application running with Backbone.js, and I need to trigger the browser password save when logging in.
Currently I am using preventDefault when the form is submitted, and thus the password save is not triggered. When searching for this I find old posts about using iFrames and stuff, which seems obsolete, so my question is:
How do you trigger the password save prompt, when handling form submit in JS?
I don't think you can force the Browser to do that; What I'm sure you can do is, after the ajax (or anything) post request, do a form submit something like that
in jquery :
$.ajax({
url:requestUrl,
success: function (data, text) {
//Request Finished with Success
$('#Form').submit();
},
error: function (request, status, error) {
//Request Finished with Error
}
});
in VanillaJS :
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === 4) {
//Request Finished
if(request.status === 200) {
//Success
document.getElementById('Form').submit();
} else {
//Error
}
}
}
request.open('POST', URL);
request.send();
This way you let the Browser and the User keep control over what happens.
If you still want to save the password then use cookies, Here is something you might use
I have been trying to implement a form without using the form element but no success yet. I have two .php files, file1.php and file2.php
I tried to implement it using the onclick of a button in file1.php, but I can't seem to understand how it works:
function submitData(){
var http = new XMLHttpRequest();
var url = "file2.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
The function works well, upon the button click it returns the the whole text of file2.php. But this is not what I am trying to achieve. I want this button click to get me to file2.php and from there I can get the parameters and use them further. When I use the form eleement upon clicking the submit button it will get me to file2.php but the above code does not seem to do that. I know I am missing something very obvious here :/ ?
I want this button click to get me to file2.php
I don't know if I undestand you well, but you have to know that XMLHttpRequest() is used to AJAX connections.
AJAX means: Asynchronous JavaScript and XML
Asynchronous menas, that you will be NOT redirected to this file. You will stay in the file file1.php, and at this time the server will run file2.php and give you an answer.
XMLHttpRequest is not used for show you another file. This is useful, when you want to get an answer from a PHP file, without leaving a current page.
Try some jquery like:
$(document).ready(function(){
$('#yourBtnId').click(function(){
//Define all of your form data from input fields, something like:
var formData = {
'name' : $('input[name=inputName]').val(),
//put more here similar to above
};
$.ajax({
type : 'POST', //or get whatever
url : 'urltophpfilewhereyouprocesspost',
data : formData,
dataType : 'json', //or whatever
encode : true
})
.done(function(data){
//do whatever you want
});
event.preventDefault();
});
});
I know its super basic and probably simple as well, but i'm really stuck.
just trying to get data from php in an event of onkeyup, and post it into the HTML page.
this is my HTML
<input id="dell" type="text" onkeyup="dell_function()"<br>
<p id="gimr">get her the php variable var.</p>
php file:
<?
$var=11;
echo $var;
?>
Now i need to write the dell_function() which i want to open the php file and get the $var value, and post it as a string in here:
<p id="gimr">get her the php variable var.</p>
i know there is ajax involved but i really tried but couldn't figure it out, so how do i write the dell_function?
Ajax is really simple, especially if you are using JQuery. Here is how it would look in jQuery:
function dell_function() {
$.ajax({
url:"test.php", // replace test.php with the name of your PHP file
success: function(data) {
$("#gimr").html(data);
}
});
}
The jQuery documentation describes loads of other cool things you can do with Ajax : http://api.jquery.com/jquery.ajax/
function dell_function() {
var xhttp = new XMLHttpRequest(); // creates a ajax request object
xhttp.onreadystatechange = function () { // will fire when the status of the request changes
if (this.readyState == 4 && this.status == 200) { // checks if the current state indicates that the content has been loaded successfully. readyState=4 means that the request has been completed and the status 200 means that the request returned http status code 200, which means the server response is OK (404 would mean file not found, 408 means timeout, etc - you get the idea).
document.getElementById("gimr").innerHTML = this.responseText; //this will put the response text as html inside the "gimr" element.
}
};
xhttp.open("GET", "YOUR_PHP_FILE.php", true); //the first parameter sets the request method, the second defines the url, and the third defines if the data should be fetched asynchronously.
xhttp.send(); // sends the requests to the specified url.
}
Replace "YOUR_PHP_FILE.php" with the url to your php file.
Btw, take a look at jquery - it makes things like this alot easier ;D
I am trying to export my web page data and download it as excel file. but the download does not start even the response return succeed.
$.ajax({
type: "POST",
url: _url,
contentType: 'multipart/form-data;boundary=SzB12x',
data: json,
});
The responseText something like this:
PK�J;Fxl/theme/theme1.xml�YOo�6����,[r��n;v��i����#-�kJH:�oC{0X7�2��mZ���d��u#�(٦b:M���������{|��^�0t#��*"w$�!0I�[�՚n�i��'����iH� g�,��|�J�!���hRh�h��?r&�L ���߶S��v#���#���"���}��Жt%�hR�t"������+��������u{ނ��0K���oy�9OTWywkAͯ�
���F�� 6*�����[���U���
I think its the file but I cant download it!!
Any help please?
Thanks!
I faced the same issue and successfully solved it. My use-case is this.
Post JSON data to server and receive an excel file.
That excel file is created on the fly and returned as a response to client.
Code:
$("#my-button").on("click", function() {
// Data to post
data = {
ids: [1, 2, 3, 4, 5]
};
// Use XMLHttpRequest instead of Jquery $ajax
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
// Trick for making downloadable link
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response);
// Give filename you wish to download
a.download = "test-file.xls";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
};
// Post data to URL which handles post request
xhttp.open("POST", excelDownloadUrl);
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
xhttp.responseType = 'blob';
xhttp.send(JSON.stringify(data));
});
The above snippet is just doing following
Posting an array as JSON to the server using XMLHttpRequest
After fetching content as a blob(binary), we are creating a downloadable URL and attaching it to invisible "a" link then clicking it.
Here we need to carefully set few things at the server side. I set few headers in Python Django HttpResponse. You need to set them accordingly if you are use other programming languages.
# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
Since I download xls(excel) here, I adjusted contentType to above one. You need to set it according to your file type.
Try to use a hidden form to submit the request.
When a user submits an HTML form, all the data entered into the form by the user is sent as either a GET or POST request to the URL specified in the “ACTION” attribute of FORM.
<FORM action="http://www.labnol.org/sendmail.php" method="post">
...form contents...
</FORM>
In the above example, an HTTP POST request is issued to the sendmail.php script on form submission. You can add target=”_blank” to the FORM tag to process the request in a new window.
However, if you would like to submit a FORM on the page in the background without directing the browser to another page (document.location.href changes on form submit), you have two options:
Option #1. You can either create an invisible IFRAME inside your HTML page and set that as a target for the Original FORM. This will submit the form but without reloading the parent window.
<FORM action="http://example.com/script.php"
method="POST" target="hidden-form">
...form contents...
</FORM>
<IFRAME style="display:none" name="hidden-form"></IFRAME>
Option #2: There’s another method that allows you create custom payloads before submitting the form. Unlike the IFRAME based form submission, the following code makes a standard form submit request and thus your browser location will change and the current page will get added to the browser history. Credit: Rakesh Pai.
submitFORM('http://example.com/script.php', 'POST',
{'name':'digital+inspiration', 'age':'100', 'sex','M'});
function submitFORM(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
//Move the submit function to another variable
//so that it doesn't get overwritten.
form._submit_function_ = form.submit;
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form._submit_function_();
}
In this link you can find the way to create hidden form and submit it.
enjoy!!
The approach here is directly lifted from https://gist.github.com/DavidMah/3533415.
This approach uses <form> and appends the data with a key. This approach works if the server is already expecting the data as an attribute of the request body, as opposed to being the request body itself. If the data to be uploaded is an object, you could iterate over that object's keys. If the data to be uploaded is an array, either modify the server route or [add idea here].
In browser
// Takes a URL, param name, and data string
// Sends to the server... The server can respond with binary data to download
jQuery.download = function(url, key, data) {
// Build a form
var form = $('<form></form>').attr('action', url).attr('method', 'post');
// Add the one key/value
form.append($("<input></input>").attr('type', 'hidden').attr('name', key).attr('value', data));
//send request
form.appendTo('body').submit().remove();
};
On server
# A Tidbit of sinatra code to respond
# Assume 'url' is a set variable
# Assume 'key' is the key of the value used in the javascript
post url do
data = params[:key]
puts request.body.read
headers['Content-Type'] = "application/octet-stream"
body(data)
end
Example
$.download('/path/resource/', 'data', JSON.stringify(data))
If you just want to download a file, you don't need to use ajax to do it. Actually, you cannot download file using ajax.
You can still do it by making a hyperlink Export request to a server page that responses content-type is application/vnd.ms-excel and content-disposition is attachment.
You can achieve this using an iFrame as well. A sample function:
// append the data to URL
var requestData = {
param1 : "value1",
param2 : "value2",
}
// call the function
downloadFile(<your_URL>, requestData);
function downloadFile(requestURL, data) {
// "transData" is just a user defined variable to encapsulate "downloadIFrame". It can be named anything as required.
var downloadIFrame = window.transData.downloadIFrame = window.transData.downloadIFrame || $("#downloadFileiFrame");
downloadIFrame.attr("src", requestURL + $.param(requestData));
}
// define the iFrame in your HTML and hide it.
<iframe id="downloadFileiFrame" style="display:none;"></iframe>"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: yoururlpath,
success: function (response) {
var file = fileName+".xlsx";
window.location = "someFilePath?file=" + file;
}
});
I've got a web page that displays some content. The query itself is pretty slow (4000 ms).
I don't want my users to have to wait for the query to run before the rest of the page loads though.
Is there a way I can stick some code before and after the tag in my HTML template that will "delay" that function from executing until after everything else has rendered?
e.g.:
<javascript code that tells the page not to render what comes next until very last>
<?php my_heavy_php_function(); ?>
</javascript>
As I can understand from your question, you should go for AJAX: you first load the page without the heavy content, and when the page is ready you do an AJAX call to a webservice to fetch and display the data, while showing a "Processing, please wait" message to the user.
symbolic write:
document.onload = ajax call
Using Ajax
Using the jQuery Ajax request method you can post the email data to a script (submit.php). The $(function(){ }); executes when the dom is ready. Also, you might need to use the 'timeout' option if you are going to be executing an long query.
note - I would suggest utilizing the ajax Response Object to make sure the script executed successfully.
$(function() {
$.ajax({
type: 'POST',
url: 'submit.php',
timeout: 10000,
error: function()
{
alert("Request Failed");
},
success: function(response)
{
//response being what your php script echos.
}
});
});
Although, jQuery is by no means required do do an ajax request, I would highly recommend using some kind of framework to help ensure x-browse support.
If you are using a large dataset I would highly recommend using json to encode your repsonses. It makes parsing quite easy. Here's an example with jQuery $.getJSON() API and likewise how you can encode it with PHP
Either optimizing the query or doing an AJAX call. Here is a plain JS way of doing AJAX, I found this script in a Google search and modified to use a callback function so you can parse the data or do other things other than just load the content straight to a HTML element:
the ajax function: The Original function I found unmodified
function ajaxRequest(Url, callback) {
var AJAX;
try {
AJAX = new XMLHttpRequest();
}
catch (e) {
try {
AJAX = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX.");
return false;
}
}
}
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4) {
if (AJAX.status == 200) {
callback(AJAX.responseText);
}
else {
alert("Error: " + AJAX.statusText + " " + AJAX.status);
}
}
}
AJAX.open("get", Url, true);
AJAX.send(null);
}
Usage of it:
<div> some normal content </div>
<div id="loadlater">loading data...</div>
<div> more content that loads before the data</div>
<script>
ajaxRequest('/echo/html/', function( response) {
document.getElementById('loadlater').innerHTML = response;;
});
</script>
Working example here: JSFiddle