Uploading photo Spring - Ajax - ajax

I am trying to upload a photo and get a preview of the uploaded image using Spring and Ajax.
I have the following code:
<h3>File Upload</h3>
<ul>
<li>
<form id="upload-form" method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="uploadfile" size="45" accept="*" />
<br>
<input id="submit-button" type="submit" value="Upload" />
</form>
</li>
<li><p>Result: <br><span id="result"></span></p></li>
</ul>
<h3>Show Image</h3>
<ui>
<li>original:<img id="image-o" src="#" alt="original image" /></li>
<li>small: <img id="image-s" src="#" alt="small image" /></li>
<li>medium: <img id="image-m" src="#" alt="medium image" /></li>
<li>large: <img id="image-l" src="#" alt="large image" /></li>
<li>extra large: <img id="image-xl" src="#" alt="extra large image" /></li>
</ui>
<script type="text/javascript">
$(document).ready(function () {
$("#submit-button").on("click", function (event) {
event.preventDefault();
// create an FormData object
var data = new FormData($('#upload-form')[0]);
// disabled the submit button
$("#submit-button").prop("disabled", true);
// post data
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "image/api/upload",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
// shows server's response
// $("#result").text(data);
console.log("SUCCESS: ", data);
enableSubmitButton();
updateImages(data);
},
error: function (e) {
// shows server's response
// $("#result").text(e.responseText);
console.log("ERROR: ", e);
enableSubmitButton();
updateImages(e.responseText);
}
});
});
});
function enableSubmitButton() {
$("#submit-button").prop("disabled", false);
}
function updateImages(data) {
var url = 'http://localhost:9001/image/api/' + data;
$('#image-s').attr('src',url + '?size=s');
$('#image-m').attr('src',url + '?size=m');
$('#image-l').attr('src',url + '?size=l');
$('#image-xl').attr('src',url + '?size=xl');
$('#image-o').attr('src',url + '?size=o');
}
</script>
And my Java code:
#POST
#Path("/upload")
#Consumes(ExtendedMediaType.MULTIPART_FORM_DATA)
#Produces(ExtendedMediaType.APPLICATION_JSON_UTF8)
#Transactional
public ResponseEntity<Void> uploadImage(#RequestParam("uploadfile") MultipartFile file) {
if (file.getSize() < maxFileSize && validExtensions.contains(file.getContentType())) {
Image image = Image.builder().id(file.getSize()).build();
imageServiceConfigMapper.saveImage(image);
/* FormDataContentDisposition fileDetail = null;
ImageMetadata imageMetadata = buildImageMetadata(fileDetail, image);
imageServiceConfigMapper.saveMetadata(imageMetadata);*/
}
return new ResponseEntity<>(HttpStatus.OK);
When I choose a photo from my PC, it is accepted - see screenshot below:
When I click in upload, my browser gives the following answer:
The JSON looks like this:
BUT the selected picture is not showing:
Am I using a wrong URL?
The address of the site where I got the above screen ends is the one with index.html at the end, but I defined /api/upload as a relative path...
If I open the relative path, I got the following:
Or is it something wrong with the code responsible for the preview?
Sorry, I know there is a tones of similar issues but I could not found anything that hepled. I am quite a beginner...
Sorry for the long post and thanks for the help in advance!

Spring Content can do this and has a getting started guide and git repo with an angularjs based front-end that demonstrates exactly what you are trying to do. The getting started guide is here.

Related

Post form using AJAX in Django

I'm trying to POST form in Django using Ajax. I've already done this way before but now i cant find whats wrong with my code. When submitting the form, ajax POST's to wrong URL even though i've provided the right URL. I want to post to "/upload/videoUpload/" but it keeps on posting to "/upload".Below is the code.
HTML:
<form id="videouploadForm" method="POST" >
{% csrf_token %}
<input type="text" id="vidlc" name="video" value="submit" style="display: none" >
<input type="submit" id="sBm120" style="display: none"/>
</form>
AJAX:
<script>
$('#sBm120').trigger('click');
$(document).ready(function() {
$("#videouploadForm").submit(function(event){
event.preventDefault();
$.ajax({
method:"POST",
url:"/upload/videoUpload/",
data: {
'video': $('#vidlc').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
success: function(data){
if (data.status){
alert(data.status);
var result = " <video poster='{% static 'images/single-video.png' %}' style='height:30vh' controls='controls' width='100%' height='30%'><source src='http://gateway.ipfs.io/ipfs/"+data.filehash+"' type='video/mp4; codecs='avc1.42E01E, mp4a.40.2'></video>";
document.getElementById("upv").innerHTML=result;
}
}
});
return false; //<---- move it here
});
});
</script>
URLS.py:
path('upload/videoUpload/', uploadVid, name="uploadVideo"),
have you tried to use Django url template tags?
url:"/upload/videoUpload/", to
url:" '{% url " uploadVideo" %} ",
Hope it works!
Sorry if you dont see properly, writing from my phone :)

Data not going to controller using Ajax

I am new to AJAX and I am trying to send some data to the controller using the AJAX. on clicking the button "Start Event", nothing is happening..
This is my jsp page where I have written the AJAX code
<c:forEach items="${scheduledEvents}" var="event">
<div class="col-md-3" id="eventId">
<div class="card-counter primary">
<div id="head" class="card-counter head-color"></div>
<span class="count-head">${event.eventName}</span>
<br>
<span class="count-name">Date : ${event.date}</span>
<span class="count-name">Location : ${event.location}</span>
<span class="count-name">Hosted By : ${event.hostName}</span>
<span class="count-name">Description : ${event.description}</span>
<br>
<br>
<div class="count-join">
<button class=" btn" id="${event.linkId}" style="background-color: #cc3300;"><font style="color: white;">Start Event</font></button>
</div>
</div>
</div>
</c:forEach>
<script type="text/javascript">
$(function() {
$('.count-join').on('click',function(){
var eventData = $(this).attr("id")
.ajax({
url : 'startEvent?data=' +eventData,
type : 'GET',
contentType : 'application/json',
success : function(data){
$
.get(
'${pageContext.request.contextPath}/startEvent',
function(data,status) {
$("#eventId").html(data);
}
);
}
});
});
});
</script>
And this my controller mapping
#RequestMapping(value="/dashBoard/startEvent")
public ModelAndView startScheduledEvent(#RequestParam("data")String data)
{
System.out.println(data);
return new ModelAndView("DashBoard");
}
Where am I wrong? please give some detailed explanation as I do not know much about AJAX. Thanks in advance.
As per you controller #RequestMapping, you have missed the /dashBoard in ajax call.

Cross Domain Ajax Issue

I have two files
1) index.php(picks data from the code editor and submits for processing via Jquery Ajax to exec.php)
2) exec.php (currently just transfer the data it recieved via index.php using jsonp)
Code of index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function test() {
var code = document.getElementById('code').value;
var code_data = "code=" + code;
alert(code_data);
$.ajax({
type: "POST",
crossDomain: true,
url: "http://code1.guru99.com/exec.php",
data: code_data,
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
alert("End of Test");
}
</script>
<form name="myform" id="myform" method="POST" class="code-box">
<textarea name="code" id="code"><?
$code='<?php
"Hello";
?>';
echo $code;
?>
</textarea> <!-- for add html tag in text area nad print the code-->
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="submit" value="Run" id="submit" onClick="test();"><!--<img id="ajax-loader" name="ajax-loader" src="/img/ajax-loader.gif" class="hidden" style="vertical-align:middle" />-->
</form>
<div name="label" id="label"> </div>
<div name="out" id="out"> </div>
Code of exec.php
<?php
$code=$_POST['code'];
$fp=fopen("file.txt","w"); // Storing the data into a file just to know that data is passed
fwrite($fp,$code);
fclose($fp);
header('Content-Type: application/jsonp');
echo $_GET['callback']."(".json_encode($code).");"
?>
The problem is data just does not pass into exec.php. I am not sure why...
The code is live at http://code.guru99.com/php/
Please help...
You cannot use AJAX to do this. Instead consider posting from a hidden Iframe using a regular FORM and setting the action to the URL you desire. You can still submit the form using JavaScript.
You can also listen to the onload event on the iframe to detect when your post has completed.
Alternately, you can use a server-side proxy.
The code syntax is correct.
May the problem could be with your server

Load PHP array into html as select options

I am having trouble working the finishing touches out with this. I am still fairly new to ajax and json, but here's what i have so far. I am trying to take an array(s) from a php file and load them into a select dropdown (#input) via ajax/json. I think i'm pretty close, but i'm not sure where i'm messing up. Please help
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="../_js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function() {
if ($("#numbers").val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = <?php echo json_encode($array); ?>;
for (i=0;i<numbers.length;i++){
$('#input').append("<select>" + numbers[i] +
"</select>");
}
},
});
}
});
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
</div>
<div id="content">
<div class="main">
<div id="formwrapper">
<select id="numbers">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="input"></select>
</div>
</div>
</div>
</div>
</body>
</html>
And here is my PHP (login.php)
<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>
In your script, you aren't doing anything with the data that is returned from the AJAX call. I suspect that is because you don't understand how AJAX works. I'll try to explain it without going into super deep detail.
When you make an AJAX call to a URL, you are making an HTTP request, just like when you type http://www.google.com into your web browser. In response, the server at the other end of that URL sends you an HTTP response with some data.
In the case of your AJAX, you are requesting the response of login.php, which, I will assume, is the PHP you added to your question above. In the success function, you get a result. That result is everything that was output by login.php.
So,
$(document).ready(function() {
$("#numbers").change(function(e) {
if ($(this).val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = result; //result is equal to your array from the php. You don't put PHP here.
$('#input option').remove(); //Remove any existing options.
for (i=0;i<numbers.length;i++){
$('#input').append("<option>" + numbers[i] + "</option>");
}
}
});
}
});
});
If login.php is NOT the PHP you added above, then I'm not going to be able to help you until you tell me what file that is from.
Also, notice that we wrapped the AJAX call into a change event on the #numbers select box. That way, when the select box's value changes, it will call this AJAX, and select the numbers.
Thanks for the assist tymeJV.

How to trigger Ajax with flash buttons?

I'm working on something where there are 2 links which triggers some Ajax. However I need to turn the links into Flash buttons (AS3). I've never worked with Ajax before, and I have no idea how this can be done.
Edit:
The Ajax:
<script>
$(document).ready(function() {
$('a.catlink').unbind('click').click(function(e)
{
e.preventDefault();
var link = $(this);
var inputs = [];
var cat_type = $(this).attr('href').replace('#', '');
link.attr('disabled', 'disabled');
inputs.push('cat_type=' + escape(cat_type));
$.ajax(
{
type: "POST",
cache: false,
dataType: "html",
url: window.location.href,
data: inputs.join('&'),
success: function(html)
{
var json = $.parseJSON(html);
if (json['status'] == 1)
{
$('div.listing').html(json['html']);
}
link.removeAttr('disabled');
}
});
});
});
</script>
The HTML
<h1 class="section-head">Products
// **The 2 links*** //
<a class="catlink" href="#cinema">cinema</a> <a class="catlink" href="#smart">smart</a></h1>
<div class="listing">
<ul class="listing">
{foreach from=$products item="product_info"}
<li class="clearfix">
<div class="inner-left">
<img height="68" width="90" src="{$product_info.image}" />
<h2 class="normal mt-5">{if $product_info.price != '0'}${$product_info.price}{else}Click for price ยป{/if}</h2>
</div>
<div class="inner-right">
<h3 class="mb-0">{$product_info.productName}</h3>
<p class="small mb-5"><span class="quiet">{$product_info.category}</span></p>
<p class="mb-15">{$product_info.description}</p>
<a class="button getprice" href="{$product_info.url}">Buy Now</a>
<br><br>
</div>
</li>
{/foreach}
</ul>
</div>
If you're going to use AS3 then you can use ExternalInterface.call() to call a JavaScript function on the page. Though, using Ajax may not be required if you're using AS3 because you can make use of the URLLoader class to do the same thing (call a PHP script and decode a result).
If you describe more accurately what you want to achieve then I shall provide some example code and clarify a little more.

Resources