I am implementing a messanger using Jax-Rs. I have a client application which use the implemented API. within the database message_id,message,date, sender fields are stored. I need to display these values within a div of jsp page of the client application.
client.jsp
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
<script>
function onTechIdChange() {
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details)
{
dispatchEvent(event)
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
Through this code nothing is displayed in the div. But values are printed in the tomcat console which ensures that all the methods within API are working properly. Do you have any idea? Thank you in advance
UPDATE
I Updated the javascript code snippet. But nothing is displayed inside the <p> tag
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details.sender)
{
display(name);
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
This is the section with the <p>
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
If somebody knows a tutorial regarding this can you upload a link?
I think you are not calling the display function that add the values to the DOM.
for(name in details){
display(name)
}
Also I am not sure that your parser is correct
success : function(result) {
var details = result[0]; -- Extract the first value of response
var name;
for(name in details) --- should be an array as well
{
dispatchEvent(event) -- I think here you need to call print function
}
alert(details.sender); -- If details.sender have the details probably the
iteration should be for(name in details.sender)
},
Also I reconsider the use of $.ajax, probably use $.get is better and also, use jsp I dont think is needed use a simple html with a javascript.
Related
I made this coding myself recently but just simply doesn't seem to work. This code is supposed to get the value of the name I've submitted and using ajax, if the name equals, "James", the code is supposed to return "Hello James" and just "Hello" for other names inputted. The response when the input is not "James" sort of works, but it only works some of the time and I also hope to fix that.
Tried reviewing some of my codes
<fieldset>
<form style="padding:15px;">
<label for=name>Enter Name:</label>
<input type="text" name="name" id="name">
<br>
<input type="submit" style="margin: 15px;" value="SUBMIT" id="submit">
</form>
</fieldset>
<div id="result"></div>
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var send = {
name: "name"
};
$.ajax({
type: "POST",
url: "process2.jsp",
data: send,
success: function(data) {
$("#result").html(data);
}
})
});
});
<% if(request.getParameter("name").equals("James"))
{
<% out.println("Hello James"); %>
} else { %>
<% out.println("Hello"); %>
<% } %>
I want to pass some text input as array string to angular controller. I'm able to send single input as POST param and get it in Serlvet by using String key = request.getParameter("key");
This is my form
<form ng-controller="FormController" ng-submit="submitForm()" class="ng-valid ng-scope ng-dirty ng-valid-parse">
<p>Text1: <input type="text" name="ancestor" ng-model="blob.ancestor" class="ng-valid ng-dirty ng-touched ng-empty"></p>
<p>Text2: <input type="text" name="ancestor" ng-model="blob.ancestor" class="ng-valid ng-dirty ng-valid-parse ng-empty ng-touched"></p>
<p><input type="submit" class="btn btn-primary" value="Confirm"></p>
</form>
and this is my js script:
var app = angular.module('myApp', []);
app.controller('FormController', FormController);
FormController.$inject = ['$scope', '$http', '$httpParamSerializerJQLike'];
function FormController($scope, $http, $httpParamSerializerJQLike) {
$scope.blob = {};
$scope.submitForm = function() {
alert(JSON.stringify($scope.blob));
$http({
method : 'POST',
url : '/javaAngularJS',
data: $httpParamSerializerJQLike($scope.blob),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
}
});
};
}
Again, i'm able to send single param but i want to send "ancestor" with multiple values and get it using String ancestors[] = reuest.getParameterValues("ancestor"); in my Post method on servlet.
Let us assume that from your backend you are getting value of ancestor as [1,2,3,4] as array . you can bind this value to input field with ng-repeat like this
In Controller:
$scope.blob = {};
$scope.blob.ancestor = [1, 2, 3, 4];
In HTML:
<form ng-submit="submitForm()" class="ng-valid ng-scope ng-dirty ng-valid-parse">
<p ng-repeat="ancestor in blob.ancestor">Text {{$index +1}}: <input type="text" name="ancestor" ng-model="ancestor" class="ng-valid ng-dirty ng-touched ng-empty"></p>
<p><input type="submit" class="btn btn-primary" value="Confirm"></p>
</form>
Now in submitForm() click we will perform this to send data to backend in array
$scope.submitForm = function() {
console.log($scope.blob); // result:{"ancestor":[1,2,3,4]}
$http({
url: 'http://localhost:8080',
method: "POST",
params: {
ancestor: $scope.blob.ancestor
}
}).success(function(data) {
console.log(data);
}).error(function(data) {
console.log(data);
});
}
The data will go in paramter and the url will look like this:
http://localhost:8080?ancestor=1&ancestor=2&ancestor=3&ancestor=4
I have this practice project that I am working on, but I cant get my UI Boostratp modal working. Using example from the site https://github.com/angular-ui/bootstrap/tree/master/src/modal I have been trying to implement this feature but without success.
I believe that this is because of that I do not have the knowledge to integrate demo code to my MVC style project (I have separate app.js, controller, and service files), and this one file example is rather confusing to me.
My folder/file structure:
Now, I have tried various things, including making a separate controller, and separate view for modal content (that's why I have bookDetailes.html and bookDetailesConreoller.js files but they are currently out of order - not connected in app.js's stat provider and their code is under comment). This is where I am:
A have a list of basic book details retrieved from data base and printed out in book.html view via data-ng-repeat. In every repeat I have an Action button that is supposed to open modal for editing or deleting that entry.
Here is my book.html file where I have nested the demo markup code from UI Bootsratp site:
<h4 class="text-center"><strong>Book Collection</strong></h4>
<br>
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Image</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Publisher</th>
<th>City of Publishing</th>
<th>Genre</th>
<th>Action
<th>
</tr>
</thead>
<tbody data-ng-init="init()">
<tr data-ng-repeat="book in books">
<td>{{book.id}}</td>
<td>{{book.image}}</td>
<td>{{book.title}}</td>
<td>{{book.author}}</td>
<td>{{book.yearOfPublishing}}</td>
<td>{{book.publisher}}</td>
<td>{{book.cityOfPublishing}}</td>
<td>{{book.genre}}</td>
<td><a class="btn btn-default" data-toggle="modal" data-ng-click="open()">Action</a></td>
</tr>
</tbody>
</table>
<div>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}</a>
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
</div>
As you can see, this last part after table tag is supposed to be modal markup taht is called when Action button is pressed and command "open()" i passed to bookController.js via data-ng-click.
My bookControler.js:
collectionsApp.controller('bookController', function($scope, bookService,
$state) {
var books = [];
$scope.save = function() {
bookService.save($scope.book, onSaveDelete);
}
$scope._delete = function(id) {
for (book in books) {
if (book.id === id) {
bookService._delete(book, onSaveDelete);
}
}
}
$scope.edit = function(id) {
for (book in books) {
if (book.id === id) {
$scope.book;
}
}
}
$scope.init = function() {
bookService.list(onInit);
}
// <-- Beginning of the modal controller code I inserted (and adopted) from the example:
$scope.items = [ 'item1', 'item2', 'item3' ];
$scope.open = function(size) {
modalInstance = $modal.open({
templateUrl : 'myModalContent.html',
controller : ModalInstanceCtrl,
size : size,
resolve : {
items : function() {
return $scope.items;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
var ModalInstanceCtrl = function($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item : $scope.items[0]
};
$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
// <-- Ending of the modal code I have inserted from the example.
onSaveDelete = function(response) {
if (response.data.status === 'success') {
$scope.init();
} else {
alert("DEBUG ALERT: SAVE/DELETE FAIL");
}
};
onInit = function(response) {
$scope.books = response.data;
books = response.data;
};
});
Now, like this, code is working in the seance that data-ng-repeat is working and I get list of database entries on page load. But when I click on the Action button i get this error message in the console:
But when I add $modal to may code like this:
collectionsApp.controller('bookController', function($scope, bookService,
$state, $modal) {
var books = [];
...
I get this error on page load:
Can someone help me understand and implement modals to my project? Thanks in advance... ;)
Add this,
angular.module('Urapp', ['ui.bootstrap']);
I am trying to make an upload page which takes file to upload. I am using Spring framework here my query is on Upload button I am calling a JavaScript method which should send my file to controller using jQuery AJAX. Is there any way to pass this through JavaScript?
Following is the code which I am trying.
<body>
<div style="text-align: center; margin-top: 60px;">
<form enctype="multipart/form-data">
Select file:
<input type="file" name="dataFile" id="fileAttachment"/><br/><br/>
<div style="text-align: center; margin-top: 100px;">
<input style="cursor: pointer;" onmouseover="" onclick="uploadAttachment()" class="dialogbox" type="submit" value="Upload Report" />
</div>
</form>
</div>
</body>
JS:
<script language="Javascript">
function uploadAttachment(){
var Name = jQuery('#Name option:selected').text();
jQuery.post('upload',{Name:Name}
function(data){
if(data==1)
alert("success");
else
alert("failed");
});
}
</script>
on controller.java page following is the code written
#RequestMapping(value = "upload", method=RequestMethod.POST)
public #ResponseBody String upload(HttpServletRequest request, HttpServletResponse response,
#RequestParam("Name") String Name){
System.out.println(Name);
}
If you are in fact seeking a pure javascript way to upload an image/file, then the following tutorial from 2009 will tell you exactly how to do that:
http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html
I ran into this when I wanted to add basic-authentication to a form submission, without enabling cookies. E.g. when you have username/password fields with your filename, file, etc fields.
Hope this helps!
I think you can try the following code to upload file with javascript.
function uploadAttachment(){
$('#fileAttachment').trigger('click');
if (typeof timer != 'undefined') {
clearInterval(timer);
}
timer = setInterval(function() {
if ($('#fileAttachment').val() != '') {
clearInterval(timer);
$.ajax({
url: 'YOUR_UPLOAD_URL',
type: 'post',
dataType: 'json',
data: new FormData($('#fileAttachment').closest('form')[0]),
cache: false,
contentType: false,
processData: false,
success: function(response){
}
});
}
}, 500);
}
You need to replace YOUR_UPLOAD_URL with your server upload URL.
refer.jvmhost.net/refer247/registration, this is my url,i have to fetch request to this url like user details and should get the appropriate response in json format with status n error if it contains ..dont give me android code..
this is html page.
<head>
<script type="text/javascript" src="json2.js"></script>
</head>
<body>
<div data-role="page" data-theme="c">
<div data-role="header" data-position="fixed" data-inset="true" class="paddingRitLft" data-theme="c">
<div data-role="content" data-inset="true"> <img src="images/logo_hdpi.png"/>
</div>
</div>
<div data-role="content" data-theme="c">
<form name="form" method="post" onsubmit="return validate()">
<div class="logInner">
<div class="logM">Already have an account?</div>
<div class="grouped insert refb">
<div class="ref first">
<div class="input inputWrapper">
<input type="text" data-corners="false" class="inputrefer" placeholder="Userid" name="userid" id="userid" />
</div>
<div class="input inputWrapper">
<input type="password" data-corners="false" class="inputrefer" placeholder="Password" name="password" id="password" />
</div> <input type="submit" data-inline="true" value="Submit" onclick="json2()">
<p>Forgot Password
</p>
</div>
</div>
<div class="logM">New user? Create refer Account</div>
<input type="button" class="btnsgreen" value="Sign Up! its FREE" class="inputrefer" data-corners="false" data-theme="c" />
</form>
</div>
</div>
<p style="text-align: center;">© refer247 2013</p>
</div>
</body>
this is json2.js
function json2()
{
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
//var parsed = jsonString.evalJSON( true );
alert(json1["username"]);
alert(json1["password"]);
};
so tell me how to send the json data to that url n obtain some response like if email
id is already exist if u registering with that id ..then give some error
like email id already exist n if registerd succesfully then give respone like registerd successfully and status msg..200 okk...
You can use ajax to post json data to specified url/controller method. In the below sample I am posting an json object. You can also pass each parameter separately.
var objectData =
{
Username: document.getElementById('userid').value,
Password: document.getElementById('password').value
};
var objectDataString = JSON.stringify(objectData);
$.ajax({
type: "POST",
url: "your url with method that accpects the data",
dataType: "json",
data: {
o: objectDataString
},
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
And your method can have only one parameter of string type.
[HttpPost]
public JsonResult YourMethod(string o)
{
var saveObject = Newtonsoft.Json.JsonConvert.DeserializeObject<DestinationClass>(o);
}
$.ajax({
url: urlToProcess,
type: httpMethod,
dataType: 'json',
data:json1,
success: function (data, status) {
var fn = window[successCallback];
fn(data, callbackArgs);
},
error: function (xhr, desc, err) {
alert("error");
},
});
function addProductById(pId,pMqty){
$.getJSON("addtocart?pid=" + pId + "&minqty="+ pMqty +"&rand=" + Math.floor((Math.random()*100)+1), function(json) {
alert(json.msg);
});
}
Here is a simple example, which will call on button click or onclick event and call addtocart servlet and passes 2 argument with it i.e. pId and pMqty.
and after successful completion it return message in alert which is set in that servlet in json.
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
$.ajax({
url: '/path/to/file.php',
type: 'POST',
dataType: 'text',//no need for setting this to JSON if you don't receive a json response.
data: {param1: json1},
})
.done(function(response) {
console.log("success");
alert(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
on the server you can receive you json and decode it like so:
$myjson=json_decode($_POST['param1']);