sending long strings in jquery post - javascript

I am not able to send long strings (more than 96 char. Tested in FF12 and Chrome 18) in jquery post method.
My servlet is -
public class TestServletAsh extends HttpServlet{
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doPost(req, resp);
String xml=req.getParameter("xml");
}
}
and my jquery post request is -
<body>
<script>
function callMe() {
var str = "dkghjkdf dfg jdfgjd gkdfgdjk gdf gdfg dkjgdfjk gdjgdfjg dfjkgdfjkg dfjkgdfjkg dfjkgdf jkdfgdjhgs";
$.post(
"TestServletAsh",
{ xml:str },
function(data) {
alert("mission successfull"); //nothing to do with it or data here in this SO question
}
);
}
</script>
Click to send request
</body>
I am debugging the servlet and I find "xml=null". I am using jboss as a webserver.
Can anyone please tell me where is the problem.
When I use another version of jquery.post like this -
$.post(
"TestServletAsh?xml="+str,
function(data) {
alert("mission successfull"); //nothing to do with it or data here in this SO question
}
);
Then I am able to send around 6000 characters. For more than 6000 characters Firebug says - "405 Aborted". Why ?? Any idea ?

May be your webserver i.e. Jboss could be the issue.
You can look into changing server config parameters
Try setting maxPostSize = 0 in conf/server.xml file

Related

How to send value from jsp page to database without refreshing the page

I am developing a spring+hibernate webapp for practicing translation skill from Russian to English.
In one of my jsp pages I am retrieving all the questions from database and placing them into a table with the following columns: text in Russian, field for user's translation, button for checking the result. The goal is to save user's input into database without refreshing the page. How can I do it?
I tried several options, but none of them worked for me.
I used the solution from Send javascript variables to spring controller in my project, but nothing happened at all.
Part of "firstPage.jsp" ("/first" path in the controller):
<head>
<title>Title</title>
<script>
function searchViaAjax(id) {
var tempId = id;
alert("Start");
$.ajax({
type : "POST",
url : "./search/api/getSearchResult",
data : {id:tempId},
timeout : 100000,
success : function(id) {
alert("success");
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
alert("error");
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
alert("done");
console.log("DONE");
}
});
}
</script>
</head>
<body>
<button onclick="searchViaAjax(1)">Simple button</button>
</body>
Controller class:
#Controller
public class DemoController {
#RequestMapping("/first")
public String getFirst(){
return "firstPage";
}
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult", method=RequestMethod.POST)
public String getSearchResultViaAjax(#RequestParam("id") Integer id) {
System.out.println("come to ajax"+ id);
return "hello";
}
}
The "Start" message gets printed, but other messages from searchViaAjax() don't. And controller method doesn't start.
You can pass id in controller as it is no issue in your 'id', and also you can skip value attribute in #RequestParam.
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult")
public String getSearchResultViaAjax(#RequestParam("id") integer id) {
System.out.println("come to ajax"+ id);
return "hello";
}
Specify the methodType
#RequestMapping(value = "/search/api/getSearchResult", methodType=RequestMethod.POST)
It is also a good practice to use wrapper instead of primitive
#RequestParam("tempId") Integer id
the problem is in your ajax url attribute.
It should be url : "./search/api/getSearchResult",
Root Cause:
When you are about to hit your controller, it construct the url like this
http://localhost:8080/search/api/getSearchResult
and hence such resource is not available and it causes 404 not found error.
In actual the url should be
http://localhost:8080/contextroot/search/api/getSearchResult
here contextroot refers your project name.
Now if you hit url ./search/api/getSearchResult then ./ refers the base url i,e localhost:8080/contextroot and the entire url will be constructed properly.
I would like to recommend you to create global variable in JavaScript say baseUri and assign./ into it.
<script>
var baseUri="./";
</script>
In your AJAX it becomes
url : baseUri+"search/api/getSearchResult",
Hope this will help
The code from user9634982 was fine, thanks to him. The problem was because I was using slim jQuery version so my browser was giving me "$.ajax is not a function" error. And I didn't see it for hours because I didn't know where to look :facepalm: Thanks again to user9634982 for discovering browser inspector to me :D After replacing slim version to usual it still didn't work because of spring security. I added _csrf token and all worked fine.
.jsp:
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<script>
function searchViaAjax(id) {
var csrfHeaderName = "X-CSRF-TOKEN";
var csrfTokenValue;
var metaTags = document.getElementsByTagName('meta');
for(var i = 0; i < metaTags.length; i++) {
var metaTagName = metaTags[i].getAttribute("name");
if(metaTagName === "_csrf_header")
csrfHeaderName = metaTags[i].getAttribute("content");
if(metaTagName === "_csrf")
csrfTokenValue = metaTags[i].getAttribute("content");
}
$.ajax({
type : "POST",
url : "./addAnsweredQuestion",
data : {id:id},
timeout : 100000,
beforeSend:function(xhr){xhr.setRequestHeader(csrfHeaderName, csrfTokenValue);},
success : function(id) {
alert("success");
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
alert("error");
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
alert("done");
console.log("DONE");
}
});
}
</script>
Controller:
#PostMapping(value = "/addAnsweredQuestion")
public void getSearchResultViaAjax(#RequestParam("id") Long id) {
System.out.println("come to ajax"+ id);
}

Passing value from java to Javascript

I'm making an Android app using webview.
The app can print out receipts. What I want to do is when the printer is not working, alert box shows up to tell the printer isn't working, and return false to the form's onsubmit event to prevent form from being submitted.
Java code:
public class JSKicker {
#JavascriptInterface
public void callPrint(final String argumet) {
Thread thread = new Thread(new Runnable() {
public void run() {
int nRtn;
connectionNum = myPrinter.Connect("000.000.0.000");
if(connectionNum < 0){ //Printer not working
webview.post(new Runnable() {
#Override
public void run() {
String script = "alert('Printer Error'); return printer_connection = false;";
webview.evaluateJavascript(script, new ValueCallback<String>() {
#Override
// I can't figure out what to do here...
});
}
});
}else{ //Printer is working properly
connectionNum = myPrinter.SetLocale(8);
strText = argument;
nRtn = myPrinter.PrintText(strText, "SJIS");
nRtn = myPrinter.PaperFeed(64);
nRtn = myPrinter.CutPaper(1);
myPrinter.Disconnect();
}
}
});
thread.start();
}
JavaScript in header:
<script type="text/javascript">
function gate(){
jQuery.ajax({
url:'/cart_info.php',
type:'GET'
})
.done( (data) => {
window.JSKicker.callPrint(data);
})
if (printer_connection = false) {
return false;
}else{
return true;
}
}
</script>
HTML form tag:
<form method="post" id="order_form" onsubmit="return gate();">
How can I get this work?
Could you do it thru WebView.evaluateJavascript()?
https://developer.android.com/reference/android/webkit/WebView.html#evaluateJavascript(java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.String%3E)
So with that you could send simple CustomEvent to document in WebView
webView.evaluateJavascript("document.dispatchEvent(new Event('printer_error', { details: "No printer found!" }));");
and in JavaScript you can hook listener for your custom event to react.
document.addEventListener('printer_error', e => alert(e.details));
Didn't test this so might be that at least evaluateJavascript() needs callback function.
WebSocket can solve your problem.
WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time. The client establishes a WebSocket connection through a process known as the WebSocket handshake.
Its very straight forward and easy to implement.
You can follow referrer links for more details:-
JAVA WebSocket:- WebSocket using Spring Boot, WebSocket using Simple JEE
Browser WebSocket(JavaScript):- WebSocket API
In Android ,if you want webview pass value to JavaScript.
First,you need to set the webview enable the JavaScript,
private WebView mWebView;
void onCreate(){
mWebView = findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
}
And ,in you want do some thing code
if(connectionNum < 0){ //Printer not working
// I need to do something here to send a message that the printer isn't working to JS.
//In thread can not use mWebView,should send message to MainThread to do
// mWebView.loadUrl("javascript:javaCall()");
Message msg = new Message();
msg.what = 1;
myHandler.sendMessage(msg);
//myHandler can be your MainThread send to here
}
And where the mWebView created in your code, be in main thread ,you can use the
Handler to deal with the message sended to here.
private Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// this 1 is just thread send to here
if (msg.what == 1) {
//and here can do the webview UI method
mWebView.loadUrl("javascript:javaCall()");
}
}
};
the javaCall() is where you JacaScript invoke method,in javaScript you can writre like this:
<script language="javascript">
function javaCall(){
alert("Printer Error");
//other thing you can do
}
</script>
if you have problem ,you can refer to the official document.
public void loadUrl (String url)
Loads the given URL.
Also see compatibility note on evaluateJavascript(String, ValueCallback).
webview use link

Run multiple ajax when page load

I write three ajax function like below:
function showClass()
{
...
var url="getObjectProperty?"
....
}
function showDtPro()
{
...
var url="getDataTypeProperty?"
....
}
function showObjPro()
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your Browser Don't support AJAX");
return;
}
var url="getObjectProperty?";
url=url+"sid="+Math.random();
xmlHttp.onreadystatechange=loadObjPro;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
except the "url" is different, the other things are the same.This ajax is used to get the data from three different servlets and update the tag in html.
One of the servlets is below:
//This function is used to get the data from an jena model and response the data to the client.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
//
ArrayList<String> ObjectPropertyNames=new ArrayList<String>();
//Define the jenaOwlModel
JenaOWLModel jenaOwlModel;
try {
OntModel ontmodel=MyModelFactory.getJenaModel().getOntModel();
ExtendedIterator ObjectProperties = ontmodel.listObjectProperties();
while(ObjectProperties.hasNext()){
ObjectProperty property = (ObjectProperty) ObjectProperties.next();
if(property.getLocalName()!=null)
{
ObjectPropertyNames.add(property.getLocalName());
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String AllObjectProperties="";
for(int i=0;i<ObjectPropertyNames.size();i++)
{ AllObjectProperties=AllObjectProperties+ObjectPropertyNames.get(i)+"#";
}
System.out.print(AllObjectProperties);
out.print(AllObjectProperties);
out.flush();
out.close();
}
The other servlet is almost the same with this one.Now I want to load the data from the three servlets when the page is loaded.So I write in the windows.onload function like below:
window.onload=function()
{
showClass();
showObjPro();
showDtPro();
}
But it doesn't run as expect.Sometimes,only the last functionshowDtPro();fetch the data.The other two function don't fetch the data. Sometimes, the tag should be updated by showClass() and showObjPro() appear the data get from showDtPro().
<div id="class">
<h4>Class</h4>
<ul id="rdfclass" type="dclass"></ul>
</div>
<div id="obj">
<h4>Object Property</h4>
<ul id="rdfobjpro" type="dobjpro"></ul>
</div>
<div id="dt">
<h4>Datatype Property</h4>
<ul id="rdfdtpro" type="dtpro"></ul>
</div>
the html tag is above. Correspondingly, the three functions are used to update the three<ul>tag.
I am a beginner to web develop. I hope to get your help! Thank you !
That is because ajax is asynchronous. You'll have to implement some callbacks etc..
The execution is not synchronous in case of ajax.

JSP not receiving AJAX response from Servlet

I have a simple jsp page that sends an ajax request to a servlet and awaits a response. Unfortunately, it's not receiving the response after many attempts. The ajax requests are being transmitted but response isn't being received.
As of now, I have a dropdown in my page and a textbox. I am trying to get the value selected in the dropdown to be printed in the textbox on the dropdown's "onchange" event.
Here's my code. Any help regarding this would be very welcome.
JSP PAGE
<script>
function ajaxrequest(){ return new XMLHttpRequest();}
function ac()
{
var myajaxrequest = new ajaxrequest();
if(myajaxrequest==null){alert("AJAX NOT WORKING");}
else
{
alert("AJAX WORKING");
var ind2=document.getElementById("dd1").value;
myajaxrequest.onreadystatechange=connection;
myajaxrequest.open("GET", "../ajaxservlet?dd1="+ind2,true );
myajaxrequest.send(null);
}
}
function connection()
{
if(myajaxrequest.readyState==4)
{
var x=myajaxrequest.responseText;
document.getElementById("result").innerHTML = x;
}
}
</script>
<body>
<form id = "form1" name ="form1" >
<select id="dd1" name="dd1" onchange= "ac()">
<option>Please select </option>
<option>ankur</option>
<option>akshay</option>
</select>
<input type="text" id="result" name="result" />
</form>
</body>
SERVLET :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("hitting servlet");
String abc = request.getParameter("dd1");
System.out.println(abc);
PrintWriter pw=response.getWriter();
response.setContentType("text/html");
pw.println(abc);
}
The values selected in the dropdown are getting printed in the console but aren't being transmitted back.
Thanks for your time.
myajaxrequest is local to the ac() function since you've used the var keyword. You cannot access it in the connection() function.
Try declaring your connection() function within ac() itself.
Instead of checking the status of readyState, using XHR level 2, you can simply attach a handler to the onload event.
BTW, if native XHR isn't supported ajaxrequest() will throw an error; it won't return null.
Try initializing myajaxrequest globally.

Valums file-uploader doesn't work under Internet Explorer 9

Valums file-uploader (now called Fine Uploader) doesn't work under Internet Explorer 9 but wors fine under Chrome.
So under IE it shows the name of the file and button CANCEL and no % of uploading.
Any clue?
UPDATES:
Solution is here as well MVC Valums Ajax Uploader - IE doesn't send the stream in request.InputStream
I know this question was filed under asp.net specifically, but it came up when I searched for "valums ajax upload IE9", so I'll post my fix here in case it helps anyone like myself regardless of language:
I was returning a JSON response from the AJAX upload request with a "application/json" content header. IE9 does not know what to do with "application/json" content (but Chrome/FF/etc do).
I fixed this by making sure to return a "text/html" MIME type http header on my json response from the server.
Now IE is no longer trying to download the response! Cheers
I am unable to reproduce the issue. Here's a full working example.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase qqfile)
{
var uploadPath = Server.MapPath("~/app_data");
if (qqfile != null)
{
var filename = Path.Combine(uploadPath, Path.GetFileName(qqfile.FileName));
qqfile.SaveAs(filename);
return Json(new { success = true }, "text/html");
}
else
{
var filename = Request["qqfile"];
if (!string.IsNullOrEmpty(filename))
{
filename = Path.Combine(uploadPath, Path.GetFileName(filename));
using (var output = System.IO.File.Create(filename))
{
Request.InputStream.CopyTo(output);
}
return Json(new { success = true });
}
}
return Json(new { success = false });
}
}
Index.cshtml view:
<script src="#Url.Content("~/Scripts/valums/fileuploader.js")" type="text/javascript"></script>
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script type="text/javascript">
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '#Url.Action("upload")'
});
</script>
You could also include the CSS in your Layout:
<link href="#Url.Content("~/Scripts/valums/fileuploader.css")" rel="stylesheet" type="text/css" />
It seems that is IE cache issue, if you are using Ajax & GET, add timestamp value in the get parameters for the Ajax parameters, that will do the trick like this :
$.ajax({
url : "http:'//myexampleurl.php' + '?ts=' + new Date().getTime(),
dataType: "json",
contentType: "application/json; charset=utf-8",
.
.
//more stuff
If you are using java spring
#RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody YourObject excelUplaod(#RequestHeader("X-File-Name") String filename, InputStream is) {
// chrome or firefox
}
#RequestMapping(value = "/upload", method = RequestMethod.POST,headers="content-type=multipart/*", produces = "text/html")
public #ResponseBody ResponseEntity<YourObject> uploadByMultipart(#RequestParam(value = "qqfile") MultipartFile file) {
// IE
try {
String fileName = file.getOriginalFilename();
InputStream is = file.getInputStream();
// more stuff
} catch (Exception e) {
logger.error("error reading excel file", e);
}
}

Categories