Function getting informations from website - javascript

Lets take a look here: http://www.pepco.pl/sklepy
When you click one particular shop, there appears window with opening hours and address. In site source I can see that there is javascript function. Is it possible to get all those data using javascript function without having to click on every shop? I need this for informational purposes.

When you click on a shop, there s a Ajax call which request the specific informations.
Try to use this url for your purposes.
var count = 244,
$output = $('#output');
for (var i = 0; i < count; i++) {
$.ajax({
url: 'http://www.pepco.pl/web/ajax/sites.city.php?param='+i+'&date_format=Y-m-d',
})
.done(function(data) {
$output.append($("<div class='item'>"+data+"</div>"));
})
.fail(function() {
$output.append($("<div class='item'>error</div>"));
});
}
Because of crossdomain policy you cant use this from any other page. A curl solution could work

Related

Dealing with facebook Graph API objects in javascript

I am trying to access specific albums via their location from a Facebook page via a graph API call and ultimately display them on a webpage.
Essentially I think I need to loop through the object that Facebook sends back (response in this case) and only store objects which contain the substring "Germany" in the location description to the variable albums. Currently nothing happens in the console when I trigger the method.
I'm kind of stuck at this point, I can make API calls and have them returned from the specific page via other functions, so my permission seems to be fine, I'm just structuring this function incorrectly (I think, I'm relatively new to JS and Jquery).
model.getPhoto = (function(data){
var albums;
FB.api(
'/--USER ID GOES HERE--/albums',
'GET',
{"fields":"link,location"},
function(response){
for (var i=0; i<response.length; i++){
if (response.albums.location[i] = "Germany"){
albums = response.albums.location[i];
i++;
}
console.log(albums);
}
}
);
});
You are setting model.getPhoto as a new function. If your code is complete, you never call this function. I added some lines then you can try to fix and see some results... Also changed some lines, created albums as an Array and put i++ outside of if to execute for loop correctly.
Last line calls your function.
model.getPhoto = (function(data){
FB.api('/--USER ID GOES HERE--/albums',
'GET',
{"fields":"link,location"},
function(response){
var albums = new Array();
for (var i=0; i<response.length; i++){
if (response.albums.location[i] == "Germany"){
albums.push(response.albums.location[i]);
}
i++;
console.log(albums);
}
});
});
model.getPhoto({var1: "value1"});
I suggest you play more with javascript and logics, take a look inside some libraries like jQuery itself, as you are not using it here, just pure JS, and have fun!
EDIT
When comparing, you must use == instead of =
Best,
Eder

Ajax GET duplicates if bad connection or a lot of DB connections

I have this code to GET jSon data from my hosting, but sometimes it duplicate or more when the connection is unstable
//Interval to run getChat() every 2 seconds
setInterval(function(){getChat();}, 2000);
//Get Messages from Database
function getChat() {
$.ajax({
type: "GET",
url: "myhosting.net/myscript.php"
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html_ = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
var chatmsg = $("<div></div>").text(result.chattext).html();
html_ += '<span class="color-'+result.color+'"><b>'+result.usrname+'</b></span> <i class="fa fa-angle-right"></i> '+chatmsg+'<br>';
}
$('#page-chat').append(html_);
});
}
Also i have a form and when i send the message with another function, i call getChat() again to refresh my #page-chat content div...
The POST to datbase works fine, i dont have duplicates there, it is just a client side problem with my code, i was thinking to set a CheckState=1 var to check if the ajax GET call got Success, if not, CheckState=0...that way it wont run again same function, what do you think? ps. it happens when the internet is slow or a lot of people is chatting at same time...this is meant to be an Mobile Chat APP
An easy way of handling duplication of messages would be to create a chronological ID of each message. This way, even if something arrives later (and it can happen due to many things network related) you will still be able to order your messages.
Generate a timestamp for each message as it reaches the server on the post message, or when it leaves the client.

how to use for-loop to do form submission in javascript?

I have written a javascript in the console of chrome to download many files from a web. The javascript is as follows:
for (i=0; i<100; i++) {
$("input[name=id]").val(i);
$("form").submit()
}
I expected I can download all the files whose id is from 0 to 99; however, what I am able to download is only the last file (i.e. file with id =99). Why does this happen?
I think you are missing the responses. When you call first form, the browser start the connection, but just after that, you ask for the second form. Whitch cancel the first.
You need to call that forms with AJAX, to store each request with the correspondent response in some variable.
Your problem is like when you click too many links in a page before let it load the first link. Finally the loaded link is the last clicked.
TRY THIS SOLUTION:
You need to que keep some time between calls to handle response and start the download, so wright a function like this:
function submitFormAndWait(i) {
//this is your code to submit
$("input[name=id]:hidden").val(i);
$("form").submit()
//wait some time and call next form
if (i < 100) {
setTimeout(function(){ submitFormAndWait(i + 1); }, 3000);
}
}
POSSIBLE PROBLEM:
When you submit a form in the browser, this will load the response as the current page, and the script will start from zero other time.
The best way to do that is using AJAX and FormData.
Assuming you're using jQuery in your site, some pseudocode for this:
var url = '/some/ajax/url';
var i = 0;
for ( ; i < 100; ++i) {
var formData = new FormData();
formData.append('some-number-field', i);
// Send data using Ajax POST
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function(response) {
// Do something on success
},
error: function(xhr, status errorThrown) {
// Do something on error
}
});
}

Load random page without array

I've been searching for a way to take the user to a random page when they press a button with JavaScript/jQuery. Everything I've seen has all the pages in an array, and then uses a script to randomly choose an index.
Would it be possible to do something like this without adding all the pages into an array. I don't want to sit there and add every page/image in the directory to a large array and then have the script run, I just want it to go through the appache directory list and grab something by itself.
Can this be done? I know we're supposed to include code we have so far, but this is more of a conceptual question.
Use ajax to get your link:
$.ajax({
method: "GET",
url: "/getRandomLink", // I don't know which server side language you're using, I presume its PHP
dataType: "text", // text will be enought if it only returns a link
success: function(link) {
window.location.href = link;
}
});
Then put this inside an event of your choice. Nice and easy.
UPDATE
The return of your service must be a string with the link. I'm suposing you're using PHP, so will be something like:
<?php
$randomLink = "";// Code to get the random link here
echo $randomLink; // e.g.: http://www.google.com/
?>
Something needs to provide the list of files for your script to randomly choose from. That's going to be either a pregenerated array or an ajax request.
These would work:
Apache directory listing as json
how to get file listing using jquery ajax
...but for your purposes it would make more sense for your server side script to just return a single randomly selected file, instead of using bandwidth for the whole list only for the client to discard all but one.
Edit to reflect the comment given by the OP. Pardon the jQuery.
Assuming the directory index you've got is a standard Apache Auto-Index page:
//jQuery doc.ready, because I'm too lazy to do something better ;)
$(function () {
var links = [];
$.ajax(
{
//url: location.pathname, // Use current page
url: '/directoryname/', //directory index of your choice
success: saveAjaxedLinks
}
);
function saveAjaxedLinks (data, e) {
// Scrape anchors off of page.
// Note -- there might be other anchors on the page
// that you don't want to pick up, say the "up a directory level" anchors.
// you can filter those out if you want, but you'll have to determine the criteria for doing so.
var directory = $('a', data);
//Get anchor nodes and store them.
links = directory.get();
//Assign event listener to button after the data is ready.
$('button#yourbuttonid').on( 'click', onclickGetRandomPage );
//uncomment to do action immediately.
//onclickGetRandomPage();
}
function onclickGetRandomPage (e) {
if ( !!e && !!e.preventDefault ) {
e.preventDefault();
}
//if no links on the index, do nothing.
if ( !links.length ) return;
//Get the a random index from the links.
var rnd = Math.floor( Math.random()*links.length);
for (var i = 0, len = links.length; i < len; i++ ) {
// Make sure there's an actual href inside the random link.
// Also, check to make sure the links arent just hashes. Not necessary if you're just using an apache auto-index.
// If there are certain types of links you don't want (eg. directory roots), you can filter them out here.
if ( !!links[rnd].href && links[rnd].href.replace( links[rnd].hash, '' ) !== (location.href.replace( location.hash, '' ) ) ) {
//console.log(links[rnd].href); //Log out the links if you're just testing
window.location.href = links[rnd].href;
break;
} else {
//That link was no good, get a different one.
rnd = Math.floor( Math.random()*links.length );
}
}
}
});

How to pass data from one HTML page to another HTML page using JQuery?

I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.

Categories

Resources