I have struggled with this problem for 2 days now. I've found MANY tutorials on similar topics but none have helped me solve my issue yet.
On a Volusion shopping cart I am trying to remotely grab content from the product page and save it's information in a variable for use on the shopping cart. I am unable to use php (not supported by Volusion) and am forced to do this by using javascript (as far as I know). The following code searches the cart items for a certain brand name "Palliser". If that name is present, it grabs the link, uses ajax to send a request to the page associated with the link, and grabs the info I need. It GETS the info I need, but in the process my page turns white and it leaves behind the year, 2013... I have NO idea why this is happening. This is my first time working with ajax so could someone PLEASE help!?!?
$(window).load(function(){
var seat_count = 0;
var i = 0;
var prodLinks = [];
var numSeats = '';
$('b.cart-item-name:contains("Palliser")').filter(function(index) {
prodLinks[i] = 'http://xepwk.cjvgn.servertrust.com/'+$(this).parent('a').attr('href');
$.ajax({
url:prodLinks[i],
//data:string,
async:false,
success: function(result){
var html = jQuery('<div>').html(result);
var prodInfoArray = html.find('span.PageText_L660n').parent('b').parent('td').html().split('<br>');
var numSeats = prodInfoArray[1];
alert(numSeats);
}
});
i+=1;
});
Here is a link to the info that helped me get as far as I did: Get the content of another page's div with jQuery Ajax
You can start ajax requests when DOM ready event fired. Because you don't need images and other staffs to begin ajax requests. Also async:true must be help in your situation.
var seat_count = 0;
var i = 0;
var prodLinks = [];
var numSeats = '';
$(document).ready(function() {
$('b.cart-item-name:contains("Palliser")').filter(function(index) {
prodLinks[i] = 'http://xepwk.cjvgn.servertrust.com/'+
$(this).parent('a').attr('href');
$.ajax({
url:prodLinks[i++],
//data:string,
async:true,
success: function(result){
var html = jQuery('<div>').html(result);
var prodInfoArray = html.find('span.PageText_L660n')
.parent('b').parent('td').html().split('<br>');
var numSeats = prodInfoArray[1];
alert(numSeats);
}
});
});
});
Just a thought, Having:
async:false
Loads your ajax-request synchronously and the request has to complete before you can do anything else. Try to change it to true or remove it (it is true by default).
Related
I've been trying to solve this problem for hours now maybe anyone of you could help me.
Right now my Code looks like this:
$('.clickable').on('click', function() {
var id = $(this).attr('data-packages');
id = "'" + id + "'";
$.ajax({
url: "show.php",
data: {
type: "showSFM",
data: id,
user: username
},
type: "POST",
success: function(data) {
$('#main').html(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Everything is working fine but I was asking myself If it is possible to use $('#main').html(data) on a new Window. Right now if I click an Element the current window is showing the result but I want a new tab to pop up with the result.
I was trying things like this:
success: function(data) {
var url = location.href;
var window = window.open(url);
window.document.getElementById('main').innerHTML = data;
}
The result I'm getting is that the window opens on the main page. Looks like window.open(url) works just fine but the line below does nothing.
The reason this likely doesn't work is due to the fact that you use:
window.document.getElementById('main')
The window might already be opened by the line before, but is most likely not loaded and doesn't contain an element with id main yet (since making a HTTP(S) request takes time). This could be solved by moving the filling of main element into a callback.
window.addEventListener('load', function () {
window.document.getElementById('main').innerHTML = data;
}, { once: true });
You can send the data you need for the request in the URL and then on the new page, you can send the AJAX request again, and getting the data you need for it from the URL.
Sorry for the confusing title, I'm not quite sure how I should name this better.
Anyway, I'm dealing with a postmessage interface that receives and sends data between its iframe child. It basically sends very simple messages: either score related to the game in the iframe or save/load requests.
What I'm trying to do is make it possible for the user to have more than one save "file" at once, using the concat method. I'm basically making separate save states into one large string by combining them with a separator and separating them when I need to access them for load requests.
Here's how I handle save requests from the game at the moment:
var states = JSON.stringify(data.gameState);
var newstate = {state: gameState};
var savesArray = savestring.split("||");
savesArray.unshift(newstate);
if (savesArray.length > 5){
savesArray.pop();
}
var state = savesArray.join("||");
and then I send the 'state' back to the database.
The problem that I'm having is how I would be able to let the user decide which of the 0-5 save files he wants to choose to open (=> send back as a load request).
What I'm doing at the moment as a way to avoid the problem altogether is send the first state using
var first_state = loaded_state.split("||")[0];
but I was wondering if there's any neat way to give the user a button box/div when the load request is received in the parent HTML with buttons deciding which index save state is sent back to the iframe. The biggest problem I have with this is how I can properly build the button to communicate & send the load request dynamically.
I already have a function that I use for other things in the page to dynamically create a button, but I'm not 100% sure if I can work with it to suit my needs here or if it's even the best approach in the first place.
function play(name, URL) {
var element = document.createElement("button");
//Assign different attributes to the element.
element.setAttribute("value", URL);
element.setAttribute("id", "gamebutton");
element.innerHTML = name;
element.setAttribute("style", "display:block");
element.setAttribute("class", "btn btn-success btn-block");
element.onclick = function () {
document.getElementById("iframeID").src = this.getAttribute("value");
document.getElementById("iframeID").width = "95%";
document.getElementById("iframeID").height = "750 px";
document.getElementById("iframeID").style.display = "block";
document.getElementById("hiddenScore").style.display = "block";
var gameelement = document.getElementById("gamediv");
gameelement.style.display = "block";
var miscarea = document.getElementById("misc_div");
miscarea.style.display = "none";
};
I was thinking of making it into a modal box, but the uncertainty of whether or not I would be able to smoothly create the buttons I need for it has made me hesitate whether or not I want to go the extra mile to make multiple saves possible.
Edit:
This is how the message is sent back to the iframe. As you can see, being able to create buttons for each of the indexes (var first_state = loaded_state.split("||")[0];) would mean that the code would otherwise be the same for all buttons
$.ajax({
type: "GET",
url: "{% url 'get_detail_game_instance' game.pk %}",
beforeSend: function (xhr, settings) {
$.ajaxSettings.beforeSend(xhr, settings);
},
success: function (data) {
var loaded_state = JSON.parse(data.state);
var first_state = loaded_state.split("||")[0];
console.log(loaded_state);
var message = {
"messageType" : "LOAD",
"gameState" : first_state
};
event.source.postMessage(message, eventSave.origin);
},
failure: function (errMsg) {
console.log(errMsg);
}
});
The event is received through a simple eventlistener and the event data contains whether or not it's a score, load or save request
I have contact page on my website where I have various social network links (plus an e-mail form) with links at the side to select each one. Clicking a link makes an ajax request to the server, and on success replaces the html of a common div with the response.
Each one has a javascript file associated with it, and this is added as a script tag in the document head on ajax success.
These scripts should evaluate on each load and prepare the DOM in the response. However, I am finding that the first click works perfectly, the script is loaded and executes, but when I go to click on another link, it loads the new script but it never seems to execute. And none of those dynamically loaded scripts work thereafter.
The ajax call for loading each option is bound to each link's click event here:
$('.socialLink').click(function() {
var id = $(this).prop('id').toLowerCase();
var callingObj = $(this);
$.ajax({
url: "./socialMedia/" + id + ".php",
success: function(msg) {
$('.socialLink').css('opacity', '0.4');
$('.socialLink').data('active', false);
callingObj.css('opacity', '0.9');
callingObj.data('active', true);
if ($('#Feed').css('display') !== 'none') {
$('#Feed').slideToggle(400, function() {
$('#Feed').html(msg);
});
}
else
{
$('#Feed').html(msg);
}
$('#Feed').slideToggle(400);
$.getScript('./script/' + id + '.js');
}
});
});
The thing is, I dynamically load scripts for each page on the site, too... and don't seem to have any problems with that.
You can see the page I am talking about if you go here http://www.luketimoth.me/contact.me. Only two options actually load any javascript at the moment, the e-mail and twitter ones... the rest are empty js files with only a single comment inside.
EDIT: I am now using jQuery getScript()... I have changed the code above to reflect this. The scripts I am trying to load, which are not working as exepcted, are:
twitter.js (just the standard code twitter gives you for one of their widgets):
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.
js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
email.js:
$('#Send').click(function() {
var senderName = $('#YourName').val();
var senderEmail = $('#Email').val();
var emailSubject = $('#Subject').val();
var emailBody = $('#EmailBody').val();
$.ajax({
url:'./script/sendMail.php',
data: {
name: senderName,
email: senderEmail,
subject: emailSubject,
body: emailBody
},
type: "POST",
success: function(msg) {
$('#success').html(msg);
}
});
});
$('input, textarea').focus(function() {
if (this.value === this.defaultValue) {
this.value = '';
}
});
$('input, textarea').focusout(function() {
if (!this.value.length) {
this.value = this.defaultValue;
}
});
Thanks for all the comments and suggestions. I decided in the end to load everything in the background rather than make an ajax request every single time.
It's actually a much more responsive page now... admittedly at the cost of having unused DOM elements in the background. Given how much faster it is, though, I think the trade-off is acceptable.
I'm trying to write KDE4 plasmoid in JavaScript, but have not success.
So, I need to get some data via HTTP and display it in Label. That's working well, but I need regular refresh (once in 10 seconds), it's not working.
My code:
inLabel = new Label();
var timer= new QTimer();
var job=0;
var fileContent="";
function onData(job, data){
if(data.length > 0){
var content = new String(data.valueOf());
fileContent += content;
}
}
function onFinished(job) {
inLabel.text=fileContent;
}
plasmoid.sizeChanged=function()
{
plasmoid.update();
}
timer.timeout.connect(getData);
timer.singleShot=false;
getData();
timer.start(10000);
function getData()
{
fileContent="";
job = plasmoid.getUrl("http://192.168.0.10/script.cgi");
job.data.connect(onData);
job.finished.connect(onFinished);
plasmoid.update();
}
It gets script once and does not refresh it after 10 seconds. Where is my mistake?
It is working just fine in here at least (running a recent build from git master), getData() is being called as expected. Can you see any errors in the console?
EDIT: The problem was that getUrl() explicitly sets NoReload for KIO::get() which causes it load data from cache instead of forcing a reload from the server. Solution was to add a query parameter to the URL in order to make it force reload it.
I have the code that I've pasted below, helpfully supplied by another Stackoverflow member. I've added this code into a Kentico web part, and set the cache minutes=0, thinking that would solve my caching issue. It does, but not in IE. Is there any way I can tweak this code to refresh the content when the user comes to the page, or when we have to update the html file?
// article footer
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan +1)/86400000);
return Math.ceil(dayOfYear/7)
};
jQuery(function(){
//Quotes/Testimonials
var today = new Date();
var weekno = today.getWeek();
jQuery('#quotes-wrapper').load('/quotesroller.html div.quote-'+weekno);
});
Add a cachebust parameter. Since it's a GET request, IE is annoying and always caches the contents.
var time = (new Date()).getTime();
jQuery('#quotes-wrapper').load('/quotesroller.html?_cb=' + time + ' div.quote-'+weekno);
It's probably better to use a more complex function like $.ajax() if you want to control caching on a per-request basis. Or, if you just want to turn it off for everything, put this at the top of your script:
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
EDIT: To set up no cache just for this request, replace your load with this:
$.ajax({
url: '/quotesroller.html div.quote-'+weekno, //that's based on your URL above
cache: false,
success: function(result) {
jQuery('#quotes-wrapper').html(result);
}
});