Javascript/Jquery Post and Get? - javascript

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
?>

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;
}

JQuery $.ajax request returns me "Error 404" even if the resource exists

I'm developing an app with TideSDK and I need to send some data to a PHP script that will create a file to store it on the pc. I'm pretty new to AJAX and to send data I do:
var jsonString = JSON.stringify(GW2.items);
$.ajax({
url: "/assets/scripts/save.php",
type: "post",
dataType: "json",
data: { jsonString: jsonString }
}).done(function(data){
console.log(data);
});
Where GW2.items is a JSON object, "save.php" is my script and jsonString is the variable I want to send.
But, when I try to execute the program it returns me:
POST http://127.0.0.1:52432/assets/scripts/save.php 404 Not Found
And the answer is: Cannot POST /assets/scripts/save.php
This is the PHP script:
<?php
$jsonString = $_GET['jsonString'];
return {};
?>
I checked the path and it's correct so why it can't find my file?
Did you try your path with POST or just GET? It could be exist for GET requests (pasting the url on a browser) but probably not for POST or other HTTP verbs.
You can use REST clients like Postman to be sure, which is also a Chrome extension.

Executing cross domain javascript never hits code in .done

#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!

How to Get Response From rest URL using jquery

I have a URL https://aua.maharashtra.gov.in/aua/rest/checkauastatus
When I visit the URL in a browser, I get an XML response. I want to collect that response in a String using Javascript or jQuery. I tried many things but nothing worked.
Please help me to get that response in a String.
Try this:
$.ajax({
type:'POST',
url:'https://aua.maharashtra.gov.in/aua/rest/checkauastatus',
success: function(response)
{
alert(response);
}
Just see if your expected reponse is coming or not.
Hope this helps.
If you are trying to make a request to other domains, use the below code for reference.
$.ajax({
url: 'https://aua.maharashtra.gov.in/aua/rest/checkauastatus',
dataType: 'jsonp',
jsonpCallback: 'dataResult',
jsonp: 'callback',
});
function dataResult(data) {
//Access your data here.
};
If you are calling ajax with different domain , then ajax will not work, You have to call your server and collect data. For e.g using curl, then return as response. You can also use jsonp if it supports.

Get prayer time JSON data using JQUERY and Ajax

I want to READ JSON data using Jquery ana Ajax from this link
http://praytime.info/getprayertimes.php?lat=31.950001&lon=35.9333&gmt=180&m=3&y=2013&school=0&format=json&callback=?
and this is my code:
$(document).ready(function() {
var strUser ="http://praytime.info/getprayertimes.php?lat=31.950001&lon=35.9333&gmt=180&m=3&y=2013&school=0&format=json&callback=?";
$.ajax({
url: strUser ,
dataType: 'jsonp',
success: function(data){
jQuery.each(data, function(){
alert("yes");
});
}
});
});
I tried this code with other links , and it's correct, but from the specified link I don't get any out put, can you help me??
The url you are trying to access with JSONP doesnot support it. The server will need to return the response as JSON, but also wrap the response in the requested call back. So a way to solve this problem is using a server side proxy, which fetches the response from the specified url and passes it on to your client side js, like:
$.ajax({
type: "GET",
url: url_to_yourserverside_proxy,
dataType: "json",
success: function( data ) {
console.log(data);
}
});
where
url_to_yourserverside_proxy is a server side file that fetches response from the url specified
URL is outputting json but for cross domain need jsonp.
Not all API's provide jsonp. If cross domain API doesn't provide jsonp and isn't CORS enabled you will need to use a proxy to retrieve data due to same origin policy

Categories

Resources