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();
});
});
Related
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 am pretty new to html5 web development
I have created a page with login and password on it and have a submit button.
On submit , I send a rest request to the server which has a url
THE RRQUEST IS SOMETHING LIKE THIS
<USERNAME>
abc
</USERNAME>
<PASSWORD>loooik
</PASSWORD>
which is in js file as var data...
This request is set as
var parameters=JSON.stringify(data);
I use the following code for establishing connection
xmlHttp.open("post",url,true);
XmlHttp.setRequestHeader("Content-type","application/json);
xmlHttp.send(parameters);
xmlHttp.onreadystatechange=function X()
{
if(xmlHttp.readyState==4)
{
alert(xmlHttp.responseText);
}
}
return true;
}
I need to add a loading element and want to display the next screen between request and the response. How can I achieve it?
In tag I have used submit input type where onClick attribute calls return sendPost() method which has the request to be called
How should I proceed for the same... having loading screen and getting the response ... suppose just the name to be displayed on next html screen
First of all see basic jQuery example. This will guide you through how jQuery works and help a lot in the solution I'm going to suggest.
http://learn.jquery.com/about-jquery/how-jquery-works/
jQuery has it's own AJAX method and further shorthand called $.post
Now you can write something like this -
function requestNetwork() {
// Code for loading screen
$.ajax({
url: "yourURL",
data: "yourData"
}).done(function(data) {
alert(xmlHttp.responseText);
// Code for dismissing loading screen
}).fail(function(data) {
// Code when call fails
}).always(function() {
// This code will always run
});
}
I am using the following tag to let the users like the post
Like
I get the id of the <a> through Javascript which is actually the post_id and send the data to like.php using the following GET method.
post_id = 22;
xrequest.open("GET","like.php?post_id="+post_id+",true);
xrequest.send();
I have two questions
How can I send this request using POST Method?
(Note that there is not any <form>...</form> around the tag.)
If I use the above mentioned GET Method, Is it secure?
Since you've tagged jQuery, I assume you are using it. If so, you can do it like:
// attach a click handler for all links with class "like"
$('a.like').click(function() {
// use jQuery's $.post, to send the request
// the second argument is the request data
$.post('like.php', {post_id: this.id}, function(data) {
// data is what your server returns
});
// prevent the link's default behavior
return false;
});
Regarding your second question: No, it does not really make it safer unless you are doing it within SSL (https). a middle-man can still intercept your message mid-way and read the contents. POST makes it more indirect (to intercept and read the payload) than GET, but not safer.
To use POST to send the like link id you can do the following:
$(document).ready(function() {
$("a.like").click(function(event) {
var data = event.target.id;
$.ajax({
type: "POST",
url: "like.php",
data: data
});
});
});
updated, there was a typo in my code.
If i understand your question correctly, something like this should work for you:
$('#link_22').click(function(){
var link = $(this).attr('id');
$.post('/like.php/', {post_id: link});
return false;
})
Then you can reach this from PHP with something like:
$_POST['post_id'];
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.