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

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.

Related

How to refresh browser cache?

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!

Why I can't fetch data on the sometime by using curl_setopt and Ajax jquery?

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.

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

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

Categories

Resources