How to show AJAX response data on a website - javascript

I'm writting a Spring Boot applicaiton in which I have a website with a submenu with several computer games. When I click on an position in this submenu, I want server to send an image (by image I mean a path to the image) of this game as a response, and after the response comes back to my JS on a website, I want to show it on the website. What I have already done is sending a request to server, and selecting an image based on request data. I don't know how to send a response and use it on my website.
Here is my code:
Java:
#RequestMapping("/change-game")
public String changeGame(HttpServletRequest request, #RequestBody GameData data){
File file;
String game = data.getName();
switch (game) {
//some code which actually works. I removed it to save space
}
request.setAttribute("gameIcon", file);
return "index";
}
JavaScript:
$("#selectGameSubmenu li").click(function(e){
e.preventDefault();
var option = $(this).data("option");
console.log(option + " " + JSON.stringify({"option": option}));
$.ajax({
type: "POST",
url: "http://localhost:8080/change-game",
data: JSON.stringify({name: option}),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
HTML:
<img src="${gameIcon}" alt="${altGameIcon}"
style="width:100px;height:100px" class="gameLogoCenter"/>

I would add a new method that returns only the image path for your AJAX calls to consume.
For example
#ResponseBody
#PostMapping("/change-game-icon")
public String changeGameIcon(#RequestBody GameData data) {
File file;
String game = data.getName();
switch (game) {
//some code which actually works. I removed it to save space
}
return file.toString();
}
and in your JS
$.ajax({
url: '/change-game-icon',
method: 'post', // or "type" if your jQuery is really old
data: JSON.stringify({name: option}),
dataType: 'text',
contentType: 'application/json'
}).done(iconPath => {
$('img.gameLogoCenter').prop('src', iconPath)
})

Related

Sending byte array over ajax [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am having ajax request which is working only half way.
function receivedText() {
alert(fr.result); //Here i have good result
$.ajax({
type: "POST",
url: "/Gallery/UploadImage",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
byteArray: fr.result,
fileName: $('input[type=file]').val().split('\\').pop()
},
success: function (data) {
if (data == 0)
alert("error");
else
alert("Success");
},
error: function () {
alert("ERROR");
}
});
}
Here is my request. As you can see i commented up there that in my test(alert) fr.result has value BUT when i debug and go see it in my controller, it is NULL.
Here is my controller.
[HttpPost]
public IActionResult UploadImage(byte[] byteArray, string fileName)
{
try
{
System.IO.File.WriteAllBytes(_hostingEnvironment.WebRootPath + "\\Uploads\\Images\\" + fileName, byteArray);
return Json(0);
}
catch
{
return Json(0);
}
}
Your're using ajax in a wrong way.
The first error is a mismatch with Content-Type
$.ajax({
...
contentType: "application/json; charset=utf-8",
...
data: {
byteArray: fr.result,
fileName: $('input[type=file]').val().split('\\').pop()
},
...
}
Although you've set the Content-Type=application/json, the payload sent to server will be form-url-encoded by default:
fileName=Xyz&byteArray=
If you need JSON format, you should use JSON.stringify({...}) to get a text representation.
The contentType: "application/json; is not suitable here. That's because :
The JSON is not designed to deal with binary data but used for text. You can't send a byte[] with json.
The server side code expects simple type from query/routes/form. If you need json, they should be something like IActionResult UploadImage([FromBody] Fr fr)
If you're sending an image, the easiest way is to use the Content-Type of multipart/form-data with the IFormFile on the server side at the same time.
// action method
public IActionResult UploadImage(IFormFile image, string fileName)
{
// ...
}
and now you could send a FormData :
// your receivedText() function
function receivedText(){
var formData = new FormData();
formData.append('fileName', 'Xyz.img');
// if you need upload image
var inputFileElement=document.getElementById("inputFileImage");
formData.append('image', inputFileElement.files[0]);
// of if you're already have a `byte[]`, you could do it as below:
// var blob = new Blob([bytearray]...); // see https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
// formData.append('image', blob);
$.ajax({
type: "POST",
url: "/Gallery/UploadImage",
contentType: false,
processData: false,
data: formData,
success: function (data) {
console.log(data);
// ...
},
error: function () {
// ...
}
});
}
That would be your idea:
public class UploadImageBindings {
public string byteArray {get;set;}
public string fileName {get;set;}
}
[HttpPost]
public IActionResult UploadImage(UploadImageBindings bindings)
{
try
{
var bytes = System.Text.Encoding.UTF8.GetBytes(bindings.byteArray);
System.IO.File.WriteAllBytes(_hostingEnvironment.WebRootPath + "\\Uploads\\Images\\" + bindings.fileName, bytes);
return Json(0);
}
catch
{
return Json(0);
}
}
Your problem is that you not post as byte[] but you have to post as string !

Javascript Equivalent of Swift HTTPbody

I am looking for a way to put variables in to a AJAX get call, now i know the obvious way to do it would just be to add it too "data" like so
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication', favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});
But this goes to an api and the api also handles request from an iOS app which put the data into httpBody like so
let json: [String: Any] = ["userid":userID, "message":applicationtext.text, "favourid":selectedFavour]
let jsondatatosend = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = "myurl";
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsondatatosend
I believe the reason i did this origionally was it was messing up because of having strange characters in the URL so i had to send it through the body which all worked well, but now im trying to get a website to follow the same method on my api i would like it to be sent in the body from ajax so my php can do this function
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
I understand there are many ways for me to get around it in my php just use $_GET[' var '] instead of file_get_contents when it is sent from the AJAX of my website but i was wondering if there was a way of sending it into the body via ajax so i dont have to change the php file and then it is not sent through url's
so what i want to be able to do is something like this
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication'},
httpBody: {favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});

Upload Attachment and some additional parameters to MVC Controller

I have a MVC Controller with the following signature:-
[HttpPost]
public async Task<JsonResult> SaveBrochureAsAttachment(Guid listingId, HttpPostedFileWrapper attachmentFile)
{
///some logic
}
How do I make an ajax call and send the file attachment and additional listingId parameter. Currently I am only able to send the attachment like this:-
var uploadFile = function () {
if ($('#attachmentFile').val()) {
}
else {
alert('No File Uploaded');
return;
}
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: '/Listing/SaveBrochureAsAttachment',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert('File Uploaded');
},
error: function (jqXHR, textStatus, errorThrown) {
$("#FileUpload").replaceWith($("#FileUpload").val('').clone(true));
alert('File Uploaded Error');
},
cache: false,
contentType: false,
processData: false
});
return false;
}
Currently as you folks can see I am only able to send the attachment. How do I also send the Guid listingId to match the controller signature.
Try adding another formdata parameter:
formData.append("listingId", guidValue);
Provided you have the guid value accessible. You can use this to generate one from the client. Or create one from the server:
var guidValue = '#Guid.NewGuid()';
one approach would be to your controller accept viewmodel (a class) which contains different property you need. and use formdata.append required stuff to post to the server.
On Server side; you will need to use modelbinder so that you will get required stuff populated.
Refernce for modelbinder : https://www.dotnetcurry.com/aspnet-mvc/1261/custom-model-binder-aspnet-mvc
you can get more on google. :)

JQuery/Ajax & Spring Rest Multi-part form submit

I am quite new to JQuery and I was trying to do some asynchronous multipart form uploading. The form consist of few data fields and a file type. I have set up the server side code (Spring) like this:
#RequestMapping(method = RequestMethod.POST)
public #ResponseBody
Upload multipleSave(MultipartHttpServletRequest request)
{
Upload upload = new Upload();
Iterator<String> iterator = request.getFileNames();
while (iterator.hasNext())
{
MultipartFile file = request.getFile(iterator.next());
try
{
System.out.println(MessageFormat.format("File Length: {0}", Arrays.toString(file.getBytes())));
System.out.println("File Type: " + file.getContentType());
upload.setContent(file.getBytes());
upload.setDocId(id++);
upload.setError(null);
upload.setName(file.getName());
upload.setSize(file.getSize());
fileList.put(upload.getDocId().toString(), upload);
} catch (Exception e)
{
System.out.println("Error occurred: " + e);
upload.setError("500: Something went wrong!");
}
}
return upload;
}
and client side code like this:
function processFileUpload()
{
console.log("fileupload clicked");
var formData = new FormData();
formData.append("file", files[0]);
$.ajax({dataType: 'json',
url: "/SpringJqueryFileUpload/upload",
data: formData,
type: "POST",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function (result) {
alert('success' + JSON.stringify(result));
},
error: function (result) {
alert('error' + JSON.stringify(result));
}
});
}
When I do submit, the server responds with this:
java.lang.IllegalArgumentException: No converter found for return value of type: class com.upload.model.Upload
I am wondering with error. Could I be missing something here??
I would try changing your annotation to:
#RequestMapping(method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
And make sure you have Jackson (which Spring uses for JSON serialization) properly on your path. Also, make sure your Upload class is serializable, e.g. is not private or anything like that. If it is just a normal Java bean type class it should be fine.
Lastly, if that doesn't work you can turn on Spring debug logs with something like:
log4j.category.org.springframework.web=ALL
in your log4j.properties file.

Passing Parameters of AJAX POST to Grails Controller

I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.

Categories