Unable to initiate ajax call from jquery - java

I am new to ajax and jquery and trying to place an ajax call in my code. But below are the error messages I get when placing alerts:
jqxhr.status = 404
thrown error = Not Found
jqxhr.statusText = Not Found
request = undefined
error = undefined
What I want to do:
Open a modal dialog with just a Fancy text box (Tinymce) on click of an "Edit gif". After the contents are edited in the textbox, and the "Save" button in the modal dialog is clicked, initiate an ajax call to save the contents in the Database.
What is happening:
The modal dialog opens correctly, I am able to see that the "data" part for the ajax call is populated correctly (placed alerts to confirm). I believe the url is also correct. If I type the url in a browser, the control does go to my servlet as per web.xml (Sysout in Servlet gets printed). But somehow, the ajax call never goes through to the server after click of "Save" button. Will be really great if one of you can help me out here, will greatly appreciate it. My JSP (copied what I feel is relevant alone):
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="css/sis.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/jquery-ui-1.10.3.custom">
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/tinymce/tinymce.min.js"></script>
<script>
$(function() {
$("#dialog-form2").dialog({
autoOpen: false, width: 500, modal: true,
buttons: {
"Save": function() {
tinymce.get("stChallenge").setContent(tinyMCE.get("edChallenge").getContent());
alert($("#ChalId").val());
alert(tinyMCE.get("edChallenge").getContent());
var xhr =
$.ajax({
url: "/AjaxServlet?method=updateChal&keyword=dummy",
type: "GET",
data: {
CommentId: $("#ChalId").val(),
challenge: tinyMCE.get("edChallenge").getContent()
},
success: function (result) {
alert("Success :" + result);
$(this).dialog("close");
},
error:function (jqxhr, ajaxOptions, thrownError, request, error) {
alert('jqxhr.status = ' + jqxhr.status + '\n' + 'thrown error = ' + thrownError + '\n' + 'jqxhr.statusText = ' + jqxhr.statusText + '\n' +
'request = ' + request + '\n' + 'error = ' + error);
$(this).dialog("close");
}
});
},
Cancel: function() {
$(this).dialog("close");
}
},
close: function() {
}
});
$("#Edit2")
.click(function() {
$("#dialog-form2").dialog("open");
});
});
</script>
<script type="text/javascript">
tinymce.init({
selector: "#edChallenge", theme: "modern",
plugins: [
],
image_advtab: false
});
</script>
<script type="text/javascript">
tinymce.init({
selector: "#stChallenge", theme: "modern", readonly: true, toolbar: "false", menubar: "false",
plugins: [
],
image_advtab: false
});
</script>
</head>
<body>
<c:set var="model" value="${sessionScope.model}" />
<html:form action="managePerf.do?method=showPerf" method="post" styleId="ManagePerfForm">
<html:errors/>
Date: <html:text property="rankDate" styleId="datepicker" name="ManagePerfForm" />
<html:submit value="Go" styleClass="input button"/>
<fieldset>
<table border="0">
<tr>
<td>
<div id="dialog-form2" title="Edit Challenges">
<form>
<textarea cols="75" rows="50" id="edChallenge">${comments}</textarea>
</form>
</div>
<label>Challenges</label>
<a href="javascript:void(0);" id="Edit2">
<img src='${pageContext.request.contextPath}/img/Edit.gif' height="32" width="32"/>
</a>
<div id="dTextBox" class="ui-widget">
<textarea cols="75" rows="15" id="stChallenge" readonly="true">${comments}</textarea>
</div>
<input type="hidden" id="ChalId" value=${CommentId} />
</td>
</tr>
</table>
</fieldset>
</html:form>
</body>

Related

How to create editable combobox with database?

I am new to java and want to create an editable combobox in which when user types in it the results come from database.
Like if I type "e" in combobox then all the name starting with "e" should come from database.
Please give a simple example.
You can use jQuery plugins, following example is for php just replace the php parts with java code, or have a look at this.
With JSON
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "SearchController",
type : "GET",
data : {
term : request.term
},
dataType : "json",
success : function(data) {
response(data);
}
});
}
});
});
});
With DB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Remote datasource</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.ui-autocomplete-loading {
background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
</style>
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</body>
</html>

how to use jquery ajax in jsp ?

i have written a small code which inclued 2 jsp pages and
1) test2.jsp --> i have made a dropdown in this page
2) test3.jsp --> displays a welcome message when the person selects an option from the dropdown ,
he will migrate to this page without refreshing test2.jsp
for this i have used ajax jquery
when i click on the submit button nothing happens , please help me with this
i have also put the org.json.jar file in the libraries
test2.jsp code
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//malsup.github.com/jquery.form.js"></script>
<script>
function check()
{
$.ajax({
url: "test3.jsp",
type: "GET",
success: function() {
alert("succes");
},
error: function() {
alert( "Sorry, there was a problem!" );
}
});
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br>
<form method="post" action="test2.jsp">
<select name="city">
<option value="dropdown">select city</option>
<option value="jal">Jalandhar</option>
<option value="ggn">Gurgaon</option>
<option value="noida">Noida</option>
<option value="amrtsr">Amritsar</option>
<option value="bombay">Bombay</option>
</select>
<input type="submit" value="Submit" onclick="check()">
</form>
test3.jsp code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>welcome</h1>
</body>
</html>
The function should return false to prevent form submittion
<script>
function check() {
$.ajax({
url: "test3.jsp",
type: "GET",
success: function() {
alert("succes");
},
error: function() {
alert( "Sorry, there was a problem!" );
}
});
return false;
}
</script>
It should be
<input type="button" value="Submit" onclick="check()">
instead of
<input type="submit" value="Submit" onclick="check()">
because submit input type call form's action that is test2.jsp.
call your javascript function on change event of drop down
onchange="check()"
and navigate through firebug and check your consol it will show you your whole ajax request

Send sms in Cordova 3.4

I am new in cordova 3.4. I want to write send sms app. I get SMSPlugin from github but i want to write this myself. I write a html file like this and copy in root/www and i write a java script file in root/www/js. but when i run the app, i don't see button in the page! Why? What is problem? How can i write this app?
And i change name of java file(Activity) from AndroidManifest manually to my class, this is not a problem, Yes? and i changed 'id' in widget tag from config.xml to my package manually.
index.html:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
<script type="text/javascript">
var txtMSG = "";
function onDeviceReady(){
document.getElementById("deviceName").innerHTML= device.model;
document.getElementById("version").innerHTML= device.cordova;
document.getElementById("mobilePlatform").innerHTML= device.platform;
document.getElementById("platformVersion").innerHTML= device.version;
document.getElementById("uuid").innerHTML= device.uuid;
document.getElementById("sendSMS").style.display="block";
}
function displayTextMessage(msg){
alert(msg);
$('#text-messages').prepend('<div>' + msg + '</div>');
}
function sendConsole(){
var message = "This_is_a_test"
DeviceInfo.SendConsole({text: message}, function(){
alert("success");
}, function(){
alert("fail");
});
}
function SendSMS(){
console.log("-------------------Start----------------------");
DeviceInfo.SendSMS({phoneNumber:[document.getElementById('cellNumber').value], text: document.getElementById('textMessage').value}, function(){
alert("success");
}, function(){
alert("fail");
});
console.log("---------------------End--------------------");
}
/** Called when browser load this page*/
function init(){
document.addEventListener("deviceready", onDeviceReady, false);
}
</script>
</head>
<body>
<input id="sendSMS" style="display:none" type="button" ontouchend="SendSMS()" onclick="SendSMS()" value="Send SMS To:" />
<!-- <button onClick="SendSMS();">Send SMS</button> <br> -->
<input id="cellNumber" type="text" style="width:100%" value="9126012134" onclick="this.select()" ontouchend="this.select()" />
<textarea id="textMessage" style="width:100%; height:100px">Plugin Example</textarea>
<input id="sendConsole" style="display:none" type="button" ontouchend="sendConsole()" onclick="sendConsole()" value="Send Console Log" />
<div id="text-messages" style="border:solid 1px #efefef; padding 10px"></div>
</body>
</html>
DeviceInfo.js:
var DeviceInfo = function () { };
DeviceInfo.callMethod = function (methodName, content, success, fail) {
return PhoneGap.exec(function (args) {
success(args);
}, function (args) {
fail(args);
}, 'DeviceInfo', methodName, [content]);
}
DeviceInfo.GetPhoneNumber = function (content, success, fail) {
return DeviceInfo.callMethod('getPhoneNumber', content, success, fail);
};
DeviceInfo.SendSMS = function (content, success, fail) {
return DeviceInfo.callMethod('SendSMS', content, success, fail);
};
DeviceInfo.SendConsole = function (content, success, fail) {
return DeviceInfo.callMethod('SendConsole', content, success, fail);
};
Thanks for advises
There is a plugin on ghithub developed by javatechig here but only work with old cordova/phonegap version. This fork https://github.com/aharris88/phonegap-sms-plugin works with recent version of cordova and is updated frequently. Read the "readme.md" for example and more informations.
This Android Phonegap plugin allows you to easily send SMS in android using both native SMS Manager or by invoking the default android SMS app

How to print google-annotated-chart by clicking on print button, just like normal print as save it as a pdf programatically?

How to print Google annotated chart by clicking on print button in a web page?
In my code, I used window.print() method, but when I print the page, chart disappears from the webpage and rest of the content is printing.
Please help me.
<!DOCTYPE html> <html> <head>
<title>Google Chart with jsp Mysql Json</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"><!--
css for datepicker -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script><!--
Javascript for datepicker -->
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]}); $(document).ready(function(){
showGoogleChart('2013-12-01','2013-12-31');
//============================= Onpage load calling chart function
$( "#from" ).datepicker({ changeMonth: true,
dateFormat:'yy-mm-dd', numberOfMonths: 3, onClose: function(
selectedDate ) { $( "#to" ).datepicker( "option", "minDate",
selectedDate ); } }); $( "#to" ).datepicker({
dateFormat:'yy-mm-dd', changeMonth: true, numberOfMonths: 3,
onClose: function( selectedDate ) { $( "#from" ).datepicker(
"option", "maxDate", selectedDate ); } }); });
//==================== OnChange date call google chart
================== function getChartdate(){ alert("hi"); var startdate = $('#from').val(); var enddate = $('#to').val();
showGoogleChart(startdate,enddate); //===========On button click
calling chart function========= }
function showGoogleChart(startdate,enddate){
var queryObject="";
var queryObjectLen="";
var postdata = {"startDate":startdate,"endDate":enddate};
$.ajax({
type : 'POST',
url : 'testPages.jsp',
data:postdata,
dataType:'json',
success : function(data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length;
google.setOnLoadCallback(drawChart(queryObject,queryObjectLen));
},
error : function(xhr, type) {
alert('server error occoured')
}
});
}
function drawChart(queryObject,queryObjectLen) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'date');
data.addColumn('number', 'temp');
for(var i=0;i<queryObjectLen;i++)
{
var name = queryObject.empdetails[i].date;
var empid = queryObject.empdetails[i].temp;
data.addRows([
[name,parseInt(empid)]
]);
}
var options = {
title: 'Employee Information',
}; var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options); }
</script>
</head>
<body>
<div style="margin: 50px;">
<label for="from">From</label> <input type="text" id="from" name="from"> <label for="to">to</label> <input type="text"
id="to" name="to"> <input type="button" id="changeChart"
onclick="getChartdate();" value="Change Chart"/>
</div>
<div id="chart_div"></div>
</body>
</html>
The method window print() will simply open the print dialog. How the page is formatted for print depends on how the browser formats webpages and the print stylesheet if present.
Assuming the chart is some kind of image (or canvas), it might be that the browser choses to strip images when printing. Especially if the image is added using css background-image: url(...) because it assumes a background image (like background-color) is just for decoration and would waste ink if printed.
A plain img tag should print though in most cases unless some css is removing it for print...

how can get response from <form target="IFrame">

There is a simple web page which sends request, handles & manipulated by a servlet class and send back the response text.while i want ajax type handleing the request at client side that is why i am giving the response target to a invsible iframe. *but i want to print success on the page after iframe gets the response *
<html> <body>
<form action="test" method="post" target="IFrame"> /*response target is iframe*/
<input type="text" name="logic" />
<input type="submit" value="Submit" />
</form>
<iframe name="IFrame" style="width:0; height:0"> </iframe>
</body> </html>
i think this can be done using javascript or jquery, please guid me if you have any idea.
In the page which loads in the iframe, you will need to invoke a parent function.
<!-- This is the Parent. Call it JSTest1.html -->
<html>
<head>
</head>
<body>
<script type="text/javascript">
function parentAlert() {
alert('hey there from the parent');
}
</script>
I'm the parent
<iframe src="/JSTest2.html"></iframe>
</body>
<!-- this is the iframe html loaded. Call it JSTest2.html-->
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function() {
window.parent.parentAlert();
});
</script>
In the Iframe.
</body>
To send a message from Iframe to Parent window page:
<script type="text/javascript">
$(document).ready( function() {
//Message part is two parts Event name and Data you want to send
// Example message = "my_action,my_data"
message = "my_action,my_data"
parent.postMessage(message, "*");
});
</script>
At the parent window you can do the following to listen to this message and capture it:
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
// Youe message which you send is captured here in e.data will split it on ',' to get the event and the data
message = e.data.split(',')[0]
value = e.data.split(',')[1]
if ( message === "my_action" ) {
myParentFunction(value)
}
},false);

Categories