Trouble consuming html source in javascript code - javascript

I'm trying to replicate the WhateverOrigin service, seen here:
http://stackshare-importer.herokuapp.com/get_website?url=http://firebase.com
However when I try to run it on my browser this code which worked perfectly on WhateverOrigin no longer works with my dummy service:
$.getJSON("http://stackshare-importer.herokuapp.com/get_website?url=" + import_url + "&callback=?", function(data) {
console.log(data);
});
Uncaught SyntaxError: Unexpected token <
I just want to work with the html source string, how can I achieve this?
Edit:
Also tried this and get the same result:
$.ajax({
url: "http://stackshare-importer.herokuapp.com/get_website?url=" + import_url + "&callback=?",
jsonp: "callback",
dataType: 'jsonp',
success: function(response) {
console.log(data);
}
});

Sites like WhateverOrigin and AnyOrigin get the page you want and convert it to a JSON/JSONP object, which allows it to be used cross-origin.
If you are trying to replicate what those websites are doing, you will need to create a PHP script which gets the page as a variable and then converts it to JSON and outputs it in a JSONP object.
Change the PHP on your page "get_website" to:
<?php
$page = file_get_contents($_GET['url']);
echo 'jsonCallback({"html":'.json_encode($page, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT).'});';
?>
Then use this HTML/JS on any site to output the JSON:
<div class="stuffhere"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("document").ready(function () {
$.ajax({
type: 'GET',
url: 'http://stackshare-importer.herokuapp.com/get_website?url=http://firebase.com',
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
alert(json.html);
$("div.stuffhere").html(json.html);
}
});
});
</script>
..and it will work!

Related

is that possible to make ajax call to external web page?

is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}

Adding options in select tag generated from ajax

This is my ajax code
<script type="text/javascript">
$('#right_make').change(function() {
var make = document.getElementById('right_make').value;
alert(make);
$.ajax({
url: 'get.php',
async: true,
cache: false,
data: {make:make},
dataType: "html",
type:'post',
success: function (result) {
var select = document.getElementById('right_model');
select.insertAdjacentHTML('beforeend', result);
}
});
});
</script>
I am getting data in form of html reverted from backend php ,I want to append this data in select tag ,given below
<select name="model" id="right_model" class="custom-select c_model right_model">
<option value="">Model</option>
</select>
I tried the above thing but it is producing gaps between the options ,
this is what I am appending from backend
<?php
include 'includes/config.php';
include 'includes/database.php';
$make=$_POST['make'];
$stmt=$db->prepare("SELECT distinct `model` FROM `car` WHERE make=?");
$stmt->bind_param("s",$make);
$stmt->execute();
$stmt->bind_result($model);
while ($stmt->fetch()) {
echo "<option>".$model."<option>";
}
?>
Any idea ow to do that?
Generally, if you want to communicate some data with a php server, you may use JSON.
JSON keeps a very sample solution to traduce javascript or php to a very sample string. After, you can traduce JSON to php, Javascript or what else...
You may do this because php do not understand javascript and javascript do not understand php, of course.
When you pass data with your ajax, you may do like this:
$.ajax({
url: 'get.php',
async: true,
cache: false,
data: {make:JSON.stringify (make)}, // Traduce to simply string.
dataType: "html",
type:'post',
success: function (result) {
var select = document.getElementById('right_model');
select.insertAdjacentHTML('beforeend', result);
}
});
Then, when you get the data in your php, you may do like this:
$make=json_decode ($_POST['make']); // Traduce to php.
When you use echo:
echo json_encode ("<option>".$model."<option>");
And finally in your javascript:
success: function (result) {
var select = document.getElementById('right_model');
select.insertAdjacentHTML('beforeend', JSON.parse (result));
}
Consult the documentation.

how to call js/jquery webservice

I have a web service
http://itmamhosting-001-site16.itempurl.com/lsc/GenerateCertificate.asmx/GenerateCertificate?Name=saif
It has a Url inside it :
How to call it using jQuery and take the picture url from it and save it inside a variable
I tried this code to call it but doesn't work
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=application/xml",
dataType: "xml"
});
});
I got this error
no access control , Allow origin header is present on the requested resource
Im new to jquery and js ,Im stuck i tried many codes if some one can give or show
$(document).ready(function () {
$.ajax({
type: "GET",
url: "https://services.faa.gov/airport/status/IAD?format=application/xml",
dataType: "xml",
success: function(data){
var xmlString = data.documentElement.innerHTML;
$("#result").html(xmlString);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="" id="result" cols="50" rows="50"></textarea>

Ajax wont retrieve the file from php file

Hi guys this script was working fine when I add a console.log but as soon as I replaced the console.log with the $.ajax() function it wont give me the result back from the php file the ajax function I used was working from my other projects but I cant seem to find out why it wont work on this snippet
Here is my js code :
$(document).ready(function(){
$("#qs").find(".chs").each(function(i,obj){
$(this).addClass("chs"+i);
$(".chs"+i).on("click",function(){
var s = $(this).data("lvs"),carrier= {"vars":s};
$.ajax({
url: aScript.php,
type: "POST",
data: carrier,
dataType: "json"
success: function(data) {
console.log(data) }
});
});
});
});
my php file looks like this
<?php
$json = $_POST['carrier'];
$data = json_decode($json);
$d = $data->vars;
echo $d;
?>
<input type="hidden" id="ss" value="<?=$d?>" />
can someone review this file for me cause I cant seem to find whats wrong please help me find out whats wrong with this script
You should wrap the filename inside quotes, as it is a string variable
$.ajax({
url: 'aScript.php',
type: "POST",
data: carrier,
dataType: "json",
success: function(data) {
console.log(data) }
});
});
There are some issues with your code
in this line url: aScript.php, the url string is not quoted, it should be url: 'aScript.php',
you set dataType: "json" but aScript.php returns html instead of json, remove that line
the data you're passing is not json, it will be serialized into key=value pairs and you'll be able to access it via $d = $_POST['vars'];

Get LinkedIn share count JSONP

Using the LinkedIn API, I want to get the share count for an URL.
https://www.linkedin.com/countserv/count/share?url=http://www.linkedin.com&format=json
But this gives me an error because of Same-Origin Policy.
I want to use JSONP to then get the data, but I am stuck there.
$.getJSON("https://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=myCallback", function(data) {
elem.find(".count").html(data.count);
});
I still get the Same-Origin Policy error and no data from data.count.
Can anyone help me out? Thanks!
Try
myCallback = function(data) {
// do stuff with `data`
};
var url = "https://www.linkedin.com/countserv/count/share?"
+ "url=https://www.linkedin.com&format=jsonp&callback=myCallback";
$.getScript(url);
See jQuery.getScript()
myCallback = function(data) {
$("body").append("<pre>" + JSON.stringify(data, null, 2) + "</pre>")
};
$.getScript("https://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=myCallback");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Thanks everyone for your answers, but I solved it already myself.
This worked for me:
$.getJSON("http://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=?", function(data) {
elem.find(".count").html(data.count);
});
As of jQuery 1.5.1, this is the recommended way of structuring AJAX requests:
$.ajax({
dataType: "jsonp",
url: "http://www.linkedin.com/countserv/count/share",
data: {
callback: "?",
format: "jsonp",
url: "http://www.example.com/"
}
}).done(function(data) {
console.log(data.count);
});
A few days ago, LinkedIn changed their API and the solutions above are broken :
$.getJSON("http://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=?", function(data) {
elem.find(".count").html(data.count);
});
fails because jQuery will replace the ? into a callback with a random name with numbers in it. And Linkedin now prevents using numbers in callback names.
The solution is to use to call "manually" $.ajax to prevent jQuery automation
$.ajax({
dataType: "jsonp",
url: 'https://www.linkedin.com/countserv/count/share',
data: {'url':encodeURIComponent(location.href)},
jsonpCallback: 'this_is_a_random_name',
success: function(data){
elem.find(".count").html(data.count);;
}
});

Categories