Executing cross domain javascript never hits code in .done - javascript

#People downvoting this issue: what's wrong with it? Which info am I not providing?
I'm trying to do a cross-domain service call via javascript from domainA to domainX, but somehow the line console.log('OK'); is never hit. The line console.log('1'); is hit.
How can I make sure the line console.log('OK'); is executed?
www.domainA.com/test.aspx
<script type="text/javascript">
(function () {
var ttScript = document.createElement('script'); ttScript.async = true;
ttScript.src = '//www.domainX.com/js/test.js?v=1';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ttScript);
})();
</script>
www.domainX.com/js/test.js
(function () {
console.log('1');
$.ajax({
url: "//www.domainX.com/iplookup.php",
data: null,
type: 'GET',
async: false,
crossDomain: true,
dataType: 'jsonp'
}).done(function (data) {
console.log('OK');
});
})();
I tried jsonp and json as dataType. But when setting it to json or setting crossDomain to false I get:
XMLHttpRequest cannot load http://www.domainX.nl/iplookup.php?callback=jQuery1102023322901595383883_1419031985295&_=1419031985296. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
www.domainX.com/iplookup.php
I tried with and without Access-Control-Allow-Origin
<?php
header('content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
$data = json_encode($_SERVER['REMOTE_ADDR']);
echo "jsonp_callback($data);";
//print json_encode($_SERVER['REMOTE_ADDR']);
?>
With the above configuration I get NO errors in my Chrome console.
Under network I see that the test.js is loaded succesfully when requesting page www.domainA.com/test.aspx
I checked under Net tab under the Response tab and I see the call being made to //www.domainX.com/iplookup.php" which returns the value I'd expect, in this case an IP address.
What more can I do?

When using jsonp you are atually requesting a file like this:
jsonp_callback(yourDataHere);
And this file is included into your document making the values accessible when the function is called.
So your php-file has to echo something like this:
<?php
$data = json_encode($_SERVER['REMOTE_ADDR']);
echo $_GET['jsonp_callback']."($data);";
?>
Note that you have to add the jsonp-function to the $.ajax:
$.ajax({
url: "//www.domainX.com/iplookup.php",
async: false,
jsonp: 'jsonp_callback',
dataType: 'jsonp'
}).done(function(data){
console.log(data);
});
Btw: Why would you do that call syncronous?
Edit: I wrote kinda crap. I updated my answer. The file you are requesting is just calling a function with your data as parameters. The callback is then the function itself. Jquery should normally handle that for you and make the data available in .done().
Read through the manual here!

Related

PHP MVC & AJAX - AJAX does not call function from controller

So I am trying to learn AJAX requests, and in testing purposes, I am trying to use it in my personal project. I set up some test functions here and there, to test out how I can use AJAX in my project, and I got on an issue.
I'm making an AJAX call from script tags in my html, but it appears to just return all the html of that page.
AJAX call code is:
$.ajax({
URL: "<?php echo URLROOT;?>tasks/setcompleted",
type: "GET",
data: {id:'3'},
contentType: "application/json; charset=utf-8",
success: function(res){
console.log(res);
}
});
PHP Tasks controllers method setcompleted() code is just a simple echo of data passed from AJAX request via GET:
public function setcompleted(){
if(isset($_GET['id'])){
echo $_GET['id'];
}
}
I did some research, and found similar questions here, that suggested to check the URL that is passed to AJAX request. I did that, the URL that is passed in AJAX request is correct and works, if I manually write it into browser and add necessary parameters for the GET.
Can anyone suggest what am I doing wrong here?
Your function returns nothing.
public function setcompleted()
{
if(isset($_GET['id']))
{
$output = json_encode($_GET['id']);
}
return $output;
}

How to post to php with ajax, I consistently get error 400 bad request?

I am trying to send a "POST" request to my backend PHP code, which resides in functions.php in Wordpress. I get a readystate:4 and bad request(400 status) error when I run the code, if I change the "POST" to "GET" it works.
This is not the first time I encounter this, but previously it has been in my spare time projects, this time it is for work. as mentioned above I can "solve" it by changing the method to "GET", but that is not the method you are supposed to use when you add to your database. I've tried to comment out the lines with "dataType", "contentType", and "processData", but it doesn't make a difference I still just get a bad request(400) error. I have several "GET"s that work fine elsewhere in functions.php and urlen is pointing directly to functions.php.
JS
function AddToTable(){
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
jQuery.ajax({
type: "POST",
url: urlen,
dataType: "json",
contentType: "application/json",
processData: false,
data: JSON.stringify(Data),
success: successfunction,
error: errorfunction,
});
function successfunction(data){
RefreshTable();
}
function errorfunction(data, status) {
alert("error: "+status+" Content: " + JSON.stringify(data));
};
}
Functions.php
<?php
function CreateProduct(){
exit;
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
I expect it to send the data to the server function, so I can do more with it there. But I get a readystate:4 and state 400 errorcode.
UPDATED: to include the Functions.php part of the code.
I guess your data to be posted is malformed.
You have prepared it like
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
Variables to be posted should not be in quotes so your code there should begin like
Data={action:"CreateProduct",Password: Password.value,Varenr: Varenr.value, .....
and so on
A GET request to a URL will simply tell you whether or not it exists, in basic terms. If you send a GET request to cnn.com it will respond with a 200, if send a GET to cnnbootyshort.com, you will get no response.
In your case, rather than using exit, you could try using die(), along with an echo of what you want to send back to the browser.
<?php
function CreateProduct(){
echo "200";
die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
And your JS
function successfunction(data){
console.log(data); // for debugging
RefreshTable();
}
function errorfunction(data, status) {
console.log(data); // for debugging
alert("error: "+status+" Content: " + JSON.stringify(data));
};
Alternatively you can use wp_die() if you want to use a Wordpress specific function. Here is some documentation regarding its use.
<?php
function CreateProduct(){
wp_die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>

Unable to parse the json from url

<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
async: false,
contentType: "application/json",
url: "http://www.XXX.XXX.in/api/categories",//url:"dir/categories",
dataType: "jsonp", //dataType: "jsonp",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");
//alert(det);
});
alert(data);
},
error: function (data) {
alert("this is error "+data);
}
});
});
</script>
<div id="display"></div>
</body>
</html>
In the above code I am trying to access the categories json and print the details.
I am doing it in two ways:
I have kept the categories file in dir/ folder and accessing it which shows me result properly.
When I try to access it online it gives me an error:
When I give dataType:"json" instead of jsonp I gives following error:
OPTIONS http:// XXX.XXX.in/api/categories 404 (Not Found)
XMLHttpRequest cannot load http:// XXX.XXX.in/api/categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:8080' is therefore not allowed access.
I dont know whether the server has cross platform ref. added.
You can't access data of another domain from your domain using JAVASCRIPT. It is a security rule known as the "Same origin Policy"
So, to get data of another domain, you could write server side script (maybe in PHP or some other language you're familiar with.), then you can make ajax request from your script to the server.
The same origin policy is enforced by the browser to protect websites from other websites making xhr requests and displaying their content as if it was their own.
So site A.com cannot connect to B.com with XHR or:
http://A.com cannot connect to http://sub.A.com
localhost:80 cannot connect to localhhost:8080
Edit
As you requested, here is the solution using PHP script.
get_json_from_url.php
<?php
header("Content-type: text/json");
$response = fopen('http://www.eazydial.logicengine.in/api/categories', "rb");
echo stream_get_contents($response);
?>
HTML page
<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "get_json_from_url.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");
});
console.log(data); //alert can't print [object] so always use console.log() to inspect object and it values. (see output in browser console)
},
error: function (data) {
console.log("Err:");
console.log(data);
}
});
});
</script>
<div id="display"></div>
</body>
</html>
The solution provided here in PHP script will work only for GET request method. If you want to use POST request for any API then look for cURL library to get data from api.

Token error when parsing return data in Ajax call

I am creating an app using HTML, jQuery Mobile, jQuery and Cordova. My requirement is to authenticate an user from the app by calling a remote server. I am developing my localhost WAMP stack.
My jQuery is as below.
$.ajax({
type: 'POST',
url: 'http://localhost/server/',
crossDomain: true,
data:{appkey:'1234567',action:'authenticate', username: u, password :p},
dataType: 'jsonp',
async: true,
success: function (data){
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Invalid Username or Password");
window.location = "index.html";
}
});
The remote call url is below. JQuery automatially adds ?callback= to the remote url as the datatype is jsonp, which is fine.
localhost/server/?callback=jQuery18306688079617451876_1383495199431…4567&action=authenticate&username=fdf&password=fdfdf&_=1383495208981
The response from the remote url is as below in Chrome Developer console.
{"success":"false"}
In the PHP part at server, I am using the below code to return the json object.
header('Content-type: application/json');
echo json_encode($araryVal);
It looks for me that all things are perfect, but my code breakpoint never reaches the success section of the ajax call. It always break out in error section.
In the developer console I see the error message.
Uncaught SyntaxError: Unexpected token :
JsonLint says the json is valid. Please let me know what I am doing silly.
I don't think your data type is JSONP, it's just JSON. If it were JSONP, your content-type should be "application/javascript" and your response text should wrap the JSON object it returns with the javascript function provided to the server in the callback parameter.
(Actually your error is probably PHP emitting a notice about an undefined variable: araryVal ... You sure that shouldn't be arrayVal? :)
I already accepted the answer provided by #Fabio. I just want to provide the technical details which solved my problem.
The hint from Fabio helped me to do some research on this. Thanks man.
I have added the callback options to the ajax call as below.
$.ajax({
type: 'POST',
url: 'http://localhost/server/',
crossDomain: true,
data:{appkey:'1234567',action:'authenticate', username: u, password :p},
dataType: 'jsonp',
contentType: "application/javascript",
jsonp: 'callback',
jsonpCallback: 'mycallback',
async: true,
success: function (data){
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Invalid Username or Password");
window.location = "index.html";
}
});
The remote call url is as below after the above change. JQuery now add "mycallback" instead of some random callback value "jQuery18306688079617451876_1383495199431…4567" for callback parameter.
localhost/server/?callback=mycallback&action=authenticate&username=fdf&password=fdfdf&_=1383495208981
In the PHP side I modified the output to include the callback value with the json string.
header('Content-type: application/javascript');
echo "mycallback(" . json_encode($araryVal) . ")";
Today was the day I understood how to use jsonp with callback. Thanks to all.

Javascript/Jquery Post and Get?

Is it possible to have a piece of code or a function that does the following.
I would like for a javascript file to send a request to a different domain of mine with a variable. This webpage would check the variable against the database and return to the original javascript file the result of being either TRUE or FALSE
If you are sending requests between domains, you should have a look at http://api.jquery.com/jQuery.ajax/ with the dataType set to jsonp to load the response using a script tag.
More details on JSONP: https://stackoverflow.com/search?q=jsonp
I didn't know of JSONP and used a diffrent approach
$.ajax({
type: "GET",
crossDomain:true,
url: 'http://otherdomain/check.php',
success: function(data) {
// check.php response
}
});
and in check.php
<?php
$allowable_hosts = array('http://originaldomain','http://anotherdomain');
if (in_array($_SERVER['HTTP_ORIGIN'],$allowable_hosts))
header('Access-Control-Allow-Origin: *');
//echo "ok"; - your check code
?>

Categories

Resources