I am looking for a solution after trying all different option for 5 hours . I am not a big HTML or Javascript person but I tried.
I have a List coming from the Database which is listings of services. Each Service gets their own unique ID. At the moment I send the ID via the URL but this is not preferable,
Within each list element I have a Picture and button and a link using the persons name.
I tried to use javascript to take the value from a value in the href line and sent that to the url which worked but it seems like the server saw that as a different session and hence the webpage did not display the full editable listing,
This was the script
<script>
function myFunction(test) {
var url = "/portal/vendorlistingsadd";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send(test);
}
</script>
then did
</div>
other problems I had was due to the same 'name' been on each row in the list, I could not extract the correct one.
So basically the only way I can see it working is to send the data via url .
If anyone has any suggestion I would try each one
Thank you
****UPDATE
<form action="/portal/vendorlistingsadd/editlisting" method="post">
</form>
and the second line
<button class= "btn-lg" name ='${serviclist.listing_id}' type = "submit"> <img src="${serviclist.picture}"/> </button>
Related
I have advanced ASP (classic) skills but am pretty green to JavaScript and Ajax. I'm working on a page that allows users to enter comments in response to a post. I'm wanting the form submission field to submit reader comments to the database, and then show those comments without changing the page. Much like a Facebook comment. Hence Ajax and JavaScript.
I've got the test.asp page (below) working. It's calling the AJAX.asp page, writing to the database, and updating a in the page with the submitted text. My only issue is that I am going to need to update a page with multiple sections, so I need to get a variable into the second JavaScript function to allow me to write to a unique . Currently it's set as id="newcomment" but this will need to change to something like id="newcomment" & var, so that the result is "newcomment1484" (or another unique number) and the right gets updated.
For the life of me I can't figure out how to get a variable in that second function. Any help greatly appreciated. Please keep in mind I'm quite new to JS.
<html>
<head>
<script>
function SendtoAjax(ident)
{
if(window.XMLHttpRequest)
{
oRequest = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
oRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
oRequest.open("POST", "AJAX.asp", true);
oRequest.onreadystatechange = UpdateComment;
val=document.getElementById('commentfield').value.replace(/\n/g, "<br>");
oRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oRequest.send("strCmd=availability&commentaid=" + ident + "&commentfield=" + encodeURIComponent(val));
}
function UpdateComment(ident)
{
if(oRequest.readyState == 4)
{
if(oRequest.status == 200)
{
document.getElementById("newcomment").innerHTML = oRequest.responseText;
}
else
{
document.getElementById("newcomment").innerHTML = "Asychronous Error";
}
}
}
</script>
</head>
<body>
<form method="post" action="javascript:void(0);" name="form1">
<textarea name="commentfield" id="commentfield"></textarea>
<input id="commentaid" type="hidden" value="Available1434">
<input id="submitcomment" type="button" value="submit" onClick="SendtoAjax(1434);">
<br><br><div id="newcomment"></div>
</form>
</body>
</html>
I tried all manners of getting a variable in there, but have come to learn (I think?) that there is some issue with the "onreadystatechange" and Ajax. Way beyond me at the moment.
you need to pass a formData object, see the docs for examples on how to do that.
let formData = new FormData();
// append some data (key, value)
formData.append("strCmd", "availability");
// send it with the form
oRequest.send(formData);
So I have a JS variable that is created after pressing a button, and I need to pass it to my app to process in flask. I'm currently trying to do it with query strings but I'm not really sure what I'm doing.
In the html I have a form set up like this:
<form action="/deleteBook" method="POST" onsubmit="deleteBook()">
<input type="submit" value="Delete" />
</form>
which calls this function to apply query string:
function deleteBook() {
var existingUrl = window.location.href;
window.location.href = existingUrl + '?itemID=' + itemToRemove;
};
and then I want to process that variable through flask:
#app.route('/deleteBook', methods=["POST"])
def deleteBook():
if(request.method == "POST"):
itemID = request.args.get('itemID')
In my mind the code should detect the form submission (basically single button click), call deleteBook() which should then append a query string to the URL which can then be processed in flask.
I'm aware that I'm lacking some basic knowledge about html/js/processing data so I'm not really sure where to go from here. Should I use PHP to process the request somehow? Or should I not be using a form at all? Or maybe in flask there is an easier way to get data without using POST? I'm not sure so any suggestions are appreciated, thanks!
Well I for one find your style for a question like this unique so I'll try my best to explain my idea of the answer.
Firstly, I would just have the form calling the function
Secondly, I would have the function call an 'XMLHttpRequest' with 'POST' configuration
The HTML
<form onsubmit="deleteBook()">
<input type="submit" value="Delete " />
</form>
The JavaScript
function deleteBook () {
var xhr = new XMLHttpRequest();
xhr.open('POST', existingUrl + '?itemID=' + itemToRemove, true); //The second argument is the url you wish to 'POST' to
xhr.send(); //if you want to do something if your flask returns something, 'xhd.onload = function () {}'
}
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.
I'm having a lot of issues using python and XMLHttpRequest().
I am trying to press a button on a webpage, that button send a string to python using POST and pythons urllib2.
Firstly, on the index page fun1() is not defined.
(i have about 6 identical pages with the same js and they work fine.)
python:
abc = urllib2.urlopen("http://0.0.0.0:3333/POST").read()
print(abc)
HTML index
<span class="button" onlick="jsfun1()"><p>button1</p></span>
<script type = text/javascript>
function jsfun1() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/POST", true)
xmlhttp.send("Hello World 1")
}
html /POST is empty. as im not sure what to do here. I simply want it to hold a string until another POST is sent to it and then replace the string. Unless i can skip the /POST and receive it straight to the python code instead.
Using a flask server to create the webpages.
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.