jquery loading script when preparing document - javascript

I have a problem with jquery and would appreciate a help from stackoverflow community to solve following problem
Lets assume that there a server side script which creates doc file and following links calls it
<a class="prepare_doc_file" href="somepage.php?action=docfile">docfile</a>
what i need is jquery script, which shows loading image, when doc file if being prepared (or when the link is clicked) and hide it after getting download popup.
I see loading circle in the tab in browser. I need the same thing inside the html document
Thank you

You need to use AJAX, and generate a tempfile to download.
Your php can generate file and save to some temp path. After downloading you can delete this file.
<a class="prepare_doc_file" id="downloadfile" href="somepage.php?action=docfile">docfile</a>
function loadFile(){
document.getElementById('downloadfile').innerHTML='loading, please wait';
$.ajax({
url: 'somepage.php?action=docfile',
complete: function (data) {
document.getElementById('downloadfile').href='path to file'; //path may be returned on php.
document.getElementById('downloadfile').innerHTML='docfile';
}
});
}

<div id="myDiv">
<img src="loading gif image url">
</div>
<script>
$.ajax({
type: "POST",
url: "url to the page where the contnt is",
data: 'parameters if any' ,
success: function(result){
//logics
$("#myDiv").html("<a class="prepare_doc_file" href="somepage.php?action=docfile">docfile</a>");
});
</script>

Related

after ajax success refresh / reload page but prevent page blink

as title you see, I meet some problem with my website,
I use ajax to read my API, and after ajax success, I need to reload page to display some data,
Unfortunately, the page sometime will blink and then reload, but sometime will not.
And I use setTimeout to achieve that, because I'm writing shopping cart page,
It allow user edit their shopping carts' goods.
My idea is: after user stop click plus or minus button or stop typing quantity about 1 second,
ajax will execute to read my API, after ajax success, reload page.
So, is there have any ways to prevent page blink?
Or maybe I can made a loading gif to display on the page?
My code will be like:
var timeout = null;
$('.num').on('keyup', function() {
var newNum = $(this).val();
var pid = $(this).attr("name");
clearTimeout(timeout);
timeout = setTimeout(function() {
if(newNum <= 0){
alert("At least 1 product!");
$(this).val("1");
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: 1
},
dataType: "json",
success:function(data){
window.location.reload(true);
},
});
}else {
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: newNum
},
dataType:"json",
success:function(data){
window.location.reload(true);
},
});
}
}, 1000)
});
You can add a loader gif as you want then remove when document loaded.
<div class="loader-fix" style="position:fixed;height:100vh;width:100vw;background:#ffffff;">
<img src="your.gif" />
</div>
<script>
$(window).on('load', function (e) {
$('.loader-fix').fadeOut('slow', function () {
$(this).remove();
});
});
</script>
What is the point in using ajax when you want to reload the page to show updated data...?
success:function(data){
window.location.reload(true);
}
What is the use of above piece of code..?
For your purpose a simple form submission thing was enough, but you have used ajax getting data but not using it anywhere.
If you want to reload the page, then better go with solution by Şahin Ersever.
If you want a dynamic site, where data is fetched from backend in background and updated on frontend without refreshing the page, do something like this.
<html>
<body>
<h1> Dynamic load using AJAX </h1>
<div class="dynamic_div">
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
</div>
<button onclick="letsload()">Load</button>
<script>
function letsload(){
$.post("someurl",{ data1: "value1", data2 : "value2"},
function(data, status){
if(status == "success"){
$('.dynamic_div').html(data);//Loading updated data
}
});
}
</script>
</body>
</html>
On data variable, you can echo out desired html/json or a success/error code, and handle the data/code in ajax function accordingly.
Edit :-
Looking at your comment But I check my website, if ajax success, I use console.log to print my data, it's not working, but if reload page, it can work.
I have a quick and easy solution for this.
Let's take above example, which I have given.
Suppose if I want updated data to be displayed in dynamic_div what I will do, is I keep the element to be shown inside that div in separate file.
eg:- updated.php
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
Now What I do is on success of my ajax, I will load this div in to my .dynamic_div like this.
success:function(data){
$('.dynamic_div').load("updated.php");//Load the inside elements into div
}
Now you will get updated data, as you have already updated it somewhere in backend, so load() will load a page inside a division, without refreshing the whole page.
Comment down for any queries.
AJAX Read data from a web server - after a web page has loaded
Update a web page without reloading the page
Send data to a web server in the background
What is Ajax
If you want to reload page then don't use ajax call,
but if you want to load data using ajax then update your html using JavaScript in ajax success message.

main page stucks while pdf is not loaded on new page after form submission

As the title said, I'm stuck on a problem with javascript and form submission.
My problem is, I have an html page, with a form (in a modal exactly but it does not matter here I think). When I submit the form what I need to do is
Open a new page which has to load a pdf of hundred pages (about 100 - 300).
Validate the form.
The problem is, during the validation, if the pdf is not loaded, the page where the form is, is stucked or very very slow. And once the pdf is loaded on the other page, the main page is ok. How do you explain this, and how can I do to avoid this problem ? Maybe validate the form first an then load the page ?
I'm not a javascript expert and a precise explanation on what is going on will be perfect. Thanks.
Here is a piece of code without the real links
<form id="myForm" action="someURL" method="POST">
<input type="hidden" value="someValue" name="someName">
<a class="button" id="myButton" href ="URL_OF_THE_PDF" target="_blank" >
the JS code :
$("#mybutton").on('click', function(){
$.ajax({
type: "POST",
url: myURLForm,
data: form.serialize()
});
});
I put some sample code, I tried different things but none of them works.
You can use a real HTML button here, because you do not need the href.
<button id="myButton" type="button">
That could work:
The onClick function for the button opens an empty page in a new window.
Then it sends the ajax-request first.
When that is done, it loads the pdf file in the new window, which was opened short before.
$("#myButton").on('click', function() {
let myWindow = window.open(empty.html, '_blank');
$.ajax({
type: "POST",
url: myURLForm,
data: form.serialize()
}).done(function() {
myWindow.localtion = URL_OF_THE_PDF;
});
});
see: http://api.jquery.com/jquery.ajax/
How big ist you pdf file with 100-300 pages?
I think the browser is very busy loading the pdf file, because 100-300 pages sounds very big.
So it yould be better doing the ajax request first and loading the pdf file after the ajax request has finished.

Onclick event unable to pass into mysql

I'm trying to send this into my database with PHP:
<a class="content_link" href="http://www.example.com" title="Example" target="_blank" rel="nofollow" onclick="trackOutboundLink('http://www.example.com'); return false;"> </a>
If I delete "onclick" it works, but if I leave it, I get an error saying "Chrome detected unusual code on this page and blocked it to protect your personal information (for example, passwords, phone numbers, and credit cards)." FYI, the onclick="trackOutboundLink is tracking code for Google Tag Manager.
I guess that the question lies in passing Javascript event handlers through mysql. Thanks in advance!
Hey you are missing the function you must place it in the head to define trackOutboundLink function
place this code in head tag
<script type="text/javascript">
function trackOutboundLink(url){
$.ajax({
url: "post.php",
dataType: "html",
type: 'POST', //I want a type as POST
data: "url="+url,
success: function(data){
alert("sucess");
}
});
}
</script>

Call PHP file without using form action

I am new to php. I did a little search but did not find a good solution. So posting the question here.
I have several thumbnail images in my webpage. Something like:
<img src="" id="thumb1">
<img src="" id="thumb2">
<img src="" id="thumb3">
<img src="" id="thumb4">
I want to call load a php file when a user clicks on any of these thumbnail images and pass the id of the image to the php file. This php file queries the database with the image id and displays the relevant information. So far I used "form action" to call a php file.
Can you please tell me how to call php file and pass the image id?
Thanks.
Use links:
<img src="" id="thumb1">
<a href="php_file.php?id=thumb2"><img src="" id="thumb2">/a>
<a href="php_file.php?id=thumb3"><img src="" id="thumb3">/a>
<a href="php_file.php?id=thumb4"><img src="" id="thumb4">/a>
php side: $_GET['id'];
You can post to a script without using a form, here is a simple example
$.post("get_image.php", { thumbId: thumb1 }, function(response) {
console.log(response);
});
And in php side $_POST['thumbId']
If you are using jQuery try this:
var get_thumb_details = function(thumb_id) {
$.ajax({
type: "POST",
url: "process_image.php",
data: {
thumb_id: thumb_id
}
})
.done(function( data) {
// This is the data received from the server
console.log(data);
});
};
// Attach onclick event on your images
$('img').on('click', function() {
var thumb_id = $(this).attr('id');
get_image_details(thumb_id);
});
On the server side you can access the request parameters using the $_POST object.
$input_thumb_id = $_POST['thumb_id'];
var_dump($input_thumb_id); // if you want to check the variable value
You can try Angualr Js. In angular js we can the get the form elements attributes without submitting. So you can get the image id's on clicking using angular js. You can pass the same to get your required php page.

<script> not returned in AJAX

I am creating a WordPress theme and using AJAX to load new archive pages. The problem is that the whole < script type="text/javascript">//something//< /script> is not returned in the newly-acquired content.
Suppose I have these codes initially :
<div id="post-1">
<script type="text/javascript">
//some codes here//
</script>
<div class="content">
</div>
</div>
After navigating to the next page and back to this original page using AJAX, I will get these (in Firebug) instead :
<div id="post-1">
<div class="content">
</div>
</div>
The whole chunk of Javascript codes will not be returned, but under the 'Inline' script in 'Script' tab of Firebug, they are still there.
So, I'm wondering what have I done wrong in retrieving the new content using AJAX? Below is the code that I'm using :
jQuery('.ajax-pagination a').live('click', function(e){ //check when pagination link is clicked and stop its action.
e.preventDefault();
var link = jQuery(this).attr('href'); //Get the href attribute
jQuery.ajax({
url: link,
dataType: "text",
context: document.body,
beforeSend: function(){jQuery('#container').fadeOut(500)},
success: function(html) {
var newhtml = $('#container', $(html))
$('#container').html(newhtml);
$("container").find("script").each(function(i) {
eval($(this).text());
});
jQuery('#container').fadeIn(500);
},
error: function() {
alert('Error');
}
});
});
I am trying to run the Javacript loaded via AJAX, but the problem seems to be that the Javascript itself isn't even returned together with the rest of the content.
Thanks for reading such a long question and I really appreciate your help!
The .html() method strips <script> tags from inserted HTML.
You'll need to traverse the HTML before you try to insert it to find all of the script tags and then use jQuery.globalEval to execute their contents.
success: function(html) {
var newhtml = $('#container', $(html));
// execute included script tags - assumes inline for now
$('script', newhtml).each(function() {
$.globalEval($(this).text());
});
$('#container').html(newhtml).fadeIn(500);
}

Categories

Resources