not able to execute script for limited time - javascript

I have the following script which displays a loader when a file is uploaded using upload input. I want that loader should appear till the time file uploads and also wish to capture the name of the file. Can anyone please tell how this can be done
<input type="file" id="photoimg" name="file" />
<div id='preview' align="center"></div>
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').change(function(){
$("#preview").html('');
$("#preview").html('<img src=img/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({
target: '#preview'
});
});
});
</script>

You can use ajax call for this once you click the upload button you can show loader image and on the success, you can hide it and if the upload fails you can show the separate image for that.
$.ajax({
url: 'YOUR API PATH',
"Show the loader once the ajax call made using .show() or similar"
error: function() {
"show the error image using .show() or similar"
},
success: function(data) {
"Hide the loader on success"
},
type: 'POST'
});

Related

How to display image with HTTP header in HTML page?

I have a basic HTML page with one button. On click of that button it should invoke an HTTP URL(with Accept header) on GET request.
The output of HTTP URL is a image or audio or video(as per the request header).
How should I write a Javascript or Ajax call
<html>
<form>
<input type="submit" id='img_display' onClick=imgDisp()>
<div id='display'></div>
</form>
</html>
Ajax code-
$("#img_display").on( "click", function imgDisp() {
$.ajax(
{
type: 'GET',
url: 'http_url',
dataType: 'json',
beforeSend : function(xhr)
{
xhr.setRequestHeader('Accept', 'image/png');
},
success: function(data){
alert("successfully")
},
error: function(e){
alert("error post" + e);
}
}
);
});
To make an Ajax request that returns either an image, audio, or video content, and forcing the receiving Javascript to guess the content type of a potentially huge blob of data, is poor design.
Depending on what type the audio and video content is, it may not be possible at all to do things that way.
It's much better to make one Ajax request that, say, returns a JSON object with the content type and URL:
{ "type": "image",
"url": "http://example.com/images/5/example.jpg" }
or, for a video:
{ "type": "video",
"url": "http://example.com/videos/5/example.mp4" }
You get the drift.
You can then handle the content appropriately, for example create an img element and set the src property to the URL, or invoke a video or audio player with the video URL.
This way, you can also send along other metadata that is relevant to rendering the end result - image dimensions and alt text, for example.
hope this will help you!!
$(document).ready(function(){
$("#Submit").click(function(){
var image_url = $(".imageurl").val();
$(".ImageContainer").html("<img src='"+image_url+"' width='200'>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="imageurl">
<button id="Submit">Submit</button>
<div class="ImageContainer">
<!--Image Display -->
</div>

How to display image in HTML Page

I have a simple HTML page with a Button. Onclick it should show an image through an Ajax call.
It works fine in Postman Rest Client.
But in browser it is showing raw data instead of pic.
HTML
<html>
<button type="button" id="test" onclick="asset();"> Show Asset </button>
<div class="result"></div>
</html>
Ajax
$("#test").on("click", function asset() {
$.ajax({
type: 'GET',
url: 'https://url', //get an image
//url: 'https://url', //get audio file
beforeSend: function(xhr) {
xhr.setRequestHeader('Accept', 'image/png');
//xhr.setRequestHeader('Accept', 'audio/x-wav');
},
success: function(data) {
$(".result").html(data);
},
error: function(e) {
alert("error post" + JSON.stringify(e));
}
});
});
Sample Raw data -
�PNG IHDR�O^�fsRGB���gAMA���a pHYs���o�d�mIDATx^��{TUG����3���%c�N�8������N'��;Iw'�yu�_�Q�((�����(�E#T#��%B$$�ݝd�����I�$w�xn��3�[_�9ך�Zk��^��Wc
What should I do to get image?
Question 2.
How to display/play an audio/video in html page? As of now when I use another audio url...nothing gets disaplyed in browser.
---edit---
#Everyone thank you for your quick solutions.
Actually I also need to send an HTTP Header along with the URL.
Because the URL may give me an Image/Audio/Video file depending on the Request Header.
In this case how can I display Image/Audio/Video within Webpage?
If your url is just a link to image then no need to make an ajax call. Just add a img tag to your html and modify its src attribute value.
var url = "https://placehold.it/350x150"; // some url
$(function(){
$("#test").click(function(){
$("#imgId").attr("src",url);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<button type="button" id="test"> Show Asset </button>
<div class="result">
<img id="imgId" src="" />
</div>
</html>
You don't need to use ajax to load images, images are already loaded asynchronously. So just create an img element and add the src of the image. This works even when the page has been loaded.
$("#test").click(function() {
$(".result").append("<img src='img/src.png' />");
});
I think the data in success is a base64 encoded image. In that case you have to show it like:
success: function(data) {
document.getElementById('img').setAttribute( 'src', data );
}
Maybe image that is returned from api is base64 format. So you must convert that base64 data into image. Change your success callback like the following.
success: function(data) {
var img= new Image();
img.src = 'data:image/png;base64,'+ data;
$(".result").appendChild(img);
}

Why does JQuery no longer work after not using it for 2 weeks

I have a very small web application that I have been playing around with. Two weeks ago I had JQuery functionality with it client side that was able to register new profiles with the server. I booted it up again today after not looking at it for 3 weeks and found that none of the JQuery functionality I had used before no-longer works. So the server starts, the main page goes up but when you click the buttons they don't do anything. I did upgrade to Windows 10 over this time so I'm not sure if that had anything to do with it (I don't know why it would but this is the only thing that I can remember that has happened in the mean time). Anyways for now I am just trying to get an "alert" to pop up when one of the 2 buttons before I try to implement their functionality again. Here is the file structure/ my code.
I included 2 copies of the .js files in attempt to debug, it works with neither
Here is my index.jsp file:
<html>
<head>
<title>Messenger</title>
<link rel="stylesheet" href="stylesheets/c.css" />
</head>
<body>
<script src="jquery-2.1.4.min.js"></script>
<script src="javascripts/main.js"></script>
<div class="header">
<label> Welcome!</label>
</div>
<div class="leftArea">
<label>Username:</label>
<input type="text" id="username" name="username"/>
<label>Password:</label>
<input type="text" id="password" name="password" required>
<button id="btnRegister">Register</button>
<button id="btnSignIn">Sign In</button>
</div>
<div class="mainArea">
<h2>Stupid Website!</h2>
</div>
</body>
</html>
I have tried to use both the path "javascripts/index.js" and just "index.js"
Here is my main.js file:
var rootURL = "http://localhost:8080/messenger/webapi";
$(function() {
$('#btnRegister').click(function() {
//var username = $('#username').val();
alert("Register Press");
//registerProfile();
});
$('#btnSignIn')click(function() {
//getMessage();
alert('SigIn Press');
//logIn();
});
//Works as a tester
function getMessage() {
$.ajax({
type: 'GET',
url: rootURL +"/messages/1",
dataType: "json", // data type of response
success: (function(data) {
alert('ID: ' + data.id);
})
});
}
function logIn() {
var profileJSON = formToJSON();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + "/profiles/logIn",
dataType: "json",
data: profileJSON
});
}
function registerProfile() {
alert("Here");
var profileJSON = formToJSON();
$.ajax({
type : 'POST',
contentType: 'application/json',
url: rootURL + "/profiles",
dataType: "json",
data: profileJSON,
success: (function() {
alert("Success!");
})
});
}
function signIn(){
}
//This works
function formToJSON() {
return JSON.stringify({
"profileName": $('#username').val(),
"password" : $('#password').val(),
});
}
});
As you can see I have commented out the functionality that was previously working and am now trying to just get it to have alerts that notify the user that buttons have been pressed. I have no idea what could have happened or maybe I did something that I don't remember? I doubt it though.
Running on an Apache Tomcat v7.0 server. Uses Jersey APIs
MORE INFO:
Server starts up fine, and the site goes up. I see this but the buttons have no functionality:
[![enter image description here][2]][2]
In your screenshot the jquery file icon has an alert icon on it. This generally means the file cannot be found. In fact there are lots of files that cannot be found.
You probably need to fix your project references
upgrading for windows 10 has nothing to do with jQuery not working
you can load your website from chrome or something and press f12 which will take u to the console.
you can see what's wrong in the console.
furthermore to confirm that ur jQuery library is properly loaded go to page source and copy paste the jQuery script link on your address bar and see if the jQuery file loads.
if it does load, then sometimes its an issue of jQuery being loaded after some other jQuery based scripts.
make sure to include the JQuery script first and then put the rest of the scripts and imports below it
hope this helps

Call php file which return PDF with jQuery AJAX function

My php file: example_061.php create PDF return and everything works fine.
Now I want to call that file with jQuery AJAX to get this at my screen and I try:
$("#proba").click(function() {
//in here we can do the ajax after validating the field isn't empty.
$.ajax({
url: "tcpdf/examples/example_061.php",
type: "POST",
async: true,
data: {
ime: $("#ime").val(),
pozicija: $("#pozicija").val(),
jmbg: $("#jmbg").val()
}, //your form data to post goes here as a json object
dataType: "html",
success: function(response) {
window.open('example_061.pdf');
},
});
});
Everything is fine so success function work an I get alert message but I don't get PDF file as download or at screen. How I can do that?
You do not need to use AJAX to download a file. If the content-disposition header is set, it will be downloaded and the current page will not be reloaded.
Just add this to your php script that creates the PDF:
header('Content-Disposition: attachment; filename=' . $MyFileName);
And instead of AJAX, use a regular anchor tag link:
Download
As someone noted in the comments, if you need to post you can still use a simple form with the same effect:
<form method="POST" ACTION="tcpdf/examples/example_061.php">
<input type="hidden" name="myPostItem" value="My POSt VALUE" />
<input type="submit" value="download">
</form>

"Waiting for response" message when Ajax call

When I use Ajax call(jquery) in the HEAD section I find a "waiting for response message" on a chrome browser with revolving circle. I don't want this ugly look. Is there a way to avoiding this?
PS: When I use input tag to call the JavaScript(Ajax call) function like
<input id="launcher" type="button" onfocus="go()" value="Go!"></input>
I couldn't see a waiting circle. Cause my program should call the function automatically I couldn't use this method.(If I use document.getElementById("launcher").focus() to automatically start the function, It showed waiting circle again.) I guess there's a some different context to call JavaScript function.
Update Here is my sample code
<HEAD>
<SCRIPT TYPE="text/javascript">
function go() {
$.ajax({
url: "/myService",
success: function(data){
document.getElementById("result_area").innerHTML = data;
go();
}
});
}
$(document).ready(function(){
go() //Here I want to Comet call;
});
go(); //should start automatically.
</SCRIPT>
</HEAD>
<BODY>
<!-- <input id="launcher" type="button" onfocus="go()" value="Go!"></input>
This doesn't show the waiting circle. Why? Use different call context? -->
<div id="result_area"></div>
</BODY>
there are some issue i want to highlight
<input id="launcher" type="button" onfocus="go()" value="Go!"></input>
this should be
<input type="button" id="launcher" value="Go!" />
then
if u want a image instead of text then put a div before form with display:none
in ajax call you are not writing url link with extension (.php or .html or .js )
in success : you again calling go(), this smell like recursive function
what data u r sending to the server?? data: is missing from ajax option
also mention dataType ( optional)
if you dont want to run ajax automatically then do it on some event( like i do on click)
bind with the document ready
write javascript code in head ( best practice to write just before </body> )
i tried my hard to tell you the basic, here is my way
HTML
<div id="waiting" style="display: none;">
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
</div>
<form>
// here is your form
</form>
jQuery
<SCRIPT TYPE="text/javascript">
$(document).ready(function(){
$('#waiting').show(500);
// instead run automatically now it will work on click of button
$('#launcher').click( function () {
$.ajax({
url: "/myService.html", // or whatever page
// by the way where is data which you sent on server??
data: { email : $('#email').val() }, // like i send the email to the serever
dataType : "json",
async : false,
success: function(data){
$('#waiting').hide();
$("#result_area").html(data);
}
});
});
})
I found that this waiting circle on XMLHttpRequest is depend on a browser implementation. On IE7, Firefox4 it didn't show any waiting circle or bar while chrome11, Windows safari had one.
I believe that standard on this should be made cause it impacts greatly on user experience.

Categories