I'm trying to translate text with Google translate:
$.ajax({
type : "GET",
url : "https://www.googleapis.com/language/translate/v2",
dataType : 'jsonp',
cache : false,
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
data : "key="+translateKey+"&source=en&target=de&q=Hello",
success : function(res) {
console.log('res', res.data.translations[0].translatedText);
},
error : function(xhr, ajaxOptions, thrownError) {
}
});
$.get("https://www.googleapis.com/language/translate/v2", {
key : translateKey,
source : "en",
target : "fr",
q : "hello"
}, function(res) {
console.log(res.data.translations[0].translatedText);
}, "json").fail(function(jqXHR, textStatus, errorThrown) {
alert("error :" + errorThrown);
});
I'm using API's:
Google+ API
Google+ Domains API
Translate API
I create a Google project and inserted my local host and my real site address.
I got back an error 403 forbidden.
I tried to copy it into the URL like that:
https://www.googleapis.com/language/translate/v2?key=AIzaSyCClt5fo3FDMAym59FQw-R5D39eaTNfWIg&source=en&target=de&q=Hello
And I got the error JSON.
Where am I wrong?
I'm writing with AJAX and Javascript.
HERE THE ANSWER !!!
you must to pay.. BUT their is a hack in php if someone want to use:
<?php
function curl($url,$params = array(),$is_coockie_set = false){
if(!$is_coockie_set){
/* STEP 1. let’s create a cookie file */
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
/* STEP 2. visit the homepage to set the cookie properly */
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
}
$str = ''; $str_arr= array();
foreach($params as $key => $value){
$str_arr[] = urlencode($key)."=".urlencode($value);
}
if(!empty($str_arr))
$str = '?'.implode('&',$str_arr);
/* STEP 3. visit cookiepage.php */
$Url = $url.$str;
$ch = curl_init ($Url);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
return $output;
}
function Translate($phrase, $from , $to){
$ret = "";
if(strlen($phrase)>1600){ //split and translate each part individually to get around 2048 size limit:
$phrases = str_split($phrase,1600);
foreach($phrases as $p) $ret .= translate($p, $from, $to);
return($ret);
}else{
$url = "http://translate.google.com/translate_a/t?client=p&q=".urlencode($phrase)."&hl={$to}&sl={$from}&tl={$to}&ie=UTF-8&oe=UTF-8&multires=0" ; // client = p !
$out = json_decode(curl($url), 1);
foreach($out['sentences'] as $sentence){
$ret .= $sentence['trans'].' ';
}
return stripslashes(trim($ret));
}}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body dir="rtl">
<?php
$text = "my name is name" ;
echo Translate($text,'en','iw');
?>
</body>
</html>
Its better to go for an experienced and a professional website translator. I don't believe on translation tools for any kind of translation, human translators are the best option for these kind of jobs.
goto Google API Console, click on "Enable an API" and then search for "Translate API" and switch it on(http://pastemehere.com/ai2xhwxm).
Related
I want to confirm transaction from other third-party, e.g I pay goods of $50 to juma Joe after click pay button and pay page is still loading and tell me to wait almost 5 seconds to check if the transaction is processing succeed, and if the transaction succeeds, it redirects to a success page.
So i need javascript and html confirmation code call from php to check if transaction is success then to show redirect seconds.
Thank you
Bellow is code for for validate transaction
$result = array();
$url = 'https://api.xxxx.co/transaction/verify/reference';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer xxxxxxx']
);
$request = curl_exec($ch);
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
}
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
echo "Transaction was successful";
//Compete transaction
}else{
// Not complete
echo "Transaction not complete";
}
So. You can using ajax to request and response in you code.
Example:
PHP Code: validate.php
//....above you code here
// my code config response
$res = [
'mess' => null,
'status' => 404
];
//...you code validation result
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
//Compete transaction
$res['mess'] = "Transaction was successful";
$res['status'] = 200;
}else{
// Not complete
$res['mess'] = "Transaction not complete";
$res['status'] = 404;
}
// my code response mess
echo json_encode($res);
So, below my front-end code, using jQuery Ajax to send POST request.
Document you can check here
$(document).ready(function() {
function validate(){
$.ajax({
url: 'validate.php',
type: 'POST',
dataType: 'json',
success: function(res) {
if (res.status === 200) {
console.log("you code here for success");
} else {
console.log("you code here for fail");
}
},
error: function(err) {
console.log("Request is error with: " + err);
}
});
}
});
HTML for submit button. Call to javascript
<button id="submit" type="submit" onclick="validate();">Send Request</button>
function checking(){
$.ajax({
dataType: "json",
url: status.php,
success: function(data){
if (data.done=='y') window.location = 'done.html';
}
});
}
setInterval(checking,5000);
With this script, you can call for every 5 seconds. But the best practice is to use a webhook. For more information, search it up on your payment gateway API documentation.
status.php
$result = array();
$respond=array();
$url = 'https://api.xxxx.co/transaction/verify/reference';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer xxxxxxx']
);
$request = curl_exec($ch);
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
}
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
$respond[done]='y';
//Compete transaction
}else{
// Not complete
$respond[done]='n';
}
echo json_encode($respond);
I have been stuck for a while on this mistake and I just can't seem to find it. I get this error:
ERROR: SyntaxError: Unexpected string in JSON at position 1
I am trying to do an AJAX-request to dashboard.php using this dashboard.js file:
$(".next").click(function(){
console.log("next uitgevoerd");
i++;
huidige_pagina += 1;
document.getElementById("pagina").innerHTML = huidige_pagina;
$.ajax({
type: 'POST',
url: 'http://goad-as-05/ramon/logic/dashboard.php',
contentType: 'application/x-www-form-urlencoded',
dataType: 'JSON',
data: { "pagina": i },
success: function (resultaat) {
alert(resultaat);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + errorThrown);
}
});
});
Here is the php-code:
<?php
header("Content-Type: application/json; charset=utf-8", true);
if(isset($_POST["pagina"])){
$pageno = $_POST["pagina"];
echo $pageno;
} else {
echo "foutje";
}
// $url will contain the API endpoint
$url = "https://app.teamleader.eu/api/getContacts.php";
// $fields contains all the fields that will be POSTed
$fields = array(
"api_group"=>(GROUP_KEY),
"api_secret"=>(SECRET_KEY),
"amount"=>2,
"pageno"=>$pageno
);
// Make the POST request using Curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
// Decode and display the output
$api_output = curl_exec($ch);
echo curl_error($ch);
//$json_output = json_decode($api_output);
echo json_encode($api_output);
header('application/json');
// Clean up
curl_close($ch);
?>
Here is my html:
<div class="pagina">
<p id="pagina">1</p>
</div>
I am sure it is not my URL, as both files are in the same folder.
Do I have to use JSON.stringify("pagina":i) first and use that?
Any help is appreciated, it probably is the smallest mistake I just can't seem to find.
SOLUTION FOUND:
Refresh my javascript with ctrl+F5 when loading it, completely forgot about cache.... thanks everyone for trying to help!
Ramon
In PHP, you can not use the HEADER function after an output.
echo json_encode($api_output);
header('application/json'); // delete this line
the server ends up producing an error that makes the JSON string unusable.
EDIT:
header("Content-Type: application/json; charset=utf-8", true);
if(isset($_POST["pagina"])){
$pageno = $_POST["pagina"];
echo $pageno; // ERROR
} else {
echo "foutje";
}
with the echo $pageno; line write the result sent by POST generating an error.
EDIT 2:
echo curl_error($ch);
This line also produces an unencoded output in JSON
EDIT 3:
I'm happy that you've been able to find the solution to your problem and to prevent it from happening again I suggest you edit the JS file address so:
echo 'dashboard.js?'.time(); // disable browser cache
The problem was with the the browser cache, i forgot to use ctrl + f5 to reload the cache and reload my javascript that way, thanks for the help everyone!
I'm query data from another sever by using curl_setopt PHP and Ajax
I've already to test my below function it is work but it seem not smooth enough because sometime when I try to refresh and internet got a little big slow I will never got data.How ever when i check on firebug in Firefox I found as below json respond.
"<html><head>
<meta http-equiv="refresh" content="0;url=http:MyPartnerWebsite!queryLuckNumberRecordByPeriods.action?gwqqnhmpepceiqqn">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
</head><body></body></html>
"
*I'm got stuck right now because I don't know how to do with this respond *
private function http_code() {
$ch = curl_init();
if (!$ch) {
die("Couldn't initialize a cURL handle");
}
$ret = curl_setopt($ch, CURLOPT_URL, "http://Mypartnerwebsite!queryLuckNumberRecordByPeriods.action");
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ret = curl_setopt($ch, CURLINFO_PRETRANSFER_TIME, 0.1);
$ret = curl_setopt($ch, CURLINFO_HTTP_CODE, true);
$ret = curl_setopt($ch, CURLOPT_PRIVATE, false);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$ret = curl_exec($ch);
$data;
$res;
if (empty($ret)) {
$res = 0;
$data = 0; // Partner server slow.
curl_close($ch);
} else {
$info = curl_getinfo($ch);
curl_close($ch);
if (empty($info['http_code'])) {
$res = 01;
$data = 01; // Got empty date from partner server
} else {
if ($this->errorType($info['http_code']) == TRUE) { // errors type
$data = $ret;
$res = $this->errorType($info['http_code']);
} else {
$data = $ret;
$res = 'unknowError';
}
}
}
echo json_encode(array('res' => $res, 'data' => $ret));
}
This is a function to check to know what type of server errors respond
Purpose I want to checking when my partner server errors and I will send this kind of errors to my website for make sure what kind of errors.
private function errorType($haystack) {
$errors = array(404, 200, 201, 204, 500, 501, 502, 503, 504, 505, 100, 203);
if (in_array($haystack, $errors)) {
return $haystack;
} else {
return FALSE;
}
}
Here is Jquery Ajax to fetch data from my own server
$.ajax({
method: "GET",
url: "<?PHP echo base_url('getcurrentday'); ?>",
dataType: "JSON",
beforeSend: function (xhr) {
},
success: function (data, textStatus, jqXHR) {
$(".loading").html("");
if (data.res !== 200) {
$("<p>Errors type:"+data.res+"</p>").appendTo(".errors");
} else {
if (data.data == false) {
getdata();// I want to reload Ajax if I got respond false and my data = '';
}
$.each(eval(ldata), function (i, val) {
$(val.anydata").appendTo(".result");
})
}
}
});
Please help.
It seems that your ajax call gets a timeout and therefor it is not always working. You can increase the timeout setting of ajax.
Furthermore you can add an error function to see when errors like timeouts occur.
$.ajax({
//your ajax code here...
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
},
timeout: 10000 // sets timeout to 10 seconds
});
The reason you still see the response in firebug is that the browser will anyways receive the server response, even on timeout, but it will not reach your jquery code.
I am trying to send a delete request to instagram api using ajax but my current javascript code display the response in alert box as:
<pre></pre><pre></pre>
so i cant find the problem why delete request is not successful! if i call the same php script(doit.php) from the browser and pass it media id then the delete will be successful!
could any one tell me what is wrong with my current delete ajax request that fails to make delete request to instagram api?
Instagram API Docs for Deleting Like
sample api response:
{
"meta": {
"code": 200
},
"data": null
}
javascript:
<script>
function deleteLike(a,b)
{
alert("MediaID:"+a+"\nId:"+b);
var url = "./doit.php";
$.post(url, {
"method": "post",
//"method": "delete",
"MediaID": a,
}, function(data)
{
var ajaxResponse = data;
alert("Response:"+ajaxResponse);
if (data.meta.code == 200) {
alert("sucessDelete");
}
})
}
</script>
PHP CODE:
$MediaIDvar= $_POST["MediaID"];
//$MediaIDvar= $_GET["MediaID"];
$url2 = "https://api.instagram.com/v1/media/".$MediaIDvar."/likes?xxxxx";
$api_response2 = get_data2(''.$url2);
$record2 = json_decode($api_response2); // JSON decode
echo '<pre>' . print_r($api_response2, true) . '</pre>';
echo '<pre>' . print_r($record2, true) . '</pre>';
// to see what is in the $api_response and $record object
/* gets the data from a URL */
function get_data2($url2) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$MediaIDvar= $_POST["MediaID"];
$MediaIDvar= $_GET["MediaID"]; // => this will overwrite the previous $MediaIDvar
it will work if you call the php script with a GET variable, not through ajax using POST ;-)
Is it possible to create a web site and, with JavaScript, read the feed from a Facebook page and display it to my sites visitor without them having to login, or even have Facebook for that matter.
I'm getting lost in the Facebook documentations :(
Thanks to #mch here commes version that uses php as a proxy to read a Facebook feed with JavaScript.
Place a file called proxy.php on your server and add this code:
<?php
// always add this header to ensure the JSON is output in the correct format
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header('Content-Type: application/json; charset=utf-8');
$graphUrl = $_POST[graphUrl];
if ($graphUrl == "") {
$graphUrl = "https://graph.facebook.com/facebook/feed/";
}
//App Info, needed for Auth
$app_id = "1234567890";
$app_secret = "0000011122234334445556aaass";
//retrieve auth token
$authToken = fetchUrl("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={$app_id}&client_secret={$app_secret}");
//Echo back json to read client side.
echo fetchUrl("{$graphUrl}?{$authToken}");
function fetchUrl($url){
$ch = curl_init();
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$retData = curl_exec($ch);
curl_close($ch);
return $retData;
}
?>
Change app_id, app_secret to your apps ids. Create apps here https://developers.facebook.com/apps/
Create a HTML file next to your proxyfile. Add this code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>FB reader</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var timeout = 5000,
load_error;
load_error = function (jqXHR, textStatus, errorThrown) {
if (errorThrown === "timeout") {
alert('Server bussy');
} else {
alert('error: 404', textStatus + ": " + errorThrown);
}
};
$(document).ready(function() {
console.log('Loading from Facebook...\n');
//Change data: {graphUrl: 'https://graph.facebook.com/iambounty/feed'}, to what ever you want.
$.ajax({
type: 'POST',
url: 'proxy.php',
data: {graphUrl: 'https://graph.facebook.com/iambounty/feed'},
timeout: timeout,
error: load_error,
success: function (rv) {
var data = rv.data,
len = data.length,
i,
out = '';
for (i = 0; i < len; i += 1) {
if (data[i].description) {
out += data[i].description + '\n\n';
}
}
console.log(out);
}
});
});
});
</script>
</body>
</html>
You can do it on the server side with PHP. Create a facebook App in the Facebook developer center to get a App Key and Secret Key.
$profile_id = "1234567890";
//App Info, needed for Auth
$app_id = "0001234567890";
$app_secret = "abc123ebf123f3g5g6j";
/* USE THIS LINE INSTEAD OF THE "veryfypeer" LINE BELOW */
Facebook::$CURL_OPTS[CURLOPT_CAINFO] = '/path/to/crt/fb_ca_chain_bundle.crt';
//retrieve auth token
$authToken = fetchUrl("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={$app_id}&client_secret={$app_secret}");
$data['feed_data'] = fetchUrl("https://graph.facebook.com/{$profile_id}/feed?{$authToken}");
function fetchUrl($url){
$ch = curl_init();
/* DO NOT USE THE FOLLOWING LINE: I'VE COMMENTED IT OUT HERE */
// curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$retData = curl_exec($ch);
curl_close($ch);
return $retData;
}
... on the Javascript side I think it's not possible, since the FB API Secret must be hidden from the public. Information taken from here