Jquery Setting Value of html Label at index position in loop - java

I have an ajax call and i would like in the success function to loop through every label in a class and set their value to that which has been returned from the server response. Under is the code however this sets all the labels to the same value, this is not what i want i would like to access the index of that item and set only that index to the response value. Where am i going wrong here?:
JQuery:
function GetCitizenTypeDescription(citizenTypeId){
$.ajax({
type:'GET',
url:'getCitizenTypeDescription.htm',
data:{citizenTypeId:citizenTypeId},
dataType: 'text',
success: function (data) {
$('.citizenTypeDesc').each(function(i){
alert(data);
$('.citizenTypeDesc').text(data);
});
}
});
}
$(document).ready(function() {
$(".photos").each(function(i){
if ($(this).val() != '') {
var image = new Image();
image.src = $(this).val();
image.onload = function(){
var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
ctx.drawImage(image,0,0, 320, 240);
}
}
});
$('.citizenTypeDesc').each(function(i){
var citizenTypeId = document.getElementsByClassName("citizenTypeId")[i].value;
GetCitizenTypeDescription(citizenTypeId);
});
});
The console returns the correct data i just need to write it to the labels
Console:
GET http://localhost:8084/crimeTrack/getCitizenTypeDescription.htm?citizenTypeId=2 200 OK 174ms
Response
CRIMINAL
GET http://localhost:8084/crimeTrack/getCitizenTypeDescription.htm?citizenTypeId=3 200 OK 174ms
Response
VICTIM
GET http://localhost:8084/crimeTrack/getCitizenTypeDescription.htm?citizenTypeId=4 200 OK 174ms
Response
....
html
</head>
<body>
<div id ="content">
<c:forEach items="${citizens}" var="citizen">
<div id="table">
<div>
<p><canvas class="canvas" height="240" width="320"></canvas>
</div>
Name:- ${citizen.fName} ${citizen.lName}
<input type="hidden" id="photo" value="${citizen.photo}" class="photos"/>
<input type="hidden" id="socialSecurityNumber" value="${citizen.socialSecurityNumber}" />
<input type="text" class="citizenTypeId" value="${citizen.citizenTypeId}"/>
<label class="citizenTypeDesc"></label>
</div>
</c:forEach>
</div>
</body>
</html>

Instead of looping over all of the .citizenTypeDesc labels you could loop over all of the .citizenTypeId. Test if each value matches the parameter and then set the label that is within the same parent element.
function GetCitizenTypeDescription(citizenTypeId){
$.ajax({
type:'GET',
url:'getCitizenTypeDescription.htm',
data:{citizenTypeId:citizenTypeId},
dataType: 'text',
success: function (data) {
$('.citizenTypeId').each(function(i){
//does this value match the parameter
if($(this).val() === citizenTypeId){
//find the parent div, in this case .table
var parent = $(this).parent();
//search for a child with class .citizenTypeDesc
var thisCitizenTypeDesc = parent.children('.citizenTypeDesc');
thisCitizenTypeDesc.text(data);
}
});
}
});
}

Related

Example of AJAX Request on PHP?

I am new to AJAX Request, and my project need help.
JQuery / AJAX part :
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'ajax_save.php',]
success: function(msg) {
alert(msg);
}
error: function(msg) {
alert('error');
}
});
});
});
</script>
html part :
<input type="text" id="txt" name="text" />
<span id="txt">Result Maybe Here</span>
<button>Get External Content</button>
ajax_save.php
echo base64_encode( $_GET["text"] );
This don't really perform well, and just silent with out any trace.
Example of performing well :
<input type="text" id="txt" name="text" /> >>> agnes (user type)
<span id="txt">Result Maybe Here</span> >>> YWduZXM= (result)
<button>Get External Content</button>
About Ajax
To perform AJAX request on browser(client side), you need JavaScript. Maybe you can take a look at jQuery.ajax. $.get('process.php?text=something');
To perform AJAX request in PHP(server side), use file_get_contents('process.php?text=something');
To make your code work, you should perform a GET request instead of a POST one:
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: 'ajax_save.php?text=' + $('#text').val(),
success: function(msg) {
$('#span').text(msg)
}
error: function(msg) {
alert('error');
}
});
});
});
</script>
And every id in your HTML element should be unique, so they shouldn't both be id="txt".
About Base64
BTW, if you're just going to perform Base64 encoding, why not do it in JavaScript?
$(function(){
$('#text').on('input', function(){
$('#span').text(btoa($(this).val()));
});
});
<input type="text" id="text" name="text" />
<span id="span">Here the result!</span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

post comments using jsp, servlet and ajax

I am trying to create a comment section using jsp, servlet and ajax. The problem I am facing is that each comment replaces it's previous one instead of showing next to it.
Highly appreciate any kind of help.
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitBtn').click(function() {
var cmt = $('#cmt').val();
$.ajax({
type : 'POST',
data : {
cmt : cmt,
action : 'EnterMsg'
},
url : 'SubmitComment',
success : function(result) {
$('#view2').text(result);
}
});
});
});
</script>
</head>
<body>
<fieldset>
<legend>Enter Message</legend>
<form>
Ques.<input type="text" id="cmt"> <input type="button"
value="Send" id="submitBtn"><br> <span id="post1"></span>
</form>
</fieldset>
<fieldset>
<legend>View Message</legend>
<form>
<div id='view2'></div>
<br>
</form>
</fieldset>
Try
var html='';
$.ajax({
dataType: "json",
url: "SubmitComment",
error: function () {
alert('error occured');
},
success: function (result) {
for(var key in result) {
var value = result[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#view2").append(html);
}
});
Instead of
success : function(result) {
$('#view2').text(result);
}
Because of you get multiple comments from the ajax respose and you have to iterate each one of them and append to your div tag

how to set a time limit for a REST call made with angularjs ngResource ($resource)

I'm using angularjs to call a java api using REST.
var app = angular.module("MyApp", ["ngResource","ngProgress"])
.factory('ConnectionData',function ($resource){
return $resource('URI');
});
function connectionTestController($scope,ConnectionData,ngProgress,$timeout){
$scope.connectionTest = function(){
var success = function(data, getResponseHeaders){
ngProgress.complete();
$scope.datas = data;
$('#testConnectionBtn').attr("disabled", false);
};
var failure = function(data){
if(data.status == 404) {
$scope.errorString = data.status+", Request Error, Try Again";
}else{
$scope.datas = data.data;
$scope.errMessage = $scope.datas.message;
}
ngProgress.complete();
$('#testConnectionBtn').attr("disabled", false);
};
ConnectionData.get(success,failure);
};
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<div class="col-md-4" ng-controller="connectionTestController">
<h1>Connection Test</h1>
<p><button class="btn btn-primary" ng-click="connectionTest()" id="testConnectionBtn">Click to Test</button></p>
Code: <label id="code">{{datas.code}}</label><br>
Status: <label id="status">{{datas.status}}</label><br>
Data: <label id="data">{{datas.data}}</label><br>
Message: <label id="message">{{errMessage}}</label><br><br>
<label id="customeError">{{errorString}}</label><br>
</div>
REST call is being made when the button is clicked. I want to put a time limit to the request. (example: 30 seconds.) If the reply isn't received within the time limit then it should display an error message.
You can set an timeout option on your actions, something like:
{
'get': {method:'GET', timeout:2000},
'save': {method:'POST', timeout:2000},
'query': {method:'GET', isArray:true, timeout:2000},
'remove': {method:'DELETE', timeout:2000},
'delete': {method:'DELETE', timeout:2000}
};
this can be done in the ConnectionData factory.
After that, you can all it like this:
ConnectionData.get({id:'SomeId'}).$promise.then(success).catch(failure);
Does that make sense?

jQuery setting input field value

I have a form to edit user and i would like to insert user data from database into forms' fields. What i do is
Link
Edit
Script
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
}
Form
<div id="edit-form" title="Edit user">
<p class="validateTips">All form fields are required.</p>
<form:form>
<fieldset>
<label for="elogin">Login</label>
<input type="text" name="elogin" id="elogin" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form:form>
</div>
My Spring controller returns following(in wrapper i have field login)
#RequestMapping(value="/edit/{userLogin}", method=RequestMethod.POST)
#ResponseBody
public Wrapper edit(#PathVariable String userLogin) {
return wrapper.wrap(userService.findByLogin(userLogin));
}
But the form is empty. I also tried to set manual values but still no use. Please help me set input field value.
You should send your form data with your post request.
$.ajax({
url: url,
type: "POST",
data:$('form').serialize(),
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('#elogin').val(resp.login);
}
})
}
Should work just fine, as you've set an ID for the input.
Not quite sure you have the order right, surely you would make the ajax call first and then open up the jQuery dialog?
Either way, you could supply data into the dialog as follows;
//call ajax method to get value you want to show.
var somevariable = etc.....
var dto = {
loginName: somevariable
}
$( "#edit-form" ).data('params', dto).dialog( 'open' );
Then in your dialog use the open() method.
$("#edit-form").dialog({
bgiframe: true,
autoOpen: false,
height: 280,
width: 320,
draggable: false,
resizable: false,
modal: true,
open: function () {
//so values set in dialog remain available in postback form
$(this).parent().appendTo("form");
//get any data params that may have been supplied.
if ($(this).data('params') !== undefined) {
//stuff your data into the field
$("#elogin").val($(this).data('params').loginName);
}
}
});

The request was rejected because no multipart boundary was found

I am using a Form in a LightBox which contains some input element.
<form name="imageUploadForm" action="uploadImage.do" method="post" enctype="multipart/form-data">
<input type="text" id="id" name="id" style="display: none;" value="">
<div id="fileUploaderDiv">
<input type='file' name="file0" id ="file0" />
</div>
<input type="submit" value="Submit">
</form>
when i am submitting the form than the form redirect to it's action location. I just want to submit form without redirecting user, so user stay on lightbox without loosing his data.
I have tried jquery ajax call for this
var data = new FormData();
var $inputs = $('#imageUploadForm :input');
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
data.append(this.name, $(this).val());
});
$.ajax({
url: 'uploadImage.do',
data: data,
cache: false,
contentType: 'multipart/form-data',
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
But getting error at server side in my FileUploader servlet.
The request was rejected because no multipart boundary was found
can anybody tell me what am i missing in this ?
You need to prevent the default action of submitting the form:
$('form[name="imageUploadForm"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'uploadImage.do',
data: data,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
});
I believe you should set the contentType option to false when using the FormData class, forcing jQuery not to add a Content-Type header, otherwise the boundary string will be missing, and that's probably the reason for your server error.
You must also leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Here is the simplest form of a form submit using jquery Ajax. I have not tested this but it should work :-)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test form</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#sbmt').click(function(){
var text1 = $('#text1').val();
var text2 = $('#text2').val();
/// validation of inputs
///then
$.ajax(
{
url :'submit.php',
type : 'post',
data : {'text1' : text1, 'text2' : text2 },
success: function(data){
alert("form submitted . response is :"+ data);
}
}
).fail(function(){alert("Failed!!");});
});
});
</script>
</head>
<body>
<form id="myform">
<input type="text" id="text1" />
<input type="text" id="text2" />
<input type="button" id="sbmt" value="submit"/>
</form>
</body>
</html>

Categories

Resources