Updating input in each row with ajax - javascript

I have a table showing a list of 'sightings' in my case and each specific column can be updated as the value are displayed in field, etc. Each individual row has an update button on it where I would like to click when I have finished updating that particular row. This is my forEach loop displaying all the entries:
<c:forEach var="mySightings" items="${mySightings}">
<tr>
<td><input name="id" class="data sighting_id" disabled value="${mySightings.id}"/></td>
<td><input name="total_pests" type="number" value="${mySightings.total_pests}"/></td>
<td><input name="date" type="date" value="${mySightings.date}"/></td>
<td><input name="username" disabled value="${mySightings.username}"/></td>
<td><textarea name="information">${mySightings.information}</textarea></td>
<td>
<button class="update_sighting btn btn-success">Update</button>
</td>
<td>
<button class="delete_sighting btn btn-danger" value="${mySightings.id}">Delete</button>
</td>
</tr>
</c:forEach>
This is my Ajax function, which I think is definitely wrong:
$(".update_sighting").click(function(){
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/updateSighting",
data: $(this).serialize(),
success: function(response) {
$("#alert").show();
alert("Submitted");
$(".errormsg").hide();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
Do I need to change something to my ajax code? I dont know what I should do next?
And my Controller which handles the request:
#RequestMapping(value = "/updateSighting", method = RequestMethod.POST)
public #ResponseBody String updateUser(Sighting sighting, Model model) {
sightingsService.updateSighting(sighting);
List<Sighting> sightings = sightingsService.getAllSightings();
model.addAttribute("sightings", sightings);
return "allSightings";
}
Please help, Thanks

The issue is with serialising the data. You are calling it on the button element instead of a form, but even then that would serialise the entire form, not just the row which was clicked on. So you need to build the object to serialise manually:
$(".update_sighting").click(function(){
var $row = $(this).closest('tr');
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/updateSighting",
data: {
id: $('input[name="id"]', $row).val(),
total_pests: $('input[name="total_pests"]', $row).val(),
date: $('input[name="date"]', $row).val(),
username: $('input[name="username"]', $row).val(),
information: $('input[name="information"]', $row).val()
},
success: function(response) {
$("#alert").show();
alert("Submitted");
$(".errormsg").hide();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});

Related

Changing from a textbox onblur to onKeyDown event

I have the following code on my partial view:
#foreach (var lineItem in Model.LineItems)
{
<tr>
<td>
<img src="#Url.Action("GetImage", "ImageBlocks", new { imageID = lineItem.Product.SelfOrDefault().Image.SelfOrDefault().ImageId, Width = 75 })" alt="Thumbnail" />
</td>
<td>
<span title="#(lineItem.Description ?? "")" id="lineItemDescription">#(lineItem.Product.ReceiptName ?? "")</span><br />
<span id="lineItemSKU">#lineItem.Product.SKU</span>
</td>
<td>
<span>#((lineItem.Product.InventorySummary ?? 0).ToString())</span><br />
</td>
<td><input type="text" id="lineItemQuantity" name="lineItemQuantity" value="#lineItem.Quantity" onblur="changeCartQty(#lineItem.Product.SKU,this.value)" /></td>
#if (lineItem.Discount != null ? lineItem.Discount.DiscountCategory != DiscountCategory.ORDER : true)
{
<td>
<input type="text" id="lineItemAmount" name="lineItemAmount" value="#lineItem.AdjustedUnitPrice.Value.ToString("C")" /><br />(Adj. #(lineItem.DiscountDisplayValue))
</td>
<td>#lineItem.AdjustedTotalLinePrice.Value.ToString("C")</td>
}
else
{
<td>#lineItem.BaseUnitPrice.Value.ToString("C")</td>
<td>#lineItem.TotalLineBaseValue.ToString("C")</td>
}
<td>Remove</td>
</tr>
}
<script>
On the lineItemQuantity text input, I want to change this from onblur to an onKeyDown event to capture the "Enter" key pressed to call the changeCartQty function with the same parameters. Here is the function being called:
function changeCartQty(ProductId, Quantity) {
var userId = $('#ID').val();
$.ajax({
url: "/Orders/AddtoCart",
type: 'POST',
cache: false,
datatype: 'json',
async: false,
data: { "ProductID": ProductId, "Quantity": Quantity, "UserID": userId},
success: function (data) {
console.log("Adjusted Quantity in cart");
success(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.error("[Error in Ajax request, adjust price] Code:" + jqXHR.status + "Error: " + errorThrown + " \nText Status: " + jqXHR.resonseText);
}
})
};
This works fine and the amounts update, I just need to change this to an onChange and I am unsure how this would be done.
Thanks.

Shopify Trying to update a customer

I'm trying to create a view where my customer can update his personal info (like First Name, Last Name, email, ect) using Liquid/JS, but I have failed epicly.
The nearest point that I have reached is this post where they use a form and some AJAX to update but I'm getting code 500. This is the code that I'm using (based on that).
<form action="/a/custmeta" method="POST" id="custmeta">
<input type="text" name="customer[id]" value="{{ customer.id }}" />
<input type="text" name="customer[first_name]" value="{{ customer.first_name }}" placeholder="namespace1.key1" />
<input type="text" name="customer[last_name]" value="{{ customer.last_name }}" placeholder="namespace2.key2" />
<input type="submit" />
</form>
<script>
$('form#custmeta').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
data: $(this).serialize(),
url: '/admin/customers/#{{ customer.id }}.json',
success: function (data) {
var formValid = (data.status === 'OK');
if (formValid) {
var msgs = '';
for (var i=0;i<data.messages.length;i++) {
msgs += '-- ' + data.messages[i] + '\n';
}
if (msgs > '') {
alert('SUCCESS WITH MESSAGES:\n\n' + msgs);
}
else {
alert('SUCCESS!');
}
}
else {
alert('Status: ' + data.status + '\nMessage: ' + data.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('AJAX or Server 500 error occurred');
}
});
return false;
});
</script>
found this other post where you could do it using the API but dont know how to use it.
Any help?

Issue with AJAX call

My AJAX call to a JSP works when called with drop down menu, but when called with the submit button the content disappears and the page refreshes.
function najax() {
$.ajax({
url:"testjsp.jsp",
type: "post",
data: {
crid: crid,
sid: sid,
ttid: ttid
},
async: false,
cache: true,
error: function(xhr, status, error) {
alert("error" + error);
alert("xhr" + xhr);
alert("status" + status);
},
sync: true,
success: function(responseText) {
$("#disp_span").html(responseText);
}
});
}
Call to the code:
<input type="submit" name="Submit " id="submit" value="Submit" class="btn" onClick="najax();" ></input>
If I add a drop down menu then it works .
<select name="select_menu1" onChange="najax();">
<option value=" ">Select</option>
<option value="cr_id">SUBMIT</option>
<option value="sr_id">CANCEL</option>
If you want to make the ajax call with submit button ,then add the submit event to the form.
if you want to prevent the button from submitting the form and perform ajax operation ,then prevent the default action
$('#submit').click(function(e){
e.preventDefault();
....//ajax call
});
To avoid submitting of the form change the input type to button
<input type="button" name="Submit " id="submit" value="Submit" class="btn">
Then on button click call the function
$('#submit').click(function() {
//najax()
//Or call the ajax directly
$.ajax({
url: "testjsp.jsp",
type: "post",
data: {
crid: crid,
sid: sid,
ttid: ttid
},
async: false,
cache: true,
error: function(xhr, status, error) {
alert("error" + error);
alert("xhr" + xhr);
alert("status" + status);
},
sync: true,
success: function(responseText) {
$("#disp_span").html(responseText);
}
});
})
Stop the from submit as follows
$("#formid").submit(function () { return false; });
or better yet, just use a type="button" button
You put the ajax request in a function, but you dont call it on the submit button like you do on the drop down menu onChange="najax();"
<input onClick="najax();" type="submit" name="Submit " id="submit" value="Submit" class="btn"></input>
this should work or use jquery to do that for you. :)

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

selected checkboxes(dynamically created) values should be set to destination text field

For destination text field, based on the input, the auto suggestion will be displayed as checkboxes. I can select one or more values and my requirement is to get these selected values on the controller side, Once I click on the search button. How can I achieve this for dynamic checkboxes, please provide any suggestions.
jquery:
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
HTML:
<form method="post" id="searchForm" action="someAction/showStatistics" id="ems">
<label>Destination</label>
<input type="text" id="destinationName" name="destinationName" value="${someForm.destinationName}" class="field" />
<div class="dest"></div>
<input type="submit" class="button" value="search" />
</form>
Try this
$(document).ready(function () {
var dynamicCheckbox = [];
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
};
});
}
});
$('.button').on('click', function (event) {
event.preventDefault();
$('.dest input:checked').each(function() {
dynamicCheckbox.push($(this).attr('name'));
});
console.log(dynamicCheckbox);
});
});
Here in dynamicCheckbox you will get the names of the checked checkboxes.
Hope that's what you need!

Categories

Resources