How to refresh browser cache? - javascript

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!

Related

AJAX POST requests not being received by PHP via $_POST

I'm building part of a Firefox OS app and I'm having to use the OpenBadges API, meaning I can't use more PHP, which would make this much simpler.
The problem I'm having now is that my data sent from an AJAX POST request:
$(function(){
$("#submitBtn").click(function(){
var mail = $('#mail').val();
$.ajax({
type: 'POST',
contentType: 'text',
dataType: 'JSON',
url: 'scripts/test.php',
data: {
mail: mail
},
success: function(data){
var jdata = jQuery.parseJSON(data);
alert("success! X: " + data);
}
});
});
});
...isn't being received by my PHP script:
<?php
if(isset($_POST['mail']))
{
$id_url = 'http://backpack.openbadges.org/displayer/convert/email';
$mail = $_POST['mail'];
$email = 'email='.$mail;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $id_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $email);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
curl_close ($curl);
$user_id = json_decode($result)->userId;
$test_var = json_decode($result);
echo $result;
//echo $test_var;
//echo $user_id;
}
//echo $mail;
?>
I keep getting a "cancelled" status on my PHP script in the Chrome dev tools Network tab, and I can see that it's sending the input in the form of "example%40gmail.com" instead of "#", but I'm not sure if that's part of the problem or not.
I've been looking and tweaking my code for about two days trying to figure out the problem, but none of the fixes that have worked for other people have worked for me.
Thanks in advance.
You're getting "cancelled" because the link you're clicking is being executed at the same time as your ajax call, in turn canceling it. What you need to do is use preventDefault() to prevent the click from canceling your request.
$(function(){
$("#submitBtn").click(function(e){
e.preventDefault(); // don't cancel the request
var mail = $('#mail').val();
$.ajax({
type: 'POST',
contentType: 'text',
dataType: 'JSON',
url: 'scripts/test.php',
data: {
mail: mail
},
success: function(data){
var jdata = jQuery.parseJSON(data);
alert("success! X: " + data);
}
});
});
});

Cannot translate with Google translate

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).

How to display instagram API response in javascript alert?

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

Javascript to make Post or Get call to a URL and return the text that's on the page

I've been trying to do this all morning I need to make either a POST or a GET call to this
URL http://cabbagetexter.com/send.php
I need it to return the text that's on the page, I know it can't be that difficult but I'm completely code blocked on this one,
I've tried using JQuerys .post and .get functions but I cant seem to return just the text on the page
any help would be appriciated
EDIT:
Ah ok so there's a technical reason for not being able to do it. balls, Thanks for the help guys
(function ($) {
$.ajax({
url: 'http://cabbagetexter.com/send.php',
type: 'text',
success: function (response) {
//do something with the text from the site
}
});
}(jQuery));
Obviously you need to host this script on the URL you are loading because of the same origin policy
You are running into the cross domain limitation. You can only to a request to a page in the same domain.
There is another possibility if you need to post calls to a page on another domain. Let's say your Javascript is being run from index.php. You might create a file called ctexter.php.
ctexter.php would use curl to make the post request to http://cabbagetexter.com/send.php, and would then output the response (the output from) send.php. So, if index.php makes an ajax call to ctexter.php, and ctexter.php is outputting the response from send.php, you have in effect achieved your goal.
You could make the curl post requests with this function:
function post_request($url, $data) {
$output = array();
foreach ($data as $key => $value) {
if(is_object($value) || is_array($value)){
$data[$key] = serialize($value);
}
}
$output = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = curl_error($ch);
}
curl_close($ch);
return $output;
}
where $url is (obviously) the url to post to, and $data is an associative array containing the data you want to submit.
Then on ctexter.php you could do something like:
// Since we already built the post array in the
// ajax call, we'll just pass it right through
$response = post_request("http://cabbagetexter.com/send.php", $_POST);
if($response['status'] == "ok"){
echo $response['content'];
}
else{
echo "It didn't work";
}
Finally, hit ctexter.php using JQuery .post():
$.post("ctexter.php",
{
firstparamname: "firstparamvalue",
somethingelse: "llama"
},
function(data) {
alert("It worked! Data Loaded: " + data);
});
If you're on the same domain, you'd use some code like this:
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
document.getElementById("targetElementID").textContent = ajax.responseText;
}
}
ajax.open("GET","http://cabbagetexter.com/send.php",true);
ajax.send();
Learn how to use AJAX
If not, then, sorry, you're out of luck because you'll run into the same origin policy error.
There is a way to make a request to that URL and get around the same origin policy. Put something like a PHP script on your own domain that makes a request to http://cabbagetexter.com/send.php and then call your own script from the javascript.
If your host supports PHP and cURL a script like this would do the job:
<?php
$url="http://cabbagetexter.com/send.php";
$post="";
if(strstr($url,"?")){
$split=explode("?",$url);
$url=$split[0];
$post=$split[1];
}
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 0);
if($post!=""){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}else{
curl_setopt($ch, CURLOPT_POST, 0);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
print $result;
?>

jquery problem with IE....works fine in firefox n chrome

I have a code which accept a query and uses yahoo websearch to return a suggestion.Its working fine in FF and Chrome . but in IE it gives no result. can any one help me on this??
Here is the code:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: "dummyapi.php",
data: {query: "yaho"},
success: function(xml) {
alert($("Result",xml).text());
/* do something here */
},
error: function(xhr, type, exception) { alert("Error: " + type); }
});
});
dummyapi.php
$Squery = $_GET['query'];
$appid = "S8YhyGzV34HB2jaWxc9VsNIPqeeg0OwqV.WQ0IvF1lblZsUiFzlyEs12kVyH5_IT";
$u = "http://search.yahooapis.com/WebSearchService/V1/spellingSuggestion?appid=".$appid."&query=".$Squery;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $u);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec($ch);
curl_close($ch);
echo $xml;
It seems like you're missing the closing }); of $.ajax, except if it's not shown there.
Two quick things that are syntax errors:
Missing the closing }); of the ajax call (or document.ready, depending on how you look at it)
Missing the closing " of the $u variable.
Just tested the code with these things fixed and it is working for me on IE, FF, Chrome.

Categories

Resources