Ajax (jQuery) cross domain output - - ajax

As is such function doesn't support cross domain request
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() { alertContents(http_request); };
http_request.open('GET', url, true);
http_request.send(null);
}
function alertContents(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
receiveData(http_request.responseText);
} else {
alert("error");
}
}
}
so decided to use jQuery (with this plugin) but function
$.ajax({
url: suchurl,
type: "GET",
//dataType: "text",
dataType: "text",
//global: false,
//async:false,
cache: false,
success: function(data) {
//alert(data);
alert(data.responseText);
}
});
output like
<html>
<head>
<meta content="HTML Tidy for Java (vers. 26 Sep 2004), see www.w3.org" name="generator"/>
<title/>
</head>
<body>
<p>new_towns = [ {id:"0", name:" "},
{id:"205",
name:"City205"},
{id:"17",
name:"City17"}
];</p>
</body>
</html>
Why?.. when expecting just
new_towns = [ {id:"0", name:" "}, {id:"205", name:"City205"}, {id:"17", name:"City17"} ];
What you advice?
Thanking you in advance.
such example code - doesn't work
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.6.2");
google.setOnLoadCallback(function() {
$.ajax({
url: suchurl,
type: "GET",
dataType: "text",
crossDomain:true,
async:true,
cache: false,
success: function(data) {
alert("all right");
}
});
});
</script>
</head>
<body>
</body>
</html>
OK, guys, it's more simple and more fast&understandable decision use script
get.php
<?php
if(isset($_POST['geturl']) and !empty($_POST['geturl'])) {
$data = file_get_contents($_POST['geturl']);
print $data;
}
?>
and then just
$.ajax({ url: 'get.php',
data: {geturl: suchurl},
type: 'POST',
dataType: "text",
cache: false,
success: function(data){
alert(data);
//do something else
}
});
TNX VERY MUCH FOR YOUR ATTEMPTS TO HELP AND TIPS!

I don't guess you need to rely on a plugin for getting cross domain JSON. You can use jquery's 'jsonp' dataType.
You can follow the 'JSONP' section in the following URL:
http://api.jquery.com/jQuery.getJSON/
The output you are getting may be something that the URL returns. Make sure the requested URL returns only the expected output.
Thanks

Looks like in your first example, you are requesting text/xml, but in the second one, your type is just "text" which might be causing the url to send back a differently formatted response. For JSON data, you could also try a type of "application/json".

The JQuery $.ajax() function includes native JSONP support. You must add the parameter crossDomain:true
You can read about it here: http://api.jquery.com/jQuery.ajax/

Related

How to catch a data from callback of GET jsonp request?

I'm trying to handle callback of jsonp request, but callback function is not run.
$(document).ready(function() {
$.ajax({
url: 'https://storage-testnet.shiftproject.com/peers?callback=?',
type: "GET",
dataType: 'jsonp',
jsonpCallback: 'peersData',
complete: peersData
});
var peersData = function (data) {
if(!data){
console.log("Error, can't retrieve data");
} else {
console.log(data)
}
}
}
Is there some mistake?
Your data is not wrapped in a pad eg. the following
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
//credit https://www.sitepoint.com/jsonp-examples/
function jsonCallback(json) {
console.log(json);
}
$.ajax({
url: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
dataType: "jsonp"
});
</script>
https://jsfiddle.net/kblau237/pmw0yah9/5/
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut156</title>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#theButton").click(function () {
//moved your stuff inside a button click
$.ajax({
//question mark for callback will cause jquery to generate a random callback
//I am taking out the callback
url: 'https://storage-testnet.shiftproject.com/peers',
type: "GET",
dataType: 'json',
success: function (data) {
alert(JSON.stringify(data));
}
});
})
})
</script>
</head>
<body>
<div>
<input type="button" id="theButton" value="Go" />
</div>
</body>
</html>

Error while populating bootstrap treeview from data retrieved using Ajax call

I am using bootstrap treeview plugin (https://github.com/jonmiles/bootstrap-treeview). I am not sure if this is an issue with treeview plugin or the way i am implementing the code.I am trying to load the treeview using data from ajax call back. Here is the code sample that i am using:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- Required Javascript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="~/Content/BootStrap/bootstrap-treeview.js"></script>
</head>
<body>
<div class="clear-fix"> </div>
<div class="row">
<div class="col-sm-2"><div id="lstCollections">This will display my list of all collections</div></div>
</div>
</body>
</html>
<script type="text/javascript">
function getTree(handleData) {
$.ajax({
type: "GET",
url: '#Url.Action("Get","DatabaseSchema")',
dataType: 'json',
success: function (response) {
handleData(response);
}
});
}
$(document).ready(function () {
getTree(function (output) {
var collectionTree = [];
output.forEach(function (a) {
collectionTree.push({ text: a });
});
//var tree2 = [{ text: "Buyer" }, {text: "text1" }, { text: "text2" }, { text: "text3" }];
$('#lstCollections').treeview({ data: collectionTree });
});
})
</script>
When I run the code, I don't see any data in my treeview. In my developer tool(for chrome browser), in console I see "Uncaught TypeError: $(...).treeview is not a function(…)" error on line " $('#lstCollections').treeview({ data: collectionTree });"
If i replace $('#lstCollections').treeview({ data: collectionTree });with $('#lstCollections').treeview({ data: tree2}); (where tree2 is a variable that i have declared inside document.ready function, I still get the same error.
Interestingly, If i populate the treeview using following call outside of ajax call back function :
function nonAjax() {
var tree = [{ text: "Buyer" }, { text: "text1" }, { text: "text2" }, { text: "text3" }];
return tree;
}
$('#lstCollections').treeview({` data: nonAjax() });
Everything works!!
I am not sure why I am gettig treeview is not function() when the call is inside ajax callback function.
The right format that should pass to the treeview isn't what you get back from the Ajax call you should parse the json object like the following example:
let invalid = '{ "bank": "CityBank", "sum": "500" }, { "bank": "WPBank", "sum": "700" }';
let valid = JSON.parse("[" + invalid + "]");
Now you can pass the valid variable to the treeView without any problems.
It all about adding square brackets notation to the JSON object!

Call remote asmx service by JQuery always fail

I want to use below service throw JQuery:
http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry
But it only execute the error function, I tried below :
function serviceCall() {
var txtInput = $("#txtInput").val();
var webMethod = 'http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry';
var datap = {"CountryName":JSON.stringify("Italy")};
$("#divResult").html('loading...');
$.ajax({
type: "POST",
url: webMethod,
data: datap,// { "CountryName" : JSON.stringify("Italy")},
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //for Firefox change this to "jsonp"
success: function (response) {
alert("reached success");
$("#divResult").html(response.d);
},
error: function (e) {
$("#divResult").html("Unavailable: " + txtInput);
}
});
}
SO I receive Unavailable: Italy
Below is full page code :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function serviceCall() {
var txtInput = $("#txtInput").val();
var webMethod = 'http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry';
var datap = {"CountryName":JSON.stringify("Italy")};
$("#divResult").html('loading...');
$.ajax({
type: "POST",
url: webMethod,
data: datap,// { "CountryName" : JSON.stringify("Italy")},
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //for Firefox change this to "jsonp"
success: function (response) {
alert("reached success");
$("#divResult").html(response.d);
},
error: function (e) {
$("#divResult").html("Unavailable: " + txtInput);
}
});
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="text" id="txtInput" value="Italy"/>
<br />
<div style="width: 100px; height: 30px; background-color: yellow;" onclick="serviceCall();">
Click me</div>
<div id="divResult" runat="server">
</div>
</form>
</body>
</html>
Any help to fix that?
I can see several mistakes here:
the dataType has to be json, not jsonp
your payload (the value of data) has to be a json-object entirely serialized
is your WebMethod a ScriptMethod?
Can't exactly tell what is wrong though. I need to see the error message from the server.
use the following example to call asmx method and any web method from any where else
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'PageName.aspx/SaveData',
data: "{'radio':'" + input 1+ "', 'min':'" + input 2 + "', 'sec':'" + input 3 + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
});

Trying to refresh one div content on a page without changing position of the div

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ajax div example</title>
<script type="text/javascript" src="jscripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
var dbn,machine_name;
function main_draw(d,m,r)
{
dbn = d;
machine_name = m;
draw_charts();
if ( r > 0 )
{
setRefreshid = setInterval("draw_pie()",r);
}
}
function draw_charts()
{
document.getElementById('ajdiv4').innerHTML = "";
document.getElementById('ajdiv3').innerHTML = "";
document.getElementById('ajdiv2').innerHTML = "";
document.getElementById('ajdiv1').innerHTML = "";
draw_pie();
draw_line();
draw_space();
draw_backup();
}
function draw_pie()
{
setTimeout(function() {
$.ajax( {
url: 'JSCharts/graph_pie1.html',
success: function(html)
{
$("#ajdiv4").html(html);
}
}); }, 100);
}
function draw_line()
{
setTimeout(function() {
$.ajax( {
url: 'JSCharts/graph_line1.html',
success: function(html)
{
$("#ajdiv3").html(html);
}
}); }, 200);
}
function draw_space()
{
setTimeout(function() {
$.ajax( {
url: 'JSCharts/space_graph.php',
success: function(html)
{
$("#ajdiv2").html(html);
}
}); }, 300);
}
function draw_backup()
{
setTimeout(function() {
$.ajax( {
url: 'JSCharts/backup_graph.php',
success: function(html)
{
$("#ajdiv1").html(html);
}
}); }, 400);
}
</script>
</head>
<body>
<div id="ajdiv1" style="float:left"></div>
<div id="ajdiv2" style="float:left"></div>
<div id="ajdiv3" style="float:left"></div>
<div id="ajdiv4" style="float:left"></div>
<button id="b1" onclick="main_draw('CQ1','va2apsap010',10000)">Display Content</button>
</body>
</html>
Above is an entire code which makes AJAX calls upon clicking on "Display Content" and after that it refreshes content of div "ajdiv4" by calling function "draw_pie". The only problem with this is that when it refreshes, it moves the pie graph all the way to the left. I would like it to stay and update it in the current position. Please help if any of you know what is going on here, Thanks.
Have you tried specifying the dimensions of your DIVs? With your current code, you could probably do:
<style>
#ajdiv1, #ajdiv2, #ajdiv3, #ajdiv4 {
height:200px;
width:200px;
}
</style>
Alternatively, add a class attribute to simplify things:
<style>
.chartContainer {
height:200px;
width:200px;
}
</style>
If you have a working version up, or can post something on JSfiddle, that would make things easier to troubleshoot.

Why Ajax Jquery form click not working vs div that works?

Ajax Jquery form not working vs div why its happen and how can i fix my error?
view.html-Code with form
not working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<form id="parse-form" action="#" method="post">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</form>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
view.html -form replaced by div
working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="parse-form">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</div>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
controller.php -simple php file that return json array:
<?php
$arr=array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Thanks
The form has a default action with a type="submit" button, which is submitting, so you'll need to stop that from happening by adding return false or event.preventDefault() , like this:
$(document).ready(function() {
$('#submit-html').click(function(e) {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
return false;
//or e.preventDefault();
});
});
Without this, the form is submitting as it normally would with no JavaScript, leaving the page. So effectively it's doing a refresh, instead of AJAX submitting your form (which doesn't have time to complete...because you left :)
An element of type=submit inside a <form> will perform the form request when clicked on.
You need to abort the default behavior by running event.preventDefault() inside the click callback.
My guess is that the form is submitting and refreshing the page before the ajax has a chance to respond.
Try putting return false; at the end of the click handler.
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Of course you'll have the same issue if the user hits Enter in one of the fields. Unless you're preventing the Enter key from submitting the form, you may want to the handle the event using the submit() handler.
$('#parse-form').submit(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Try using submit() http://api.jquery.com/submit/ , this should work with keyboard events as well as clicks. You can use serialize() to get any form data into the ajax objects data variable.

Resources