Google Safe Browsing with jQuery - php

I was trying to do some test with Google Safe Browsing Lookup API.
$(document).ready(function(){
$("button").click(function(){
$.get("https://sb-ssl.google.com/safebrowsing/api/lookup", { client: "api", appver: "1.5.2", apikey: "MYAPI123", pver: "3.0", url:"www.ianfette.org" } )
.done(function(data) {
alert("Data Loaded: " + data);
});
});
});
But i cannot get a response from the server. I have tried with fopen in php and it works but i need it to do with jQuery and also to get the response code from the server for example 200 if the site is listed.
Maybe you can suggest and any PHP Solution.

$.get does an ajax request, which means that it is limited by the same origin policy, so you cannot access google.com from your domain.
To get around this, you probably need to implement a proxy url in php on your domain and request that with jquery.

Related

How to use HTTP request to retrieve data from Laravel API?

I am currently learning the Laravel API, and have been developed a very simple API that retrieves data from the database by simply entering 127.0.0.1:8000/api/XXX to the browser, however, when I tried to use ajax call to get data from the exact same url, the ajax always showed that the HTTP request was failed, the ajax codes I used are following:
$.ajax({
url: "127.0.0.1:8000/api/XXX",
success: function(data) {
let response = JSON.parse(data);
displayResult(response, 1);
}
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
And this code always resulted in alert("error");, therefore I am wondering that maybe there are some Routes needed to be written in order to let the API properly processes HTTP request? I have already defined a route in routes\api.php:
Route::apiResource('XXX', 'XXXController');
PS: when entering the API URL to the browser, it worked fine, it went wrong when doing an ajax call with the API URL.
Edit
These are the errors I got from the browser console after I used function(jqXHR, textStatus, errorThrown) to catch the errors
DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL
at Object.send (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:79420)
at Function.ajax (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:77118)
at retrieveAllBooks (http://127.0.0.1:8000/js/api-query.js:25:5)
at HTMLInputElement.<anonymous> (http://127.0.0.1:8000/js/api-query.js:10:7)
at HTMLInputElement.dispatch (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:41772)
at HTMLInputElement.y.handle (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:39791)
I am not exactly sure why it is an invalid URL, since if I copy and paste this link to browser, nothing goes wrong...
(Posted on behalf of the question author).
Actually the solution is simple, just add http:// to the url.

How can I see post body data in chrome dev tools?

I have this fetch api in React that is sending data to the server. The server runs PHP and I'm having trouble accessing the data with $_POST or with file_get_contents('php://input');
So I want to check every step of the process until I can see where the error is. I also want to verify how the post data is being sent. ie I want to see the actual data and the full request from the browser.
Fetch request looks like this:
export function sendEmail (data) {
return fetch('http://example.com/email.php', {
method: 'POST',
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(response => response.json())
}
When I go into google chrome's dev tools I see the request headers, response, etc but nowhere can I see the actual data being sent. I've looked around online and no one can seem to give a clear answer.
In your dev tools, click Network tab, then do the request and click on it. Scroll to the Request body section.
Network tab
Fiddler might be helpful in this scenario. It will show you the post body sent to your PHP endpoint.
I recommend you axios, easier to check if success or error and cleaner:
Post without any body sent;
import axios from 'axios';
axios.post('http://example.com/email.php')
.then(response=>response.data)
.then(response=>console.log('Success:', response))
.catch(err=>console.log('Error: ',err))
With some arguments:
axios.post('http://example.com/email.php',
{
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(response=>response.data)
.then(response=>console.log('Success:', response))
.catch(err=>console.log('Error: ',err)

How to ajax call a php file hosted on remote server and receive a response?

We are trying to call from index.html on local, a simple PHP file hosted on webhost000 to receive a response. PHP file is:
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo ($name);
}
?>
We would like to simply input a character on a textbox in html.index and receive the same character as response from the php. We are using an ajax call to do this in html file:
<script>
$(document).ready(function() {
$('#name').keyup(function() {
var name = $('#name').val();
var request = $.ajax({
url: "https://nedo93.000webhostapp.com/phpdemo.php",
method: "POST",
data: { name : name },
dataType: "html"
});
request.done(function( msg ) {
alert( "Request done: " + msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
(The remaining html should not be important, it works perfectly, tested and retested)
If we try to debug this we can see that the file is found, the request is sent, but we can't receive a response: screenshot
If we use this browser function instead, we can send data and receive a response without a problem, don't know if this can help.
Thank you in advance if you can answer this question.
This is because your PHP script is hosted on a different server and your AJAX call code is on local.
For AJAX to run, there is same-origin policy. Under this policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin (means both are on same domain). Read more about same origin policy here.
The same-origin policy prevents some Ajax techniques from being used across domains, although the W3C has a draft of the XMLHttpRequest object that would enable this functionality. Methods exist to sidestep this security feature by using a special Cross Domain Communications channel embedded as an iframe within a page, or by the use of JSONP, websockets, cross-domain messaging or cross-domain resource sharing.
So in short you will not be able to access the PHP request residing on a 000webhost server to be accessed using AJAX code on local.
Either you host the AJAX code on the same 000webhost domain as well or enable cross-domain resource sharing on 000webhost domain where your PHP code is running.
As far I know, 000webhost is a free server and doesn't supports these changes. So you will have to either get a better server or test this all in a local.
Also as you mentioned in your query, all HTTP requests like GET, POST, PUT works cross domain. But for AJAX, no its not so straight forward.
Hope this helps!
use json_encode
your code should be....
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
header('Content-Type: application/json'); //just used as info for your application
echo json_encode($name); //encode to JSON object
}
?>
after that do JQuery validation for checking Json reply (specially for error).

Cannot call getJSON method to fetch data

I am trying to fetch some JSON data. I can access the data just fine in a regular web browser, like this: http://www.ebrent.net/apis/tsp.php?fund=G+Fund&start=2003-01-01&end=2004-01-01, but I cannot get it to work in jQuery. What am I doing wrong?
Please take a look at my jsFiddle: https://jsfiddle.net/MrSnrub/mq31hwuj/
var tsp_api = '//www.ebrent.net/apis/tsp.php?start=2003-01-01&end=2004-01-01';
$.getJSON( tsp_api, function(json) {
// This alert never gets called.
alert("Success!");
// Set the variables from the results array
var data = json;
// console.log('Data : ', data);
// Set the div's text
$('#div-data').text(data);
});
You cannot get the result because the remote site doesn't have CORS enabled:
If you look at the console, you'll see:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
http://www.ebrent.net/apis/tsp.php?start=2003-01-01&end=2004-01-01.
(Reason: CORS header 'Access-Control-Allow-Origin' missing).
You can bypass CORS by using something like anyorigin.com, i.e.:
$.getJSON('http://anyorigin.com/get/?url=http%3A//www.ebrent.net/apis/tsp.php%3Fstart%3D2003-01-01%26end%3D2004-01-01&callback=?', function(data){
$('#div-data').html(data.contents);
});
This works if you run the your server without using https. Note fetchApi was used instead of jquery Library as its not readily available in the browser
var tsp_api = 'https://www.ebrent.net/apis/tsp.php?start=2003-01-01&end=2004-01-01';
function fetchData(url) {
return fetch(url, {
method: 'get'
}).then(function(response) {
return response.json();
}).catch(function(err) {
console.log(error);
});
}
fetchData(tsp_api).then((data)=> console.log(data)).catch((err)=> console.log(err));
This won't work on jsfiddle using HTTPS, the browser will refuse to load any resources over HTTP. As you've tried, changing the API URL to have HTTPS instead of HTTP typically resolves this issue. However, your ebrent.net did not allow CoRS for HTTPS connections. Because of this, you won't be able to get your result for jsfiddle

Creating a restful API using PHP as server and jQuery as client

I'm trying to create a Javascript client API service which calls the API of my site. This will be cross domain and i'm aware of the problems this causes. However, I need the user to send through some user credentials (whether that be their username and password encoded obviously or an API key + secret) so that I can return user specific details.
I initially looked at using the jsonp datatype however this doesnt allow you to set any custom headers so ruled this out.
I've been searching the web for a while and been unable to find a secure way of doing this cross domain, has anyone had any success with this and can give me some advice?
UPDATE:
I've tried this following code as suggested by lu1s, however I get an alert of 'boo' as stated n the error function..
$.ajax({
url: 'http://www.dotsandboxes.co.cc/__tests/cors.php',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: function (xhr) {
xhr.setRequestHeader('securityCode', 'Foo');
xhr.setRequestHeader('passkey', 'Bar');
}
});
Thanks
You can. Try adding the Allow-Access-Control-Origin: * to your HTTP response headers, as well as the correct content-type.
Try with a simple PHP script like this:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: text/json');
echo json_encode(array('success'=>true,'data'=>'foobar'));
?>
Check this site to read more info about cross-origin: http://enable-cors.org/
About the authentication, it's NOT recommended to send usernames or passwords, even if they're encrypted. As you stated, it's better to pass a token in the URL. Best if following standards like http://oauth.net/2/ .

Categories