I'm creating a simple website and a html page on it which contains a table that shows products. I load this table using AJAX and it work properly. Here is a screenshot:
Under the table I have buttons which perform CRUD operations using AJAX.
They communicate to a php script on a server outside of my domain using GET method.
When I click on Add product it opens a form with a button that whose onclick event calls a function which adds a product using AJAX. But, when I click, the whole page reloads and the product is not added. If I put the value that says wheter the call is async to false, it works as intended and the product is added to the table, however that is not the point of AJAX.
This is my code for adding a product(delete and update are almost the same).
<div id="addProductPopup">
<div id="popupContact">
<form id="form" method="post" name="form">
<img id="close" src="/servis/Resursi/Slike/close.png" onclick ="hide('addProductPopup');">
<h2>Dodavanje proizvoda</h2>
<hr>
<input id="name" name="naziv" placeholder="Naziv proizvoda" type="text" required>
<input id="kolicina" name="kolicina" placeholder="Količina proizvoda" type="text" required>
<input id="url" name="url" placeholder="URL slike" type="text" required>
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct()">
</form>
</div>
When I click on submit this function is called:
function addProduct(){
var isValid = true;
var url = "http://zamger.etf.unsa.ba/wt/proizvodi.php?brindexa=16390";
var amount = document.form.kolicina.value;
var naziv = document.form.naziv.value;
var slikaurl = document.form.url.value;
var validity = validateFields(naziv, slikaurl, amount);
if(!validity) return false;
var product = {
naziv: naziv,
kolicina: amount,
slika: slikaurl
};
var requestObject = new XMLHttpRequest();
requestObject.onreadystatechange = function(event) {
if (requestObject.readyState == 4 && requestObject.status == 200)
{
loadProducts();
event.preventDefault();
}
}
requestObject.open("POST", url, true);
requestObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
requestObject.send("akcija=dodavanje" + "&brindexa=16390&proizvod=" + JSON.stringify(product));
}
It is because you are not preventing the default action of the submit button click.
You can return false from an event handler to prevent the default action of an event so
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct(); return false;">
But since you have a form with a submit button, I think it will be better to use the submit event handler like
<form id="form" method="post" name="form" onsubmit="addProduct(); return false;">
....
<input type="submit" value="Pošalji" class="popupButtons">
Your problem is that your submit button still executes a real submit. You could change your addProducts method. The method have to return false to prevent the real submit.
Submit button performs default Submit action for HTML code.
Try to change Submit tag into Button tag. Or after AddProduct() in OnClick JS Action put
return false;
Simple Change put input type="button" instead of tpye="submit"
<input type="button" value="Pošalji" class="popupButtons" onclick="addProduct()">
Related
I would like to 'post' a form with vanilla JS. There are other questions similar, but I cannot get mine to work. The data is simply not passing to the controller.
I have several options for user on page, displayed as buttons. When the user clicks one button, a hidden form gets filled, and then the JS will submit the form to the controller.
the hidden form below:
[for testing, I have not 'hidden' the form fields yet, so I can monitor the correct information is getting to the form]
<form action="RetailTimePriceDisplayOne" method="post" id="postForm" name="postForm">
<input type="text" id="fmZero" value="#ViewBag.zero" />
<input type="text" id="fmVehicle" />
<input type="text" id="fmTeam" />
<input type="text" id="fmTLabor" />
<input type="text" id="fmRouteCost" />
<input type="text" id="fmRouteD" value="#ViewBag.vehicleMile"/>
<input type="text" id="fmRouteT" value="#ViewBag.vehicleTime"/>
</form>
My JS:
<script>
function fillForm(vehicleType, teamCount, travelLabor, routeCost) {
document.getElementById("fmVehicle").value = vehicleType;
document.getElementById("fmTeam").value = teamCount;
var x = #ViewBag.rateTravelDrvr;
if (teamCount > 1) {
x = #ViewBag.rateTravelDrvr + (#ViewBag.rateTravelCrew * (teamCount - 1));
}
document.getElementById("fmTLabor").value = x;
var y;
if (vehicleType == "V") {
y = #ViewBag.vVPrice;
}
if (vehicleType == "H") {
y = #ViewBag.vHPrice;
}
if (vehicleType == "T") {
y = #ViewBag.vTPrice;
}
document.getElementById("fmRouteCost").value = y;
SubmitForm();
}
function SubmitForm() {
var myForm = document.getElementById('postForm');
//document.forms["postForm"].submit();
myForm.method = 'post';
myForm.submit();
}
</script>
The form gets filled correctly, but no data is submitted to the controller. You can see that I played around with it a bit. One thought I had was that the method was changing to 'get' and that by explicitly specifying the method, I might solve the issue. But no such luck. Thanks!
EDIT:
As requested, one of the 6 buttons on the page that fire the JS function.
<button class="btn btn-secondary btn-lg" style="width:100%; height:100%;" onclick="fillForm('T',3)">
<strong>#ViewBag.TrkThr</strong>
<p>with 3 persons</p>
<p>+ #ViewBag.TrkMinute per labor minute*</p>
</button>
Usually when I want to submit the form, I am using button, then do onClick event
The "name" of the inputs wasn't defined, and hence data wasn't getting posted.
I have the following code:
<form id="buttonForm" action = "/goSomeWhere" method="post" >
<input type="submit" name="bnext" value="Next Page" >
<input type="submit" name="bprevious" value="Previous Page" >
</form>
When either one of this two buttons are submitted I receive "bnext" or "bprevious" values in Django View request.POST so I can further construct the logic that I need.
But when I'm trying to insert some javascript for the second button I loose those values:
<input type="submit" name="bnext" value="Next Page" >
<input type="submit" name="bprevious" id="bpid" onclick="disable()" value="Previous Page" >
function disable()
{
document.getElementById("bpid").disabled = true;
document.getElementById("buttonForm").submit();
}
There is a way to do this and still receiving input names values ?
Sorry I didn't fully understood that what you are trying to do
If you are trying to stop form submission then:
function disable() {
document.getElementById("bpid").disabled = true;
document.getElementById("buttonForm").preventDefault();
}
If you want that client should not click previous button again then, it is best to change inputType submit to hidden:
function disable() {
document.getElementById("bpid").type="hidden";
document.getElementById("buttonForm").submit();
}
Or
create new <input type=hidden>, set name values ,append to form and submit it:
function disable() {
document.getElementById("bpid"). disabled=true;
newip= document.createElement("input");
newip.type="hidden";
newip.name="bprevious";
newip.value="Previous Page";
document.getElementById("buttonForm").appendChild(newip);
document.getElementById("buttonForm").submit();
}
try to use button instead input like this
<button name="bprevious" id='bpid' onclick='disable()' value="Previous Page">Previous Page</button>
As a workaround for not being able to have nested forms, I've written a system that uses Javascript to update an outside form's hidden input values and then submit the form. It is working just fine on one page in my site, but for some reason it isn't on another page. In the browser's JS console, I see the correct ID for the form I want submitted, but the server-side keeps showing a different form's data.
Here are relevant code snippets:
So the button's onclick action calls the JS function updateAndSubmitForm () to submit the actual form I want submitted for this button ("formAddStage") and NOT for the surrounding form "form-update-plan".
<form id="form-update-plan" class="form-horizontal" action="/secure/treatment-components/EditTreatmentPlan" method="POST">
<input type="hidden" name="requestedAction" value="plan-edit-update">
...
<button role="button" class="btn btn-default btn-xs" title="Add a stage to this treatment plan."
onclick='updateAndSubmitForm("formAddStage", ${treatmentPlan.treatmentPlanID }, 0, 0)'>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
...
</form>
Here is the form "formAddStage" which is at the botton of the page outside of the form that contains the button:
<form id="formAddStage" action="/secure/treatment-components/CreateStage" method="POST">
<input type="hidden" name="requestedAction" value="add-stage-to-treatment-plan">
<input type="hidden" name="path" value="${path }">
<input type="hidden" id="taskIDDynamic" name="taskID" value="" >
<input type="hidden" id="stageIDDynamic" name="stageID" value="" >
<input type="hidden" id="treatmentPlanIDDynamic" name="treatmentPlanID" value="${treatmentPlan.treatmentPlanID }">
<input type="hidden" name="clientUUID" value="${clientUUID }" >
</form>
And here is the JavaScript which gets the form by the ID supplied, gets and sets the values of the hidden fields in that form with the supplied values, then submits.
function updateAndSubmitForm(formID, treatmentPlanID, stageID, taskID){
var form = document.getElementById(formID);
var inputTaskID = form.elements["taskIDDynamic"];
inputTaskID.value = taskID;
var inputStageID = form.elements["stageIDDynamic"];
inputStageID.value = stageID;
var inputTreatmentPlanID = form.elements["treatmentPlanIDDynamic"];
inputTreatmentPlanID.value = treatmentPlanID;
var requestedAction = form.elements["requestedAction"];
console.log("Updating and submitting form " + form.id + " - requestedAction: " + requestedAction.value);
//alert("Updating and submitting form " + formID + " - requestedAction: " + requestedAction.value);
form.submit();
};
So, in summary, clicking the button should call the JS function updateAndSubmitForm() which then gets the form designated in the method's argument "formID" and then take the remaining arguments to update the values of the form and then submit it.
What ends up happening is that my browser console reports the proper information (form id = "formAddStage" and requestedAction = "add-stage-to-treatment-plan") but the server side reports getting information from the form (id="form-update-plan") that is surrounding the button (e.g. request.getParameter("requestedAction") returns "plan-edit-update" instead of "add-stage-to-treatment-plan".
Any ideas about why form.submit() in the JS function does not seem to submit the proper form or why the server is getting a different form?
The button element within the "form-update-plan" form does not have a type specified, it will therefore be defaulting to a type of submit and submitting the "form-update-plan" form.
Try this:
<button type="button"
I have two submits, one to submit the form on page 1, the other to submit form on page 1 and redirect to form 2 on page 2.
<input type="submit" value="Submit and Add Expense" onclick="window.location.href='#Url.Action("Create", "Expense")';"/>
The issue is, when this secondary submit button is clicked it just submits the form just like the first submit button. It appears that the redirect #url.action is not firing. Thoughts?
The following code should do the trick.
<input type="submit" id="btnOne" value="One"/>
<input type="button" id="btnTwo" value="One"/>
<script>
var sample = sample || {};
sample.url = '#Url.Action("Create", "Expense")';
</script>
//you can move it to a separate file
<script>
$(function(){
$("#btnTwo").click(function(){
var form = $("form");
form.submit();
setTimeout(function() {
window.location.href = sample.url;
},100);
});
});
</script>
I wound up going the easy route of assigning value property to the button, and then checking the button value in the controller.
// View
<input type="submit" value="Submit" />
<button name="button" value="SubmitAndExpense">Submit and Add Expense</button>
// Controller
[HttpPost]
public ActionResult Create(string button)
{
if (button != "SubmitAndExpense") {...}
}
Any changes that I want does not take effect because the page refreshes itself whenever I click a button.
With the POST method on it. This the scenario, I clicked the button, then changes take effect like editing the inner html of a division, after that, the page refreshes itself that is why all the changes disappears. Please help me if there are any ways that changes can be made after the page refreshes.
This is my code. Can you tell me how to use ajax on it?
<form name="myForm" method="POST">
<button style="border-radius:0px;" type="submit" name="tabExe" id="tabExe" href="#Exec" onClick="myFunction('Executive');" class="btn btn-primary">Executive Room>
</button>
</form>
<script>
function myFunction(str){
if(document.getElementById(str) == tabExe){
document.getElementById('room1').innerHTML = "Room 101";
}
}
</script>
Consider this code of Javascript ajax as you need:
function submit()
{
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "yourpage.phtml?param1=2¶m2=10", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
return false;
}
HTML onsubmit method:
<form name="myForm" method="POST" onsubmit="return submit()">
When u clicked on submit button . form submitted. But when u use button as type, It will not refresh.
remove type ="submit". use type type ="button"
add return false; in onclick function. So it change bydefault property.
<form name="myForm" method="POST">
<button style="border-radius:0px;" name="tabExe" id="tabExe" href="#Exec"
onClick="myFunction('Executive'); return false;" class="btn btn-primary">
Executive Room>
</button>
</form>
<script>
function myFunction(str){
alert();
if(document.getElementById(str) == tabExe){
document.getElementById('room1').innerHTML = "Room 101";
}
}
</script>