I am using html2canvas javascript to convert html div to image file. All script are working good and it converts html div to image properly.
But when I am adding response(anchor link) to href and triggering it using ajax it is not triggering anchor link.
Here is my code,
Html code:
<div id="mainDiv">
<h1>Heading H1</h1>
<p>Download Image using ajax and php</p>
</div>
<div>
<a id="download">Download Image</a><br/>
<a id="download-image" href="" download>Download</a>
</div>
Ajax code
<script>
$('#download').on('click', function () {
html2canvas([document.getElementById('mainDiv')], {
onrendered: function (canvas) {
var imagedata = canvas.toDataURL('image/png');
var imgdata = imagedata.replace(/^data:image\/(png|jpg);base64,/, "");
//ajax call to save image inside folder
$.ajax({
url: 'save_image.php',
data: {
imgdata:imgdata
},
type: 'post',
success: function (response) {
$('#download-image').attr('href', response).trigger('click');
//$('#downlaod-image').trigger('click');
}
});
}
});
});
</script>
Clicking the link will actually reload your page. It will still execute html2canvas(), but the response from the Ajax call will never be processed, as by that time the page has already been reloaded.
So cancel the default hyperlink action by adding a return false just before the end of the click handler (after the call to html2canvas).
Related
I am trying to make a website that loads all pages using AJAX. Here's a simple piece of JS that does that:
$.ajax({
url: url,
type: 'GET',
success: function(html) {
document.open();
document.write(html);
document.close();
}
});
This obviously works and updates my current page content.
The problem is I want to keep one div unchanged (let's call it .player-wrapper). This div is actually an <audio> wrapper which I want to keep playing (and this is the reason I AJAXified the entire website). Is this possible?
Every time you render a page, you can initialize plugins/libraries like this:
const App = function() {
return {
init: function() {
// Do all your JS stuff here
console.log('App initialized.');
},
render: function(url) {
$.get(url, data => {
$('main').html(data);
}, 'html').done(() => {
this.init();
});
}
};
}();
$(function() {
App.init();
$(document).on('click', '[data-page="ajax"]', function (e) {
e.preventDefault();
const url = $(this).attr('href');
App.render(url);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<audio class="player-wrapper" src="https://www.free-stock-music.com/music/alexander-nakarada-wintersong.mp3" controls autoplay></audio>
<main>
<h1>Initial page.</h1>
</main>
<nav>
Go to dummy page
</nav>
If you want to keep the audio tag with the player-wrapper class let's take this html as our base:
<body>
<audio class="player-wrapper"></audio>
<div class="page-content"></div>
</body>
Then with the following code you can place the html you received from the ajax request:
document.querySelector('.page-content').innerHTML = html;
Just don't write the html to the document, but place it in an already existing element like the div with the page-content class in this example.
And when you need to execute script tags in the html you can use jQuery's append method (since you are already using jQuery)
$('.page-content').append(html);
One thing you can do is copy the .player-wrapper before you write.
$(".overridebutton").on("click", function () {
var html = '<div class="override">Im a new div overriding everything except player-wrapper</div>';
var exception = $(".player-wrapper").html();
console.log(exception);
document.write(html + exception);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="everything">
<div class="sub-1">
Hello Im sub-1
</div>
<div class="sub-2">
Hello Im sub-2
</div>
<div class="sub-3">
Hello Im sub-3
</div>
<div class="player-wrapper">
I am player wrapper
</div>
</div>
<button class="overridebutton">Override</button>
I'm trying to load different views without reloading using JQUERY > AJAX.
It works fine the first time but the second time it triggers the call and loads the page.
Here is the button I'm using:
First time:
<p>Start <i class="icon arrow-right"></i></p>
Second time:
<p><a href="{{ URL::route('onboarding-ajax', ['i' => '3']) }}" id="next-step" next-step-id="3" >Next</a></p>
Here is the script:
<script>
$('#next-step').on('click', function (e) {
e.preventDefault();
var that = $(this),
url = that.attr('href'),
type = 'GET',
step_id = that.attr('next-step-id'),
width = (step_id / 32)*100 + '%';
$.ajax({
url: url,
type: type,
success: function(response) {
$('#content-wrap').html(response.view);
window.history.pushState({path:url},'',url);
return false;
}
});
});
</script>
Any idea what is being done wrong?
If your #next-step element is inside #content-wrap, it will disappear when you replace #content-wrap contents. If the new contents also have a #next-step inside it, it is a different element with the same ID, and will not have a click handler attached to it like the previous one did.
The easiest way to salvage it is to use a "live" handler - not on the #next-step, but on a parent. Try this:
$('#content-wrap').on('click', '#next-step', function (e) {
This tells #content-wrap to pay attention to a click event on a #next-step. Since you don't replace #content-wrap itself, this handler will persist, and will catch events even if #next-step is replaced.
There are links to various articles on my Webpage that open an article in a Bootstrap modal. Inside the body of Modal there are two links, one to previous article and other to next article. As of now, when a user clicks on any of these links inside of showing the content inside the modal, the link loads in the browser itself. Here is what my modal function looks like :
function openModal() {
// Store vallues in variables: var url , urlSplit, mainPage, txt, content
// prevLink, nextLink, imageURL etc.
// All of them have correct values.
$.ajax({
type: "POST",
url: 'getarticle.php',
data: {
link: url,
page: mainPage
},
success: function(data) {
var moreLinks = '<a class="modal-link" href="'+nextLink+'">Next</a>';
data = data+moreLinks;
$('.feed-modal .modal-body').html(data);
$('.progress').fadeOut();
}
});
}
The openModal function is triggered by :
$('a.modal-link').on('click', openModal);
So, a click on moreLinks should change the text inside the Modal but it instead loads the link in browser. How can I just load the content in Modal?
as the link is dynamically added to the DOM, you need to use event delegation:-
$('.feed-modal').on('click', 'a.modal-link', openModal);
and add event to openModal() so you can event.preventDefault(); to stop the a's default behaviour in loading in the browser:-
function openModal(event) {
event.preventDefault()
You need to set an onclick handler on the link inside modal.
// Event delegation approach as the link are genrated dynamically.
$(document).on("click", ".modal-link", function(e) {
e.preventDefault(); // Prevent redirection on button click
$('.progress').fadeIn(); // Fadein the progress
var url = this.href;
var mainPage = ""; // Set it to something , i dont know what it is.
$.ajax({
type: "POST",
url: 'getarticle.php',
data: {
link: url,
page: mainPage
},
success: function(data) {
// Rest all code to update the content is same.
var moreLinks = '<a class="modal-link" href="' + nextLink + '">Next</a>';
data = data + moreLinks;
$('.feed-modal .modal-body').html(data);
$('.progress').fadeOut();
}
});
});
I am trying to Ajaxify a normal page redirect.
ASPX (View: Parent.aspx):
<a id="GetContent" href="#">Go to Content Page</a>
ASPX (View: Content.aspx):
<div id="content">
...
</div>
Controller (ContentController.cs):
public ActionResult Index(id)
{
var content = _db.GetContent(id);
return View("Content");
}
JS:
$(document).on("click", "#GetContent", function () {
location.href = "/Index/3";
});
I tried this. This works, however, the url in the URL bar does not change.
$(document).on("click", "#GetContent", function () {
$("#content").load("/Index/3");
});
So when you click on the link, currently it posts back normally and then redirects to ~/Content/3 (i.e. no ajax). What I want is to immediately go to the Content page, and then display a loading indicator while the content is being fetched. I know I probably have to use jQuery.load() to do this, but not quite sure how to put things together.
Any help is appreciated!
I think this is what you are looking to do...
Index.aspx:
<div id="content">
...
</div>
<script>
$(document).ready(function() {
$.ajax({
url: '/Content/Details/3', // <-- Can use #Html.ActionLink here, to utilize routing a bit.
success: function(data) {
$('#content').html(data);
}
});
});
</script>
ContentController.cs:
public ActionResult Index(id)
{
return View("Index");
}
public ActionResult Details(id)
{
var content = _db.GetContent(id);
return PartialView("_Details", content);
}
If you put a loader.gif in the div initially I think you'll get the behavior you are looking for. You'll also need to make sure you have the _Details view created, and displaying whatever is in your model (var content).
i would link jquery (through
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
) and then use
var checking = "<img src='ajax-loader.gif'/>";
$("#content").innerHTML=checking
$("#content").load("/content/3");
to load it in the page
I'm Using Web service using AJAX Call In My HTML Page . Web Service Returning Data Nearly 30 to 40 second's .
During This Loading Time I Need to Use Some Loading Gif Images After Data Completely Received Form Web Service The Loading Image Must Be Hide.
I'm Using Only HTML,JAVASCRIPT,CSS,J Query.
Any Idea Or Samples Needed.
I'm Using Following Code
$(document).ready(function () {
document.write('<img src="http://www.esta.org.uk/spinner.gif">');
});
$( window ).load(function() {
//This following Function Related To My Design
jQuery(".chosen").data("placeholder", "Select Frameworks...").chosen();
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
});
In The Above Code My Problem Is On Page Load Gif Image Show But It's Not Hide Only Gif Image Only Showing.
Put a hidden image on your page and as soon as your ajax call is made, make that image visible
$('#image').show();
$.ajax({
complete: function(){
$('#image').hide();
}
});
and hide that image again on Complete of Ajax call.
Use your ajax request callback (on success/failure) instead of page load.
When sending the request just show a gif animation by setting the Display to block
then when you have the data set the display to none
or use jquery
function showHourGlass()
{
$("#gifimage").show();
}
function hideHourGlass()
{
$("#gifimage").hide();
}
You ask for ideas, I have one sample -
http://www.myntra.com/shoes
load scroll down fastly this is the ajax jquery request which is exact output which you have mentioned in your question
Check source code
Jquery Ajax loading image while getting the data
This what the html looks like:
<button id="save">Load User</button>
<div id="loading"></div>
and the javascript:
$('#save').click(function () {
// add loading image to div
$('#loading').html('<img src="http://preloaders.net/preloaders/287/Filling%20broken%20ring.gif"> loading...');
// run ajax request
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.github.com/users/jveldboom",
success: function (d) {
// replace div's content with returned data
// $('#loading').html('<img src="'+d.avatar_url+'"><br>'+d.login);
// setTimeout added to show loading
setTimeout(function () {
$('#loading').html('<img src="' + d.avatar_url + '"><br>' + d.login);
}, 2000);
}
});
});
I hope this will help you.