Scraping html and displaying it on another site - javascript

I have a header that I want to share between two sites. They are two separate sites, so I was wondering if its possible to create a javascript, that will pull from site A and display it exactly on site B
basically something like this, but having it display instead of just parsing
function fetchPage(url) {
$.ajax({
type: "GET",
url: url,
error: function(request, status) {
alert('Error fetching ' + url);
},
success: function(data) {
parse(data.responseText);
}
});

You have all the code you need right there. Just replace your "parse" function with a jQuery wrapper and select the section of the page you want. Keep in mind, this will only work if you're using the same stylesheet on both pages. If not, you'll have to pull in a copy of the styles as well.
function fetchPage(url) {
$.ajax({
type: "GET",
url: url,
error: function(request, status) {
alert('Error fetching ' + url);
},
success: function(data) {
$(data.responseText).find('#yourHeader').prependTo(document.body);
}
});
}

Related

How to sort by relevance on Flickr? (Not using Flickr API Module)

The Flickr API defaults to search for the most recent photos. I want my API to sort by most relevant photos first. I tried adding "&sort=relevance" to my url and while the API still returns it is not sorting by relevance.
Here is my base code:
function getFlickr(query) {
var proxy = 'https://cors-anywhere.herokuapp.com/';
var url = 'https://api.flickr.com/services/feeds/photos_public.gne?tags=' + query + '&sort=relevance&format=json&nojsoncallback=1';
$.ajax({
type: "GET",
url: proxy + url,
// dataType: "json",
success: function(response) {
renderFlickrResults(response, query);
},
error: function(xhr, status, e) {
console.log(status, e);
}
});
}
What am I missing? Thank you for your help!

Ajax Error when looping

Im using a mixture of php and javascript/jquery to scrape a websites prices from there webpage, there's no API so unfortunately I scrape the html page and pick up the prices/title from the html(I know this is a really risky way of doing it but its the only way).
Anyway, this is whats going on:
I pull in the external webpage using php file_get_contents()
This method is within a foreach loop, for every external page I want to grab data from.
This is my javascript.
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript'>
console.log('page-{$i}');
$('.page-{$i}').find('.search_result_row').each(function(i, obj) {
//This will give us each individual apps details.
var appTitle = $(this).find('.title').text();
var appPrice = $(this).find('.search_price').text();
var appDiscount = $(this).find('.search_discount').text();
var appDetails = {
'appTitle' : appTitle,
'appPrice' : appPrice,
};
callAjax(appDetails);
var my_delay = 5000;
function callAjax(appDetails) {
$.ajax({
url: 'Upload.php',
type: 'POST',
data: appDetails,
dataType: 'JSON',
success:function(data) {
console.log(data);
},
error:function(jqXHR, textStatus, errorThrown) {
console.log('request failed ' + textStatus + errorThrown);
console.log(appDetails);
}
});
}
});
</script>
Everything works fine for the first URL, and for about half of the urls that I'm grabbing data from. The issue is SOME of the data being sent via ajax is returning the following error
Upload.php net::ERR_EMPTY_RESPONSE
Can any of you help?
Try this. You must stringify your details before you post them as json. This could be a reason for ERR_EMPTY_RESPONSE.
function callAjax(appDetails) {
appDetailsJsonString = JSON.stringify(appDetails);
$.ajax({
url: 'Upload.php',
type: 'POST',
data: {appDetailsJson: appDetailsJsonString},
dataType: 'json',
success:function(data) {
console.log(data);
},
error:function(jqXHR, textStatus, errorThrown) {
console.log('request failed ' + textStatus + errorThrown);
console.log(appDetails);
}
});
}

MVC - nothing happens on click (Jquery in view)

I want my button to do something onClick(), it has the ID btnSend. But nothing happens when I click the button which is weird and I can't figure out why.
The script is in my view for now within script tags.
$("#btnSend").click(function () {
var messageInfo = {
"Body": $("#Message").val(),
};
$.ajax({
type: "POST",
url: '/Api/Posts',
data: JSON.stringify(messageInfo),
contentType: "application/json;charset=utf-8",
processData: true,
success: function (data, status, xhr) {
alert("The result is : " + status);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
Are you sure your script is running after the page is loaded?
Put your script at the bottom of the page and give it a try.

MVC 4 Ajax Requests - referencing a javascript file

Im making some ajax calls to return some partial views which are working fine when the scripts are written in the view.
Script code is
<script type="text/javascript">
$.ajax({
url: "#(Url.Action("ProjectPartial", "Project"))",
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html',
data: {
documentType: $('#DocumentType').val(),
sectionName: $('#SectionName').val()
}
})
.success(function (result) {
// Display the section contents.
$('#Projects').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
</script>
What i want to do is to store these in a javascript file called renderpartial.js so that i can add ajax calls to to one file and not write them into every view.
Does anyone know if this is possible?
Ive tried putting
<script src="~/Scripts/RenderPartial.js"></script>
at the top of my page but all i get is the error function.
As long as you use inline razor syntax like #(Url.Action( you can't move it to js file
You can do it in either specifying url like
url: '/Project/ProjectPartial',
or in View.cshtml
<script type="text/javascript">
var projectUrl="#(Url.Action("ProjectPartial", "Project"))"
</script>
in RenderParial.js
url: projectUrl,
There are two ways to do it:
By using AJAX.BeginForm. Using this, helps you not to write
your javascript/jquery ajax calls but it is useful when you are
doing something with only one form. When your form renders it then
creates javascript for you which makes your view very clean.
I normally use a html5's data- attribute to read such kind of data
that is easily available from the view in my js files. Because there
are many cases where you want something to read from server in your
view and you also want that data to be accessed in your javascript
code, mainly in another view. Use razor syntac to put data in
data- attributes like this:
//I assume you write this attribute in any control like this
data-url="#(Url.Action("ProjectPartial", "Project")"
//or if you want to write it in any html helper control as html attribute like this
new { data_url="#(Url.Action("ProjectPartial", "Project")"}
Now in your external js file you can read the url while making an ajax call. You can write as many data attributes as per your needs and make your of razor syntax to give you your data eg: type-post/get, contenttype,etc. and use like this:
$.ajax({
url: $('anyinput').attr('data-url');,
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html',
data: {
documentType: $('#DocumentType').val(),
sectionName: $('#SectionName').val()
}
})
.success(function (result) {
// Display the section contents.
$('#Projects').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
How about move the following to the js file.
function getPartial(UrlToGet) {
$.ajax({
url: UrlToGet,
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html',
data: {
documentType: $('#DocumentType').val(),
sectionName: $('#SectionName').val()
}
})
.success(function (result) {
// Display the section contents.
$('#Projects').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
}
And in your view:
<script type="text/javascript">
$(function () {
getPartial('#(Url.Action("ProjectPartial", "Project"))');
});
</script>
A pattern I have used on recent projects to avoid polluting the global namespace is to encapuslate the function and configuration variables into an object-
var projectHelpers {
config: {
projectUrl: null
},
init: function() {
//Do any page setup here...
},
getPartial: function() {
if (projectHelpers.config.projectUrl) {
$.ajax({
url: projectHelpers.config.projectUrl,
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html',
data: {
documentType: $('#DocumentType').val(),
sectionName: $('#SectionName').val()
},
error: function (xhr, status) {
alert(xhr.responseText); //Consider if console.log is more appropriate here
},
success: function (result) {
$('#Projects').html(result); // Display the section contents.
}});
} else {
console.log("Missing project URL);
}
}
};
And then in the page-
projectHelpers.config.projectUrl = "#(Url.Action("ProjectPartial", "Project"))";
projectHelpers.init();
This helps encapsulate your code and is particularly useful when working with lots of external libraries to avoid variable collisions, as well as avoiding coding errors where you re-use a variable name and overwrite values.
See What does it mean global namespace would be polluted? and Using Objects to Organize Your Code.

I can't get my JSON request to work

I have created a url that I need to pass to police data API.
var api_url="http://policeapi2.rkh.co.uk/api/locate-neighbourhood?q="+latlon;
document.write(api_url);
The URL works when you manually input it into a browser, but I need some JavaScript that sends the API request and spits it onto the page. My JavaScript is ok but I have no knowledge of jQuery.
Thank you in advance, please keep it simple brainy folk.
try the following.. its is working
JS Fiddle http://jsfiddle.net/9AZyZ/
function abc(latLong){
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
data: {
q: "select * from json where url ='http://policeapi2.rkh.co.uk/api/locate-neighbourhood?q="+latLong+"'",
format: "json"
},
dataType: "jsonp",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (result) {
alert("Sorry no data found.");
}
});
}

Categories

Resources