request from javascript in java - javascript

I try send from html through JScript to java two parameters:
1. nameSelectedWhisky
2. quantitySelectedWhisky
function buyFromJS() {
//
// $.getJSON("buySuccessfulWhisky",
// {
// nameSelectedWhisky:$('#nameWhiskey').val(),
// quantitySelectedWhisky:$('#numberOrderWhisky').val()
// },
// function() {
// window.location.href = "warehouseWhisky";
// } );
//}
var nameSelectedWhisky = $('#nameWhiskey').val();
var quantitySelectedWhisky = $('#numberOrderWhisky').val();
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST",
data: JSON.stringify(nameSelectedWhisky.id, quantitySelectedWhisky.id),
url: '/buySuccessfulWhisky',
success: function (msg) {
window.location.href = "warehouseWhisky";
},
error:function(){
alert("ERROR");
}
})
}
<form id="buySelectedWhiskyThroughJavaScript" method="post">
<tr th:each="buySelectedWhisky : ${buySelectedWhisky}">
<td align="center">
<img th:attr="src=${buySelectedWhisky.photo}" width="150" height="250"/>Photo</td>
<td align="center" th:text="${buySelectedWhisky.nameWhisky}">Name</td>
<td align="center" th:text="${buySelectedWhisky.describeWhisky}">Describe</td>
<td align="center" width="100">
<input type="number" style="width: 100px" min="1" th:attr="max=${buySelectedWhisky.quantityWhisky}"
placeholder="Enter quantity" name="numberOrderWhisky" id="numberOrderWhisky"/>
</td>
<td align="center" th:text="${buySelectedWhisky.price}">Price</td>
<td align="center">
<input type="hidden" name="nameWhiskey" id="nameWhiskey" th:value="${buySelectedWhisky.nameWhisky}"/>
<!--<input type="hidden" name="quantityWhiskeyInDB" id="quantityWhiskeyInDB" th:value="${buySelectedWhisky.quantityWhisky}"/>-->
<input type="button" class="buttons" onclick="buyFromJS()" name="buttonBuyWhiskey" style="width: 60px" value="Buy"/> </td>
</tr>
</form>
I add two versions JavaScript
1 Version use $.getJSON("buySuccessfulWhisky"
This version is working and java recive all parameters, BUT this version is not updating the page
window.location.href = "warehouseWhisky";
if I try to add location.reload() after "warehouseWhisky", then "buySuccessfulWhisky" is updated instead of "warehouseWhisky". Becouse if I will not update page "warehouseWhisky" I see wrong not updated information. If I'm updating the page "in the manual mode" - everything is working.
How proper update the "warehouseWhisky" page?
Next code through AJAX
Is not sending information to java
Java code to recive from JScript
#Controller
public class SuccessfulBuyWhiskey {
#RequestMapping(value = "buySuccessfulWhisky", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView view(#RequestParam("nameSelectedWhisky")String name,
#RequestParam("quantitySelectedWhisky")Integer quantityOrder) {
System.out.println("Name: = "+name);
System.out.println("Quantity: = "+quantityOrder);

function sendBuyWhiskyInJava(){
$('#buySelectedWhiskyThroughJavaScript').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/buySuccessfulWhisky',
data: {
nameSelectedWhisky: $("#nameWhiskey").val(),
quantitySelectedWhisky: $("#numberOrderWhisky").val()
},
success: function(data) {
window.location.href = "warehouseWhisky";
console.log(data)
}
})
})
}

Related

Posting a list of object which is located inside a viewmodel from view to controller in asp.net core 2.2

I have a view model called "RequestGoodsBrandViewModel" and it's the combination of two models (Request and RequestGoodsBrand), I want to post a list of objects "RequestGoodsBrand" of view model " RequestGoodsBrandViewModel " from view to controller.
public class RequestGoodsBrandViewModel
{
public Request request{ get; set; }//single object of this
public List<RequestGoodsBrand> requestGoodsBrand { get; set; }//List of object of this
}
my view
<tbody>
<tr v-for="(data, index) in goods">
<td width="20%">
<select id="goodsDDL" class="form-control">
<option v-for="options in goodsList" :value="options.id">{{options.name}}</option>
</select>
</td>
<td width="20%">
<input type="number" v-model="data.quantity" id="quantityTxt" class="form-control" />
</td>
<td width="20%">
<select id="brandDDL" class="form-control">
<option v-for="options in brands" :value="options.id">{{options.name}}</option>
</select>
</td>
<td width="7%">
<a v-on:click="addRow(index)" class="btn"><i class="fa fa-plus-circle" style="color:darkgreen"></i></a>
<a v-on:click="removeRow(index)" class="btn"><i class="fa fa-minus-circle" style="color:red"></i></a>
</td>
</tr>
<tr>
<td colspan="4">
<label>توضیحات</label>
<textarea id="descTxt" class="form-control"></textarea>
</td>
</tr>
</tbody>
View looks like this and table is dynamic,by pressing plus button new row will be added
public IActionResult AddRequestedGoods(RequestGoodsBrandViewModel model)// only RequestGoodsBrand of RequestGoodsBrandViewModel must be a list
{
}
Edit:
I post my ViewModel to the controller using ajax call
var requestGoodsBrand = {}
var request = {
NeedDate: $('#needDate').val(),
Description: $('#descTxt').val(),
}
var table= document.getElementById('goodsTbl')
for (var i = 1; i < table.rows.length - 1; i++) {
requestGoodsBrand[i] = {
GoodsId:(table.rows[i].cells[0].children[0].value),
Quantity:(table.rows[i].cells[1].children[0].value),
BrandId:(table.rows[i].cells[2].children[0].value)
}
}
var model = {
"request": request,
"requestGoodsBrand": requestGoodsBrand,
}
console.log(model)
var data = JSON.stringify(model)
$.ajax({
type: "POST",
async: true,
url: '/GoodsRequest/AddRequestedGoods',
data: model,
//contentType: "application/json; charset=utf-8",
//dataType: "html",
success: function (data) {
}
});
the first object receives data but the second object which is a list, return null
Any solution?
i wrote a demo code for the same please on Jquery try it :
Jquery
function () {
var requestGoodsBrand = [];
var request = {
NeedDate: 'demo1',
Description: 'demo2',
}
$('table tr').each(function () {
var entity = {
GoodsId: $($(this).find('td:eq(0) input')).val(),
Quantity: $($(this).find('td:eq(1) input')).val(),
BrandId: $($(this).find('td:eq(2) input')).val()
};
requestGoodsBrand.push(entity);
})
$.post('/Home/AddRequestedGoods', { requestGoodsBrand: requestGoodsBrand, request: request })
.done(function (result) {
}
C#
[HttpPost]
public string AddRequestedGoods(Request request, List<RequestGoodsBrand> requestGoodsBrand)
{
return "";
}

AJAX Only Updates the Last Item ID

I want to update item based on button click and send data to database using ajax and javascript button when i click on buttons of other rows only last row gets updated not the desired row.
here's my markup and ajax call:
#foreach (var item in Model)
{
<tr>
<td>
<div id="modelquantiy-#item.Id">
#Html.DisplayFor(modelItem => item.Quantity)
<script>
var value = 0;
function add() {
if (value >= 5) {
alert("No More Than Five Items");
} else {
postData = { 'number': 1, 'id': #item.Id };
$.ajax({
url: '#Url.Action("Quantity", "Home")',
contentType: "application/json;charset=utf-8",
type: 'POST',
dataType: 'json',
data: JSON.stringify(postData),
success: function (data) {
$("#modelquantiy-#item.Id").html(data.result);
},
//if it breaks, you want to be able to press F12 to see why
error: function (data) {
window.console.log(data);
}
});
}
}
</script>
</div>
</td>
<td>
<input type="button" id="Add" name="Add" value="+" onclick="add();" />
<input type="button" id="Subtract" name="Subtract" value="-" onclick="subtract();" />
</td>
</tr>
}
and here's my backend code i have written in C#
public ActionResult Quantity(int number, int id)
{
Qty Quantity = db.Qties.FirstOrDefault(q => q.Id == id);
if (Quantity != null)
{
Quantity.Quantity = Quantity.Quantity + number;
db.SaveChanges();
}
return Json(new { result = Quantity.Quantity }, JsonRequestBehavior.AllowGet);
}
You should add script outsite the foreach, and use onclick to pass the params.
#foreach (var item in Model)
{
<tr>
<td>
<div id="modelquantiy-#item.Id">
#Html.DisplayFor(modelItem => item.Quantity)
</div>
</td>
<td>
<input type="button" id="Add" name="Add" value="+" onclick="add(#item.Id);" />
<input type="button" id="Subtract" name="Subtract" value="-" onclick="subtract();" />
</td>
</tr>
}
<script>
var value = 0;
function add(val) {
if (value >= 5) {
alert("No More Than Five Items");
} else {
postData = { 'number': 1, 'id': val };
$.ajax({
url: '#Url.Action("Quantity", "Home")',
contentType: "application/json;charset=utf-8",
type: 'POST',
dataType: 'json',
data: JSON.stringify(postData),
success: function (data) {
$("#modelquantiy-"+val).html(data.result);
},
//if it breaks, you want to be able to press F12 to see why
error: function (data) {
window.console.log(data);
}
});
}
}
</script>
The problem is add function is re-declared in each loop, so only the last declared add function will be working on clicking every button, this last declared function add will be having the statement $("#modelquantiy-#item.Id").html(data.result); which will change HTML of the last row (div) only, javascript can have only one function with the same name add if you declare a function with the same name again it will replace the old one.
The solution is to declare a function add only once, that is to put the script outside and add and extra parameter which denotes to which row the ajax result should be added.
#foreach (var item in Model)
{
<tr>
<td>
<div id="modelquantiy-#item.Id">
#Html.DisplayFor(modelItem => item.Quantity)
</div>
</td>
<td>
<input type="button" id="Add" name="Add" value="+" onclick="add(#item.id);" />
<input type="button" id="Subtract" name="Subtract" value="-" onclick="subtract();" />
</td>
</tr>
}
<script>
var value = 0;
function add(itemID) {
if (value >= 5) {
alert("No More Than Five Items");
} else {
postData = { 'number': 1, 'id': itemID };
$.ajax({
url: '#Url.Action("Quantity", "Home")',
contentType: "application/json;charset=utf-8",
type: 'POST',
dataType: 'json',
data: JSON.stringify(postData),
success: function (data) {
$("#modelquantiy-"+itemID).html(data.result);
},
//if it breaks, you want to be able to press F12 to see why
error: function (data) {
window.console.log(data);
}
});
}
}
</script>

jquery ajax post selectbox array by name

I want to do an ajax request to update the status of an item, but for one or many selected item.
So how can I post all the selected checkbox items to process it on the handle page?
Here is some code I use., but it will only post one item to the process page.
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[78]">
</td>
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[182]">
</td>
And the javascript
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = {
item: $('input[name=item\\[\\]]').val(),
}
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
Assign the unique name to each checkbox
Put all checkboxes in a form tag (all input fields in a single form).
Use serialize() or serializeArray() for collecting data from form
store data in var formData
Code:
<form id="form-name">
<tr>
<td>
<input type="checkbox" name="item[1]">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="item[32]">
</td>
</tr>
</form>
Javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = $('#form').serializeArray();
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
},
error: function (data) {
console.log('Error:', data);
}
});
This will post an array of items to the url.
I did same thing in minor different way.
I got list of checkbox and names contain their id.
<input type="checkbox" class="bulkChecked" name="{{$value->id}}">
And Inside your event handler
var ids = [];
$(".bulkChecked:checked").each(function () {
ids.push($(this).attr("name"));
});
So at this point you have got ids of checked boxes. No you can pass 'ids' array with your ajax call

How can I submit a form and upload a file using ajax to a spring controller?

I have a form which contains four fields, the file, the name, the type (just a string) and the taskInstanceId.
<form>
<table id="documentDetailsTable">
<tr>
<td>Document Type: </td>
<td><select id="documentType" name="type"> </select></td>
</tr>
<tr>
<td>
Document Name:
</td>
<td>
<input type="text" id="documentName" name="name"/>
</td>
</tr>
<tr id="newFile">
<td>
Choose a file:
</td>
<td>
<input type="file" name="file" />
</td>
</table>
<input type="text" style="display: none;" name="taskInstanceId" id="taskInstanceId">
<input id="uploadButton" value="Upload" type="submit"/>
<input class="closeButton" id="closeNew" value="Close" type="button"/>
</form>
If I submit this form it will connect to my FileUploadController and the file will upload.
#RequestMapping(value = "/formTask.do", method = RequestMethod.POST)
public ModelAndView handleFormTaskUpload(#RequestParam("name") String name,
#RequestParam("type") String type,
#RequestParam("file") MultipartFile file,
#RequestParam("taskInstanceId") int taskInstanceId)...//rest of the code
Now I would like to submit this form using jquery/json instead so that I can return a string indicating a successful upload and then display a dialog on the page indicating this. (I don't want to return a new ModelAndView).
So using the same html form I create a new Controller function...
#RequestMapping(value = "/formTask2.json", method = RequestMethod.POST)
public String handleFormTaskUpload2(UploadTaskDocument myNewUpload)).../rest of the code
Now I would like to submit the form above using jQuery. My attempt is here.
This function is called everytime the file is changed.
function prepareUpload(event)
{
files = event.target.files;
}
And this one is called when the form is submitted.
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data;
data = {
documentName: $("#documentName").val(),
documentType: $("#documentType").val(),
taskInstanceId: selectedTaskInstanceId,
uploadedfiles: files
};
var json = JSON.stringify(data);
$.ajax({
url: '/SafeSiteLive/formTask2.json',
type: 'POST',
data: json,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data, textStatus, jqXHR)
{
if (typeof data.error === 'undefined')
{
// Success so call function to process the form
//submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
The Json data looks like this before it's posted...
But once it reaches the server everything is null...
Ok this might seem a bit different than your solution but I would go forth by doing the following.
As I understand you want to upload the data using ajax to your controller and avoid a post back, and then return a string and nothing but a string. I would do as follows.
You have your form:
<form> //Remove the method type as well as where the post should happen to ensure that you do not have to prevent default behavior
<table id="documentDetailsTable">
<tr>
<td>Document Type: </td>
<td><select id="documentType" name="type"> </select></td>
</tr>
<tr>
<td>
Document Name:
</td>
<td>
<input type="text" id="documentName" name="name"/>
</td>
</tr>
<tr id="newFile">
<td>
Choose a file:
</td>
<td>
<input type="file" name="file" />
</td>
</table>
<input type="text" style="display: none;" name="taskInstanceId" id="taskInstanceId">
<input id="uploadButton" value="Upload" onclick('uploadFiles()')/> //Add //the event to your submit button and remove the submit from itself
<input class="closeButton" id="closeNew" value="Close" type="button"/>
</form>
Your JQuery:
//Stays the same I would suggest using a object type and then stringify it as follows
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
//var data = new FormData();
//.each(files, function (key, value)
//{
// data.append(key, value);
//});
//data.append('documentName', $("#documentName").val());
//data.append('documentType', $("#documentType").val());
//data.append('taskInstanceId', $("#taskInstanceId").val());
// Create a objectobject and add the files
var data;
data = {
documentName:$("#documentName").val(),
documentType:$("#documentType").val(),
taskInstanceId:$("#taskInstanceId").val(),
uploadedfiles: files
}
var json = JSON.stringify(data);
$.ajax({
url: '/SafeSiteLive/formTask2.do',
type: 'POST',
data: json,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data, textStatus, jqXHR)
{
if (typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
In your controller:
As you are working with MVC, please use a Model as it is the correct fashion to catch a parameter.
public String handleFormTaskUpload2(UploadedFile mynewUpload )
{
//rest of code here
}
Your Model will then look something to this.
public class UploadedFile
{
public string documentName{get;set}
public string documentType{get;set}
public string taskInstanceId{get;set}
prop List<byte[]> files {get;set}
}
Hope this helps, please let me know if you still don't understand

onkeypress event not work properly in Mozilla Firefox Web Browser

I have a html table with onkeypress event Like :
<tr onclick="RowOnClickEvent();" class="PikerBodyRowStyle" onkeypress="return Test(event);">
<td class="PikerCellStyle" style="width:10px; text-align:left"> <input type="checkbox" value="#item.AccountHeadID" name="chkBox" /> </td>
<td class="PikerCellStyle" style="width:150px; text-align:left">#Html.DisplayFor(modelItem => item.AccountCode)</td>
<td class="PikerCellStyle" style="width:160px; text-align:left">#Html.DisplayFor(modelItem => item.AccountHeadName)</td>
</tr>
And my JavaScript function like :
function Test(e) {
// debugger;
if (e.keyCode == 13) {
if (SelectedItemID > 0) {
$.ajax({
type: "GET",
dataType: "json",
url: '#Url.Action("GetData", "ChartsOfAccount")',
data: { id: SelectedItemID },
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (xhr, status, error) {
alert(error);
}
});
}
return false;
}
}
its work good in Internet explorer but Mozilla Firefox not work.
Change
onkeypress="return Test(e);"
to
onkeypress="return Test(event);"
You cannot give a javascript action to a tablerow. Instead you can use some button or link to create your action. You can also put it in td tag. javascript actions works there.

Categories

Resources