Can someone explain me how to make a REST call using jQuery/Javascript? I tried using the .getJSON() and .ajax(), but neither helped me.
This is the REST URL :
http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&date=2010-01-15&format=json&key=API_KEY
Code:
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode='+zip+'&format=json&key=**<KEY HERE>**',
function(data)
{
alert(data.AQI);
}
);
$.ajax({
url: 'http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode',
type: 'GET',
data: 'zipcode='+zip+'&format=json&key=**<KEY HERE>**',
success: function() { alert('get completed'); }
});
there are a couple of problems. First, you need to add &callback=? to the end of the querystring to allow the crossdomain.
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D&callback=?',
function(data)
{
alert(data.forecast[0]);
}
);
You will then get an Uncaught SyntaxError: Unexpected token : error. This is because you are expecting json data, but the headers on the server are sending text/html - not application/json. Take a look at the console when you run this fiddle, you'll see the errors.
Therefore, you can't get the data from cross domain because you have to be using jsonp - which requires the header to be sent correctly.
If this is your api, then you just need to send the correct header, otherwise, you need to get with the developers there and ask them to fix it.
Alternatively
If neither of those above options work, you could always create a proxy script that would get the contents of the json feed for you and echo it out. Here's one in PHP:
<?php
// myproxy.php
header('Content-type: application/json');
$zip = $_GET['zip'];
$results = file_get_contents('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=' . $zip . '&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D');
echo $results;
?>
Then, you would just point your $.getJSON to this script on your server:
$.getJSON('/myproxy.php?zip='+zip,
function(data)
{
var mydata = jQuery.parseJSON(data);
alert(mydata.forecast[0]);
}
);
Related
This has been bugging me for the last few hours, and I've tried various searches but never found exactly this issue with an answer. Maybe asking and showing some code will help me get this figured out.
I am using ajax to do a post to PHP, which I want to just give a notification so that I may update a div on the page. In this case, I just need the PHP to say something like "Cfail" which the javascript would use to update page content.
Originally, I was going to try just text responses. So, my PHP for example would be like this:
<?php
session_start(); //Because have an encoded captcha answer.
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
echo 'Cfail';
}
?>
The Javascript would be:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'text',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned=='Cfail'){
alert("I read it right!");
}
}
});
});
});
It would run through the script just fine, but the result never would be what I was asking for. Alert showed the corrct text, however, research indicated that the issue with this was PHP apparently adding white space. The common answer was the encode a JSON response instead. So, I tried that.
Updated PHP:
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
$result = array('result' => 'Cfail');
echo json_encode($result);
exit;
}
?>
Updated Javascript:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'json',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
}
});
});
});
Which now no longer runs successfully. The alert doesn't come up, and the loader object remains visible(indicating the success never goes through). I tried putting an error section to the ajax, and it indeed fired that. However, I had no idea how to parse or even figure out what the error was exactly. The most I got in trying to get it was what PHP was outputting, which was {"result":"Cfail"} .... Which is what I would EXPECT PHP to give me.
I can work around this, I've done a similar set-up with just echoing a number instead of words and it used to work just fine as far as I knew. I'd just like to figure out what I am doing wrong here.
EDIT:
I managed to figure out what the issue was in my case. I had a require('config.php'); between the session start and the json_encode if statement. For some reason having the external file added, which was just me setting a couple variables for the code further down, some hidden character was added before the first { of the JSON object.
No idea why. As I said, it was just a $var='stuff'; situation in the require, but apparently it caused the issues. :/
Use this like
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
//$result = array('result' => 'Cfail');
$data['result'] = 'Cfail';
echo json_encode($data);
exit;
}
?>
This works for your javascript
use the below code, in your success call back, first parse the encoded json object that you are recieving from the back end and access the object property result to check it's value
success: function(returned){
returned = JSON.parse(returned);
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
I am trying to solve one problem with reading json object sent via ajax request in php file and I am keep gettin null in the console.
Javascript file
//create function to send ajax request
function ajax_request(){
console.log("hello");
var post_data = {
"news_data" : 'hello',
"news_date" : '1st march'
}
$.ajax({
url : 'index.php',
dataType : 'json',
type : 'post',
data : post_data,
success : function(data){
console.log(data);
}
});
}
//on click event
$('#news_post_button').on('click', ajax_request);
and php file which is only for testing to see what i get
<?php
header('Content-Type: application/json');
$aRequest = json_decode($_POST);
echo json_encode($aRequest[0]->news_data);
?>
Try using json_last_error function.
And print out Your post as a string:
print_r($_POST);
echo '<br /> json_last_error: '.json_last_error();
This way You will see what You got and what potentially had gone wrong.
For testing this kind of things I suggest Postman chrome extension.
You aren't sending a JSON object at all.
You are passing jQuery an object, so it will serialise it using standard form encoding.
<?php
header('Content-Type: application/json');
echo json_encode($_POST["news_data"]);
?>
If you want to actually send a JSON text, then you need to:
Set the content type of the request
Encode the data as JSON and pass it as a string to data
See this answer for an example.
To read the JSON, you would then need to read from STDIN and not $_POST as per this answer/
You can read properties of objects directly in $POST var, like this:
$_POST['news_data'] and $_POST['news_date']
You can check the post vars through the developer tools of the browser, in network tab.
The dataType property of the $.post options specifies the format of data you expect to receive from the server as a response, not the format of the data you send to the server. If you send data by the method POST - just like you do, if you use $.post - there is no need to call $aRequest = json_decode($_POST); on the serverside. The data will be available as a plain PHP array.
If you just want to get the news_data field as a response from the server, your serverside script should look something like this:
<?php
header('Content-Type: application/json');
$post = $_POST;
echo json_encode($post['news_data']);
?>
Notice, that you should check for the key news_data whether it is set.
Is it possible to read request header and thereafter fetch the variable value (say of example user id) in the jquery mobile + javascript code? If yes any example?
I found this article. How to get read data from response header in jquery/javascript, but not sure how it would work.
use this :
getAllResponseHeaders()
more detail here
Or this:
getResponseHeader()
more detail here
$.ajax({
type: 'POST',
url:'url', //the request url
data: {}, //any param that you want to send in the request
success: function(data){ //'data' is the response
alert(request.getResponseHeader());
}
error: function () {
alert("failed");
}
});
If you want request headers from this page you can get them via php getallheaders and display them as javascript array.
<script>
var headers = <?php echo json_encode(getallheaders()); ?>;
</script>
I am trying to access an external url which returns json data and based on one of the value in that data I need to hide a table row. I have tried several options to do this with jsonp, jquery and ajax but nothing seem to work. YQL is working for me but I can't use outer Service as the code need to be independent. Please someone let me know how I can make this work with javascript
This is one approach I have tried
<script type='text/javascript'>
function checkBlueLight() {
$('#trBlueLight').hide();
$.getJSON('http://.../Lights/getBlueLight?callback=?', function (data) {
if (data.expDate != null) {
$('#trBlueLight').show();
} else {
$('#trBlueLight').hide();
}
});
}
</script>
This is another approach I have tried. same issue unauthorized - 401
$.ajax({
url: 'http://.../Lights/getBlueLight',
dataType: 'json',
success: function(data) {
if (data.expDate != null) {
$('#trBlueLight').show();
} else {
$('#trBlueLight').hide();
}
}
});
I have even tried to get data from url using jsp with and that also causing some permission issue
Do you control the external url? Because you can do:
On your local page:
function your_function(data) {
alert(data.message)
}
And then on http://www.include.me/remote.php (or whatever is returning JSON) you would have it return
your_function({message: "it works!"});
And then back on your local page:
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://www.include.me/remote.php");
document.getElementsByTagName("head")[0].appendChild(script);
Which will then include the script, which simply tells it to run your already defined function with the data it provides.
If you can't control the external URL, and it doesn't support CORS nor JSONP, then you best option is to write a server side proxy method for the service. So on your server, you expose a new endpoint on your own host that on the server side access the real service on your clients behalf, and returns the result to your client.
For using jsonp, the server should bind the return type with a callback function. If it not, you cannot get the data from server.
If you are using cors, server should support that. Which means server should set,
"Access-Control-Allow-Origin" header to "*"
The issue with JS or jQuery is that crossdomain data may not be possible depending on the browser or server or a combination of both that prohibits the data exchange. This is security policy on many browsers and servers.
The best and safest choice is using a combination of JS or jQuery (Ajax call) with PHP cURL where the cURL will make the call requesting the data xml/json format and then sent back to the Ajax request.
Please take a look at the following example:
In the JS/JQuery AJax script:
$.ajax({
url: 'php_script_with_cURL.php',
dataType: 'json',
data:'THE_DATA_OR_REQUEST',
type:'post',
success: function(data) {
if (data.expDate != null) {
$('#trBlueLight').show();
} else {
$('#trBlueLight').hide();
}
}
});
and then in the php file (must be in the same server as your JS):
(you can use url string or post to request the data)
//USE POST IF YOU NEED TO SEND VARIOUS COMMANDS TO GET THE DATA BACK
$post = $_POST;
//INIT THE CURL CALL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
//this will tell the server how to return the data format
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
//use the query string if require, if not just remove it
CURLOPT_URL => 'http://THE_URL_HERE.COM?request_value=some_value',
//use the post only if yo need to post values
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
value1 => $post['value1'],
value2 => $post['value2']
)
//alternative you can also pass the whole POST array
//CURLOPT_POSTFIELDS => $post
));
$data = curl_exec($curl);
if(!$data){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
curl_close($curl);
//echo the data that will be sent to the JS/JQuery Ajax call
echo $data;
//or if you need to do more processing with php
//$response = json_decode($data);
Hope this helps :)
Happy coding !
I have a function in my controller:
function getAllExpense()
{ $date=$this->frenchToEnglish_date($this->input->post('date'));
$id_user=$this->session->userdata('id_user');
$where=array('date'=>$date, 'id_user'=>$id_user);
$allExpenses=$this->expenses_model->get_all('depenses',$where);
return json_encode($allExpenses);
}
In the view, I need to do an ajax_call to getAllExpense, but I need also to retrieve the result returned by getAllExpense in case of success(and I can't do this). Here is my view
function searchExpense()
{
var date= $('#dateSearch').val();
$.ajax({
type:'POST',
url : '<?php echo site_url()."/public/expenses/getAllExpense/"; ?>',
data :'date='+date,
success:function(data)
{ $('#searchExpense').toggle();
}
});
}
and finally the form :
<div id="searchExpense" class="toogle_form" style="display:none">
<label><strong>Vos depenses :</strong></label>
<?php
if (isset($allExpenses) && ! empty($allExpenses))
{
foreach ($allExpenses as $expense)
{
echo $expense['id_depense'] ;
echo ' ';
echo $expense['commentaire'];
echo '</br>';
}
}
else
{
echo 'Vous n\'avez pas eu de depenses pour cette date';
}
?>
</div>
This does not show anything on the browser.
I can't use the method of sending data by loading the view in getAllExpense because I already load it in the function index.
Could anyone help me please?
In your controller function getAllExpense, try echoing your json data with a header rather than using return:
Change this:
return json_encode($allExpenses);
to:
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($allExpenses);
The url:
Reading it backwards I understand getAllExpense to be your function name and expenses to be your controller name... What is /public/?
The data:
Currently you're using data :'date='+date. This is incorrect. $.ajax expects an object as the data parameter. Use data: {date: date}.
Where's the dataType?
If you're expecting json from the server, tell $.ajax this so it can parse the response properly. Use: dataType: 'json'
Your success function
It helps for debugging to call console.log() on the returned data. Inside the callback use: console.log(data); Then, open up your web tools. If you're using Chrome press ctrl+shift+j and inspect the console tab when firing your AJAX request. If you head over to the network tab and click on the most recent request (at the bottom) you can view the HTTP response as well.
"and finally the form :"
You didn't include a form.
Isolate the problem:
You're much better off inspecting the AJAX response using Chrome's Network tab as I've mentioned, but you could also isolate the issue to a client one or server one by changing your function temporarily to:
function getAllExpense(){
//$date=$this->frenchToEnglish_date($this->input->post('date'));
$date = "12/21/2012"; /*or whatever your date format is.*/
$id_user=$this->session->userdata('id_user');
$where=array('date'=>$date, 'id_user'=>$id_user);
$allExpenses=$this->expenses_model->get_all('depenses',$where);
//return json_encode($allExpenses);
echo json_encode($allExpenses);
}
And calling getAllExpense directly in the URL bar. You'll be able to see the raw json and determine if it's in a format you're happy with.