WickedPDF and JS - javascript

I am trying to execute some ajax requests in the pdf.html file for a ruby app using WickedPDF. I have the javascript outputting some append statements to keep track of the functions reached.
The first ajax call is successful, as I have outputted the json result in the pdf file. However, in that same success call, I call another function, which for now, I only have it outputting an append statement to indicate it is being executed. However, it does not happen. Any ideas?
HTML:
<div id="data"></div>
Javascript:
<script>
function getData(data) {
$('div#data').append('<p>getData function called</p>');
}
</script>
<script>
$(function() {
var assays = '';
$.ajax({
type: 'GET',
url: 'http://www.url.com/data.json'
})
.done(function(result) {
$('div#data').append('<p>First ajax call called!</p>');
data = result['DataList']['list'];
getData(data);
})
.fail(function() {
$('div#data').append('<p class="center">Data is unavailable.</p>');
});
});
</script>
Thanks for your help.

wkhtmltopdf will by default stop slow running JavaScripts if they are delaying rendering.
Try experimenting with the following options: --no-stop-slow-scripts, --javascript-delay <msec>
More options are listed here

Related

jQuery AJAX call initiates without command when .done function added

I'm rewriting a series of jQuery AJAX requests and have been having trouble with .done code blocks. I'm attempting to send an AJAX request and wait for the response before processing the data. As a guide, I have been using the following page:
http://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/
I've also looked at countless stack questions to try and troubleshoot my issues, but haven't found anything which has helped. For reference, some of the questions I've looked at are below:
jQuery Ajax call not processing .done
jquery ajax done function not firing
Confused on jquery .ajax .done() function
I've noticed that when I create code blocks which are similar to the guide above, the functions run on page load, rather than when they are triggered in code. To isolate the fault, I created a simple example, as below:
<!DOCTYPE html>
<html lang="en">
<body>
<button type="button" onclick="getData()">Click me</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
//Commented out due comment below
/*function getData() {
console.log('enter getData');
return $.ajax({url:'./testajax.html',type:"POST"});
}
getData().done(function(data){
console.log('enter done');
alert(data);
});*/
function getData() {
console.log('enter getData');
$.ajax({ url: './testajax.html', type: "POST" })
.done(function (data) {
console.log('enter done');
alert(data);
});
alert('after');
}
</script>
</html>
I was expecting that when my example page loaded, nothing would happen, as there was no trigger to execute the getData() function unless the button was clicked. However, when I load the page, my console logs 'enter getData' and then 'enter done', and I get an alert with the contents of my ./testajax.html page (just a single string). Further, when I then click the button, it enters getData() but doesn't trigger the getData().done function, so no alert is received.
Is anyone able to guide me on the right track here and help me prevent the getData() function from executing on page load, and instead make the button click execute the AJAX request, wait for the result, then execute the code in the .done block?
The getData() expression you have immediately calls the function on pageload. Then you attach a .done handler to it.
It sounds like you want a function that calls $.ajax and attaches .done to it, like:
function getData() {
console.log('enter getData');
$.ajax({ url: './testajax.html', type: "POST" })
.done(function (data) {
console.log('enter done');
alert(data);
});
}
Then attach getData as an event handler somewhere.
Don't use inline handlers. Use .addEventListener or jQuery's .on('click' instead.

Load HTML content synchronously

I need to load HTML in a div.
$("#content").load("content.html");
$("#myText").html("Prasath");
After that I need to update some text in a div(id='myText') which is available in "content.html". "content.html" contains huge data, so it takes some time to load. Before that this line is executed:
$("#myText").html("Prasath");
How to load HTML content synchronously from JavaScript/jQuery ?
I don't want to do this from call back option in load.
You can't load it synchronously but you can quite easily do the next task in the load() callback. For example:
$("#content").load("content.html", function() {
$("#myText").html("Prasath");
});
$("#content").load("content.html", function(data){
// this will execute after load is fired.
});
Use a callback.
EDIT: If you really want to make synchronous request, you can use the following code. However, you'll get a warning in console as I mentioned in the comment earlier:
var data = $.ajax({
type: "GET",
url: "content.html",
async: false
}).responseText;
// this code waits for the above ajax request.
Please have a look on the JQuery documentation about load().
You can pass callback function to load()
For example:
$("#content").load("content.html", function(){
$("#myText").html("Prasath");
});
EDIT: There is no way to make load() to load content synchronously. A workaround solution is that you can define a Jquery function that use ajax() to send synchronous request to target url and then set the response content to destinate div.
$(function(){
$.fn.extend({
syncLoad: function (url) {
var result = $.ajax({
url: url,
async: false,
type: "GET"
}).responseText;
$(this).html(result);
}
});
$("#content").syncLoad("/echo/js/?js=hello%20world!");
});
JS Fiddle: https://jsfiddle.net/1v8fmb8b/

How to execute server returned javascript on client

I make an ajax call to a server and the server returns javascript and jquery code such as
$('someclass').html('<form id='billform'>......</>');
$('#billform').submit();
How do I execute this on the client side?
You could put that code inside a script tag and append it to the body
This procedure is described best here: https://stackoverflow.com/a/611016/4202031
However, it is not recommendet to simply execute some javascript which is loaded via ajax. I would recommend to work with events that would trigger this code which is on your page already.
$.get('/sumUrl', function(data) {
switch(data.action) {
case 'event1':
//do sth.
break
case 'event2':
// do sth. else
break
}
})
You can include the code as a function in your static page, then call the function from the returned ajax call. A small example:
on your static page:
function submitmyform(formcontents)
{
$("someclass").html(formcontents);
$("#billform").submit();
}
on your ajax success method:
$.ajax({
url: "/getform",
method: "POST",
data: $(".myform").serialize(),
success: function(data){
submitmyform(data);
}
});
You have to put your id in quotation marks, and as id instead $ use #
$('someclass').html('<form id="billform"></>');
$('#billform').submit();
You can use eval function from javascript to execute the scritp which are string
e.g.
eval('alert("Hello!")');
I your case
eval('$(".someclass").html("<form id="billform">......</>")');
eval('$("#billform").submit()');

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

Receiving variable from webpy POST via jQuery.ajax

In my webpy app I have a function:
def POST (self):
signal = web.input()['signal']
if signal == 'next':
errMessage = self.cinstall.testConnection()
print signal
print errMessage
return errMessage
According to the python console it works correctly; it receives and returns strings as I expect it to.
In a template I have a script like this:
<script src="/static/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$$(function() {
var value = $$('#continue').attr('value');
$$("#continue").click(function(){
jQuery.ajax({
type: "POST",
data: {signal : value},
success: function(html) {
jQuery('#errmessage').html(html).hide().fadeIn(1500);
},
});
});
});
</script>
I know that the request is successful, because if I put an alert in the success handler it works well, but the function jQuery('#errmessage').html(html).hide().fadeIn(1500); doesn't execute. I have a <p> tag with id=errmessage in my template.
So I have several questions:
Why it doesn't work?
Can I isolate the data recieved from POST in JS for further iterations and if statements?
Can I put if statements inside the jQuery.ajax success function?
Unfortunately, jQuery API gives limited info about success().

Categories

Resources