Let me explain why I need to do this!
I need to send a request to another server that its format is something like this:
http://www.test.ccom/process?item=1AAA&item=2BBB&item=3CCC
This URL will add 3 different items (one of each) to the result page, like this:
Item = 1AAA Count=1
Item = 2BBB Count=1
Item = 3CCC Count=1
If I want to add just 3 of just one item, I should use this:
http://www.test.ccom/process?item=1AAA&item=1AAA&item=1AAA
And result page will be like this:
Item = 1AAA Count=3
My problem is that I can't send my request using GET method (because we want to add more than 100 per item and it will cause "Request-URI Too Large" error)
I used two different methods to send this request by POST, but without success.
First I used this function:
function post_by_form(path, params) {
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", path);
form.setAttribute("style", "display: none")
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "item");
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form.submit();
}
It works when I test it with different variable names (name="item"+key), but it doesn't work when I use one variable name for all the inputs.
Then I used this function to send the POST request by ajax:
function post_by_ajax(path, params_arr){
var http = new XMLHttpRequest();
var url = path;
var params = "";
for(var key in params_arr) {
if (params != "")
params += "&item="+params_arr[key];
else
params += "item="+params_arr[key];
}
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
The same result, both of this methods will return just one quantity for just one item (last one)... While we can submit a form with many input fields all with the same name, why I can not do it using these methods?! Do I have any problem in the logic?! can somebody please help me?!
Using Firefox with the TamperData plugin, and a form that simply has four fields all specified as <input type="text" name="item"> I can see that the POST data does indeed send four variables all named "item" but with different values for each.
It is then up to the receiving server to do something sensible with that. Most systems will just use one of the four values sent (maybe the first one, or the last one) but if there's already a server that correctly handles http://www.test.ccom/process?item=1AAA&item=1AAA&item=1AAA then your adding multiple fields all named "item" should work.
If that's not the case, then you need to write something to handle that on the server end of things - no amount of javascript coding will do it. That would involve getting the whole POST body and processing it yourself, as most server-side frameworks (like I said) will generally just use one of the values.
You can use TamperData or something similar to capture the HTTP data stream and see what is actually transmitted from the javascript you have now.
So ultimately, the answer to your question "Is it possible sending one variable multiple time via POST using javascript?" is yes, it is possible.
If you're passing all variables with the same name i.e.: 'item' then the request handler has no way to differentiate between them. That is why you're getting only 1 element. Try renaming the elements to item1=value&item2=value&item3=value.
If you're passing 100 elements then you should definitely be using the post method. The name problem will exist for both post and get so make sure that all the items are named differently.
Related
I want to send a variable from JavaScript to another HTML page and be redirected to that page, but I can't use forms because the first page is purely in JavaScript and a .js file so I can't declare a form. I also can't use the URL as my data is too big. What are other options? Every tutorial I've found uses either forms or the URL. Is there an alternative?
Based on this answer, I used the following code:
function post(array) {
var method = "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", "helloworld.html");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "array");
hiddenField.setAttribute("value", array);
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
}
and I call post(parameter) in another method.
It successfully redirects to helloworld.html, but how can I get the variable that I passed?
You can save the data in the localStorage and if the second page is in the same domain. The data has to be string.
Page One:
function sendData(){
localStorage.setItem("data", data);
location.href = "helloworld.html";
}
Save the data.
Page Two:
function onLoad(){
var data = storage.getItem("data");
}
Read the data.
Optional:
You could also create a JSON Object and save it with the function JSON.stringify
You can make an HTTP request from JavaScript:
// jQuery
$.get("demo_test.asp", function(data, status){
// do something
});
jQuery documentation is located here
You can use jQuery ajax API and send the data through POST request. See more:
here
or here
Edit: oops, I didn't notice that you don't have any server side handler enabled. In that case, if you do not want to use forms you can handle get/url parameters with jQuery.param() or use some routing enabling library.
I have noted that in my program every time when I want to declare a object, for example list, save, add, remove I write the following every time in each function.
ajax.open("Get", "./route/action",true);
ajax.send();
I want to do something like this.
//this.ajax.get('./route/action').update('ajax-content');
./route/action // this is path to my Action class-using servlet
Every time I have to open a connection, give the path to my action class which is a servlet and then send. I do this every time I want to load a list, delete or update.
How can I write a function that I will be just be:
this.ajax.get('./route/action');
// 'ajax.content' is the id of the div where I
// want to show the list,where after updating AJAX show the update list to the user.
update('ajax-content');
For example after adding a user I can see the added user without reloading the whole page. I am working on a maven project using Java EE, Servlet and JavaScript.
Try this:
function ajaxRequest(AJAXurl, callbackElementID){
x = new XMLHttpRequest();
x.open("get", AJAXurl, true);
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
document.getElementById(callbackElementID).innerHTML = x.responseText; //Will send the received data to the element passed in the function
}
};
x.send();
}
Use as following:
ajaxRequest("/somefile.php", "elementID"); //This will send recieved data to the element with "elementID" as id
Note: The way this is built is only for GET requests. Change code if you want POST request.
In a php page ,i created textboxes diynamically in javascript and i want to post these values to another php page how can i get these values ? And these are my codes ;
while (secenek>0){
var textBoxname = document.createElement('input');
textBoxname.name = 'textyetiskinname'+secenek;
textBoxname.id='textyetiskinname'+secenek;
textBoxname.type = 'text';
textBoxname.className='selectTravelInputFieldsCarJS';
document.getElementById("yetiskindiv").appendChild(textBoxname);
secenek--;
}
If that is the entire snippet of script, then you need to build more script to do the ajax function.
If you are just trying to grab value of the dynamically created element, then you can use document.getElementById('textBoxname').value; as this code will grab the value.
set a unique attribute on your input tags:
//at this to your while loop
textBoxname.setAttribute("phpform", "myform");
to be able to find them and then read the form data and send them like this:
function POST_data(callback){
var myinputs = document.querySelectorAll("input[phpform=myform]");
var formData = {};
for(var i=0;i<myinputs.length;i++){
formData[myinputs[i].getAttribute("name")] = myinputs[i].value;
}
req = new XMLHttpRequest();
req.open("POST", "php_url");
req.onreadystatechange = function(){
if(req.readyState==4){
callback(req.response);
}
};
req.send(JSON.stringify(formData));
}
call POST_data and give a callback for your callback scenario, like this:
POST_data(function(response){
//you can check here if it was successful or not and continue your scenario
});
just be careful, this code is using a sample ajax request, in the real world you'd better use jQuery or at least a cross-browser ajax function.
I have a situation in which I am a bit confused on how to complete.
Example domains:
http://url1.com
http://url2.com
url1.com has a registration form url2.com has another form.
I need to pass the POST values from url1.com to url2.com without an actual submit happening. On url2.com I need to reconstruct the form with the POST values from url1.com and append hidden input values to the reconstructed form and then submit. I would like to completed this with JavaScript / jQuery if possible.
I would like to note that the url1.com contains a registration form with login and password.
Any advice is greatly appreciated.
Thanks in advance.
Here is how you could post to another URL:
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
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();
}
copied from here:
JavaScript post request like a form submit
There are other solutions there as well.
P.S. Regarding the security question, read here:
Are https URLs encrypted?
Essentially, all the data you pass over secure connections are encrypted, be it GET or POST. And be aware that even if you post data over regular http it could be intercepted by the man in the middle even if it is not visible for the user in the URL.
Example URL: http://twitter.realgamingreview.com/index.php
Edit: forgot to mention: use the test sign in: test/test for username/password.
I am attempting to do a simple AJAX request to retrieve some data from a database. The target file, serverTime.php, seems to be working perfectly; it inserts the desired data and returns the desired responseText.
However, the request seems to be firing twice. This is clear when I step through the JavaScript using Firebug. This causes the page to 'reset' (not exactly sure), such that my cursor loses focus from its current textbox, which is a new problem. The URL also says, "localhost/twitter/index.php?message=", even if my message is not actually empty. I want to fix this fairly minor problem before something major comes of it.
The JavaScript is below. ajaxRequest is my XMLHTTPRequest object. Any help is appreciated!
//Create a function that will receive data sent form the server
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readyState == 4){
document.getElementById('output').innerHTML = ajaxRequest.responseText;
}
}
// build query string
var message = document.myForm.message.value;
var queryString = "message=" + message;
//send AJAX request
ajaxRequest.open("GET", "serverTime.php" + "?" + queryString, true);
ajaxRequest.send(null);
Thanks,
Paragon
I've seen this many times, and for me it's always been firebug. Try TURNING OFF firebug and submit the request again. Use fiddler or some other means to verify the request only executed once.
When I write AJAX functions in Javascript, I usually keep around a state variable that prevents a new request from being dispatched while one is currently in progress. If you just want to ignore requests that are made before another one finishes, you can do something like this:
Initialize inProgress to false.
Set inProgress to true right before calling ajaxRequest.send(). Do not call ajaxRequest.send() unless inProgress is false.
ajaxRequest.onreadystatechange() sets inProgress to false when the state is 4.
In some cases, however, you'd like to queue the actions. If this is the case, then you can't just ignore the request to ajaxRequest.send() when inProgress is true. Here's what I recommend for these cases:
Initialize ajaxQueue to an empty global array.
Before calling ajaxRequest.send(), push the request onto ajaxQueue.
In ajaxRequest.onreadystatechange() when the state is 4, pop the array to remove the request just services. Then, if ajaxQueue is not empty (array.size > 0), pop again and call send() on the object returned.
My issue was completely unrelated to AJAX. Instead, it was a simple (but obscure) issue where with two textboxes in my form, I was able to hit enter and not have the page reload, but with only one, the page would reload for some reason.
I have since changed my event system such that I am not relying on something so unreliable (now using jQuery to listen for the Enter key being pressed for specific textboxes).
Thanks to those of you who took the time to answer my misinformed question.