How to passing array values from ajax to spring xml controller - ajax

I am creating survey page which has the following ajax to pass answer values
if(check==0)
{
var surveyVal="";
var len=answers.length;
for(i=0;i<=len-1;i++)
{
if(i!=len-1)
surveyVal+="val"+i+"="+answers[i]+"&";
else
surveyVal+="val"+i+"="+answers[i];
}
var ajaxUrl = "survey.do";
var data = surveyVal;
alert(data);
var returnValue = false;
tinymce.util.XHR.send({
url : ajaxUrl,
content_type : "application/x-www-form-urlencoded",
type : "POST",
data : {values: data.toString() },
success : function(data) {
alert("Done! Content Saved")
// Do anything you need to do if save successful
ed.setProgressState(false); // cancel showing progress
},
error : function( type, req, o ){
alert("Save Failed\n Error: " + type + "\n HTTP Status: " + req.status);
}
});
//the alert gives
val0=0,val1=2
etc as per the options I have chosen at the browser . how can I take these val to my controller as it is so that I can capture in logs and save in my database as individual answers . (please note I cant use annotation)
currently controller is like this which is not working
String val0 = request.getParameter("val0");
String val1 = request.getParameter("val1");
String val2 = request.getParameter("val2");
String val3 = request.getParameter("val3");
String val4 = request.getParameter("val4");
logger.info + "|"+ToolsUser.getPlatform()
+ ">Update Survey Inputs"
+ "|Answers:"
+ "|Answer-1:"+val0
+ "|Answer-2:"+val1
+ "|Answer-3:"+val2
+ "|Answer-4:"+val3
+ "|Answer-5:"+val4
);
thanks in advance

can you replace this line
data : {values: data.toString() },
with this
data : "values=" data.toString(),
and in your controller try to get the value of
request.getParameter("values");
and let me know if this worked for you

Related

How do I send a base64 image to Microsoft-ocr api?

I'm trying to use Microsoft Azure OCR API service to extract some text from an image.
The image I have for sending to the API service has a "data:image/png; base64, " structure and therefore I can't send it with content-type "application/json".
I tried sending it with content-type "multipart/form-data" or "application/octet-stream", but it also fails...
// this "url" gives me the "data:data:image/png;base64, " code
var sourceImageUrl = document.getElementById("myImage").src;
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(jqXHR){
jqXHR.setRequestHeader("Content-Type","multipart/form-data");
jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: [sourceImageUrl]
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ?
"Error. " : errorThrown + " (" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
(jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message :
jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
I am bit confused about how I should be sending the image or if I should do some transformations.
Which content-type should I be using to do a proper request?
Should I change the encoding of the image source? How?
Thank you all!
I finally got it working by adding a makeBlob function that returns a blob out of a base64 code. I also set the content-type to "application/octet-stream".
Final code looks like this:
function makeblob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
function recognizeText() {
imageToSend = image.src;
binDataImage = imageToSend.replace("data:image/png;base64,","");
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(jqXHR){
jqXHR.setRequestHeader("Content-Type","application/octet-stream");
jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: makeblob(binDataImage, 'image/jpeg'),
cache: false,
processData: false
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ?
"Error. " : errorThrown + " (" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
(jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message :
jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
};

My jquery and ajax call is not responding and showing unexpected error in console

I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")

ckeditor validation for spaces

How can i implement validation on ckeditor to prevent user from adding spaces only . Any answer within today will be greatly appreciated .
following is what i tried for validations so far :
//Save note from ckeditor
$("input.save_note").click(function()
{
var note_id1 = $(this).attr("rel");
var thiss1 = this;
var profile_user_id = $(this).attr("rel1");
var txt=CKEDITOR.instances.editor1.getData();
var no_space_txt = txt.replace(" ","");
// var txt = txt1.replace(/ +(?= )/g,'');
var editor_val1 = CKEDITOR.instances.editor1.document.getBody().getChild(0).getText() ;
var editor_val = editor_val1.replace(/ +(?= )/g,'');
// if( editor_val == "")
// {
// alert('sak');
// return;
// }
if(editor_val !=="" && editor_val !=="")
{
$(this).attr("disabled","disabled");
var loading_img = addLoadingImage($(this),"before");
jQuery.ajax({
url: "/" + PROJECT_NAME + "profile/save-note-in-editor",
type: "POST",
dataType: "json",
data: { "profile_user_id" : profile_user_id , "note" : txt },
timeout: 50000,
success: function(jsonData) {
if(jsonData){
$("p#clickable_note_"+note_id1).hide();
$(thiss1).hide();
$(thiss1).siblings("input.edit_note").fadeIn();
$("span#"+loading_img).remove();
$(".alert-box").remove();
$(".alert-box1").remove();
$(".alert-box2").remove();
showDefaultMsg( "Note saved successfully.", 1 );
$(thiss1).removeAttr('disabled');
// $(".cke_inner cke_reset").hide();
CKEDITOR.instances.editor1.destroy();
$(".editor1").hide();
$("p#clickable_note_"+note_id1).html(jsonData);//to display the saved note in clickable p tag .
$("p#clickable_note_"+note_id1).fadeIn('slow');// To display the note paragraph again after editing and saving note.
}
else{
$(thiss1).removeAttr('disabled');
$(thiss1).before('<span class="spanmsg" id="note-msg" style="color:red;">Server Error</span>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
else
{
alert("You cannot make an empty note. Please insert some text.");
}
});
I have implement alert to check if no text is entered but i want to check if user only enter spaces . please suggest some accurate way .
Since you are evidently using jQuery, you can add jQuery.trim() as an additional check for your condition:
jQuery.trim(editor_val).length != 0
This will trim all whitespace from the submitted form and check whether there are any characters remaining. If the input consists only of whitespace, the statement will evaluate to false. You would integrate it into the following line:
if (editor_val != "" && editor_val != "" && jQuery.trim(editor_val).length != 0)

Javascript post jsonObject with Image Binary

I have a HTML form for filling the personal profile, which includes String and Images. And I need to post all these data as JsonObject with one backend api call, and the backend requires the image file sent as binary data. Here is my Json Data as follow:
var profile = {
"userId" : email_Id,
"profile.name" : "TML David",
"profile.profilePicture" : profilePhotoData,
"profile.galleryImageOne" : profileGalleryImage1Data,
"profile.referenceQuote" : "Reference Quote"
};
and, profilePhotoData, profileGalleryImage1Data, profileGalleryImage2Data, profileGalleryImage3Data are all image Binary data(Base64).
And here is my post function:
function APICallCreateProfile(profile){
var requestUrl = BASE_URL + API_URL_CREAT_PROFILE;
$.ajax({
url: requestUrl,
type: 'POST',
data: profile,
dataType:DATA_TYPE,
contentType: CONTENT_TYPE_MEDIA,
cache:false,
processData:false,
timeabout:API_CALL_TIMEOUTS,
success: function (response) {
console.log("response " + JSON.stringify(response));
var success = response.success;
var objectData = response.data;
if(success){
alert('CreateProfile Success!\n' + JSON.stringify(objectData));
}else{
alert('CreateProfile Faild!\n'+ data.text);
}
},
error: function(data){
console.log( "error" +JSON.stringify(data));
},
failure:APIDefaultErrorHandler
})
.done(function() { console.log( "second success" ); })
.always(function() { console.log( "complete" ); });
return false;
}
But still got failed, I checked the server side, and it complains about the "no multipart boundary was found".
Can anyone help me with this, thanks:)
Updates:
var DATA_TYPE = "json";
var CONTENT_TYPE_MEDIA = "multipart/form-data";
I think I found the solution with vineet help. I am using XMLHttpRequest, and didn't set the requestHeader, but it works, very strange. But hope this following can help
function APICallCreateProfile(formData){
var requestUrl = BASE_URL + API_URL_CREAT_PROFILE;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200){
console.log( "profile:" + xhr.responseText);
}else if (xhr.readyState==500){
console.log( "error:" + xhr.responseText);
}
}
xhr.open('POST', requestUrl, true);
// xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=----WebKitFormBoundarynA5hzSDsRj7UJtNa");
xhr.send(formData);
return false;
}
Why to reinvent the wheel. Just use Jquery Form Plugin, here. It has example for multipart upload as well.
You just need to set input type as file. You will receive files as input stream at server (off course they will be multipart)

Ignore a word in AJAX template using API

I'm using an api to create a quiz. The code that fetches the gif from the app Loopcam and then puts the loop title in the div #answer looks like this:
APP = {
refresh: function(limit, interval) {
APP.index(limit);
setInterval(function () {APP.index(limit)}, interval)
},
index: function(limit) {
var url = 'https://api.loopc.am/v1/loops/search?q=moviecharades'
$.ajax({
url: url,
dataType: "json",
success: function(data) {
var data = data
, html
, templatedata
, template = '{{#loops}}<div id="answer">{{title}}</div><div class="loop-tumbnail"><img src="{{file_url}}" {{loop_url}}/></div>{{/loops}}'
, offset = Math.round(Math.random() * (data.length - 1))
TITLE = data[0].title
console.log(offset)
if (data.length > 0) {
data = data.slice(offset, offset + limit);
templatedata = {loops: data}
html = Mustache.to_html(template, templatedata)
$('#loops').html(html)
}
}
})
What I need is the word "#moviecharades" to be deleted from the div #answer, which is always in the title that is fetched from the API. In short: if the title that is fetched is "#moviecharades big fish", I want it to only say "big fish" in the #answer-div.
I've tried to put it as a rule for the #answer-div, such as:
$("#answer").text($("#answer").text().replace("#moviecharades", ""));
But it doesn't work...
Try this:
var answerText = $("#answer").text();
$("#answer").text( answerText.replace("#moviecharades", ""));
Hope that helps.

Resources