I'm trying to get JSON string from an URL:
http://megarkarsa.com/gpsjson.php
The URL echoes JSON location value to be shown as string, with this result for example:
{"BMS":[{"id":"PR01","type":"prajurit","lat":"-6.253310","long":"107.156219"},{"id":"PR02","type":"prajurit","lat":"-6.224084","long":"106.653069"},{"id":"PR03","type":"kendaraan","lat":"-6.244316","long":"106.649734"}]}
I need to get this string from javascript, so i can parse it later with JSON.parse(string).
I have tried to use getJson, but seems it can't be done since it's not real Json value, but string.
How can i do that? Every suggestion will be appreciated.
Why not just jQuery ?
$.get('http://megarkarsa.com/gpsjson.php',function(data){
console.log(data);
},'json');
or use php :
<?php
$json=file_get_contents('http://megarkarsa.com/gpsjson.php');
$json=json_decode($json,true);
?>
if you already did all and still not working, try :
$.get('http://megarkarsa.com/gpsjson.php',function(data){
data = eval ("(" + data + ")");
console.log(data);
});
The last solution is dangerous, use it if you trust the API you working with
As Michael Antonio pointed out, using Ajax would be the way to do it. Heres my code
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function() {
$.ajax({
url: 'http://megarkarsa.com/gpsjson.php',
type: 'GET',
dataType: 'html',
success: function(data, status, xhr)
{
$("#json").html(data);
},
error: function(xhr, status, error)
{
$("#json").html("Error: " + status + " " + error);
}
});
});
</script>
</head>
<body>
<div id="json"></div>
</body>
</html>
However, an error keeps cropping up. Here are the request/response headers, notice the response is force closing the connection.
Request
Host: megarkarsa.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://testsites.kalebklein.com/json1/json.html
Origin: http://testsites.kalebklein.com
Connection: keep-alive
Response
Connection: close
Content-Type: text/html
Date: Mon, 21 Sep 2015 01:52:56 GMT
Server: Apache
Transfer-Encoding: chunked
x-powered-by: PHP/5.4.36
Also notice that the content-type of the response is HTML, and should be JSON if you wish to parse the JSON using the above Ajax function I provided. The error coming back is not helpful whatsoever, meaning that the connection is being cut off or refused by making the Ajax call, and no data is being sent back.
You can do this as well :
str='{"BMS":[{"id":"PR01","type":"prajurit","lat":"-6.253310","long":"107.156219"},{"id":"PR02","type":"prajurit","lat":"-6.224084","long":"106.653069"},{"id":"PR03","type":"kendaraan","lat":"-6.244316","long":"106.649734"}]}'; //example string
obj=jQuery.parseJSON( (str)); //parse as json
$.each(obj, function (i, item) { //loop through each item in main obj
$.each(item, function (i, y) { loop through each prop in item
alert(y.id) //you can access the values like this others can be accessed via the dot notation such as y. prajurit
});
});
Related
I'm trying to write a submit form that sends a JSON object to an application on another server but I keep getting a 405 Method Not Allowed error in the console.
The app is set up to accept POST and that's what I'm sending so I'm lost at where the error is. There is also a warning in the console Loading failed for the <script> with source "Request URL"
Is this a problem with the way the application is reading the JSON or the format the JSON is being sent in?
From the app server
Failed to execute: javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type
Code
json = JSON.parse(string);
$.ajax({
type: 'POST',
dataType: "jsonp",
contentType: "application/json",
url: "http://test:8080/request/committee",
data: json,
cache: false,
success: function (response) {
$("#successModal").modal('show');
},
failure: function (response) {
$("#failureModal").modal('show');
},
error: function (response) {
$("#failureModal").modal('show');
}
});
e.preventDefault();//prevents the form from being submitted by default
Request Headers
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Host: test:8080
Referer: http://www.form.com/servlet/rsvp.jsp?location=110%20Road%20Bolton%20Landing,%20NY&purpose=%20TPAS%20Teleconference%20(RSVP%20here%20to%20attend%20in-person)&visitDate=2018-03-15&visitStartTime=6:00%20AM&visitEndDate=7:00%20AM&committee=all
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0
Response Headers
HTTP/1.1 405 Method Not Allowed
Allow: POST, OPTIONS
Connection: keep-alive
Content-Length: 0
Date: Mon, 16 Apr 2018 15:38:24 GMT
Edit: corrected contentType. Same error occurs
From your exception details , it seems to be
Failed to execute: javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type
either you are passing invalid content type or not passing at all , I see your content type is application/jsonp.
just give a try with application/javascript.
This error happened to me once. My java method wanted xml not json. this annotation (in java) fixed it for me.
#Consumes(MediaType.APPLICATION_JSON)
I hope this helps!
I have a text input box, within a SPA built on AngularJS, for users to add a title to a printout. The input box is declared like this:
<input class="chart-title" type="text" ng-model="chartTitle" ng-change="titleChanged()"/>
The text box is filled with a default title provided by the server. A user may change the title to whatever suits them. When the title is changed, the server is updated and sends back a new title in the header of the response which then replaces the title in the box. This works perfectly for standard ASCII type characters.
However, for unicode characters (for example àßéçøö) it does not work. The text is sent down correctly, updated on the server correctly, and returned to the SPA correctly. The headers for the request/response are here:
Request URL:http://blahblahblah/api/.....&chartTitle=Instrument:%20%C3%A0%C3%9F%C3%A9%C3%A7%C3%B8%C3%B6
Response Headers:
chartTitle: Instrument: %C3%A0%C3%9F%C3%A9%C3%A7%C3%B8%C3%B6
The request is made using AngularJS $http(). As you can see the values match up (the space in the request codes out as %20 for obvious reasons). However, when I retrieve the header, using headers("charttitle"), the value I receive is Instrument: à Ãéçøö
The javascript bundle is declared in the index with charset utf-8:
<script src="/js/bundle.js" type="text/javascript" charset="UTF-8"></script>
In addition the html is declared with the correct charset, it seems to me in two places within the head declaration:
<meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
<meta charset="utf-8" />
According to this website (http://www.i18nqa.com/debug/utf8-debug.html) it appears that I am getting Windows1252 character encoding. This does not make any sense. I could, if absolutely necessary, write a horrible hack converting the utf-8 string to Windows1252 characters, but this seems a little extreme and quite error prone to me.
The effect is the same, whether on Chrome, Firefox or IE11. The full request headers are here:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Host:blahblahblah
Origin:http://blahblahblah
Referer:http://blahblahblah/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Is there anything I have left out? Anything that has been forgotten?
EDIT
Full response headers as requested.
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:chartTitle
Cache-Control:private
chartTitle:Instrument: %C3%A0%C3%9F%C3%A9%C3%A7%C3%B8%C3%B6
Content-Disposition:attachment; filename=PrintData.pdf
Content-Length:1391643
Content-Type:application/octet-stream
Date:Fri, 20 Jan 2017 11:19:07 GMT
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcR2l0XEVPU1xSZXZpZXdlci5XZWJcYXBpXFByaW50XGQyOTNkNjA4NWVlYzlhNTEwYjQ5YThmZGQxNjNhMjAwMWZhYTFjMGY5YzhiMzUxYzE5ZjYxYWMwYTY1OWVhMDM=?=
Code around the headers
$http({
method: 'GET',
url: filePath,
params: {
fileName: fileName
},
responseType: 'arraybuffer',
headers: {'Content-Type' : 'application/json; charset=UTF-8'}
}).success(function (data, status, headers) {
ready();
if (status == 200) {
var chartTitle = headers("charttitle");
var printoutInformation = {'chartTitle' : chartTitle, 'pdfData' : data};
deferred.resolve(printoutInformation);
}
else {
deferred.resolve(null);
}
}).error(function (data) {
ready();
console.log(data);
});
return deferred.promise;
EDIT
The web.config for the api also specifies utf-8:
<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
TL;DR
In a text box I want to display "Instrument àßéçøö" and instead I am seeing "Instrument: à Ãéçøö"
Here is your issue solved.
Based on this source,
UTF-8 character debugging and its encoding and decoding
The response you are getting is the actual charecter of the encoded utf-8 string
So, you need to decode that inorder to get your result.
HEre is the code to do it.
decoded = decodeURIComponent('%C3%A0%C3%9F%C3%A9%C3%A7%C3%B8%C3%B6')
console.log(decoded);
The result is => "àßéçøö"
we have to do this to get the actual string instead of UTF-8
So, from your response you got,à Ãéçøö
decodeURIComponent(escape("à Ãéçøö")) => "àßéçøö"
DEFINITION:
decodeURIComponent():
A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component.
So , here is your method.
if (status == 200) {
var original = headers("charttitle");
var chartTitle = decodeURIComponent(escape(original));
console.log(chartTitle);
var printoutInformation = {'chartTitle' : chartTitle, 'pdfData' : data};
deferred.resolve(printoutInformation);
}
Now, you will get the headers same as you send.
Try below for encoding
myAngApp1=document.getElementById("ItemSearch");
var uri = myAngApp1.value;
var place = encodeURIComponent(uri)
I am using AJAX to post some array data to the server. I get the following expected results in the Firebug network console from the Ajax request.
POST -----> http://example.com/drag_data.php
//request header
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://example.com/drag.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 90
Cookie: PHPSESSID=b1lr9he4l2hbcnlkcsebfq2134
Connection: keep-alive
//data in the request body
item[]=1&item[]=3&item[]=2&item[]=4&item[]=5
//firebug params
item[]:"1"
item[]:"3"
item[]:"2"
item[]:"4"
item[]:"5"
for infor this is the ajax call which give the expected success message (same as the firebug param output)
$.post({
data: data,
type: 'POST',
url: 'drag_data.php?',
success:function(result){
$(".result").html(data);},
error: function(){
console.log(arguments);
}
});
I just want to echo the posted data in the drag_data.php script. I have tried the following test code (as well as (print_r and var_dump) but cannot see any posted data which has baffled me. Can anyone tell me what I am doing wrong please?
drag_data.php test file
$i = 0;
//this loop is failing to echo the posted array data from the Ajax request
foreach ($_POST['item'] as $value) {
echo "each".$value;
$i++;
}
?>
Make url: '/drag_data.php', with preceding slash and without ?.
Maybe serializing will help: make data: JSON.stringify(data) on client and json_decode on server.
Check configurations of your server - are requests you're seeing in your firebug actually reaching the server?
Finally cracked it. Turns out that there was a server side issue with Ajax calls that has now been resolved by the service provider. So in actual fact my original code works as it should. Maybe this thread or the code will be useful for someone else in the future.
I have a promblem trying to learn and build an angularjs application. I just can't get the form data saved to mysql...
I have spent hours trying everything and it just won't work.
The PHP-file inputs empty queries to the mysql table when using the variable. If I use static info it works fine.
Thanks :)
app.controller('addMsgCtrl', function ($scope, $http) {
$scope.fill = function(add) {
var data = {
addItem: $scope.addItem
};
$http.post("msinput.php",{'data' : $scope.addItem})
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
};
});
$data = json_decode(file_get_contents("php://input"));
$addItem = mysql_real_escape_string($data->addItem);
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("stran189_taskma") or die(mysql_error());
mysql_query("INSERT INTO message (addItem) VALUES ('$addItem')");
Print "Your information has been successfully added to the database.";
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form class="add-task" id="newTaskForm" ng-controller="addMsgCtrl" novalidate ng-submit="fill()">
<div class="form-actions">
<div class="input-group">
<input ng-model="addItem" class="form-control" type="text" name="addItem" placeholder="Ny anteckning" />
<div class="input-group-btn"><button class="btn btn-default" type="submit">
<i class="glyphicon glyphicon-plus"></i></button>
</div>
</div>
</div>
</form>
RESPONSES
JS: "Inserted successfully!"
NET: "POST 200 OK msinput.php"
Request headers: "Host: (myUrl)
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:44.0) Gecko/20100101 Firefox/44.0
Accept: application/json, text/plain, /
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: (myUrl)
Content-Type: application/json;charset=utf-8
Content-Length: 2
Connection: keep-alive"
respond-headers:
Connection: Keep-Alive
Content-Length: 62
Content-Type: text/html
Date: Mon, 07 Dec 2015 21:36:53 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.10 (Unix) OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4
Vary: User-Agent
X-Powered-By: PHP/5.4.37
I am a bit confused by your controller code, but it seems to me, that you prepare the var data to be send to the server. If this is true you have to $http.post("msinput.php", {'data': $scope.data}) ...
Inside your fill() log data. See if anythign is in there. The change this
$http.post("msinput.php",{'data' : $scope.addItem})
to this
$http.post("msinput.php",{'data' : data})
Then check your Network XHR and see if data is being sent correctly to the server.
Also to get more info on what the server is saying back you can also use this method and log the error:
// Simple GET request example:
$http({
method: 'POST',
url: 'msinput.php'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
First make sure your data is present:
Open Firebug in Firefox, choose the console tab
Navigate to your form in Firefox, fill in the the form and submit it.
The last line in the console should show:
POST http://..../msinput.php
click this and look at the POST & JSON tabs, it will show all your input data for each field. Anything missing obviously wont get to your db.
Once you know your data is leaving, then you can figure out why its not arriving.
I also strongly suggest you change to PDO and stop using mysql functions has it is now deprecated.
Ok, so now you know the data in your form is leaving thru your post action.
Inside your msinput.php do the following
var_dump( file_get_contents(http://input) );
See what comes back in the firebug console.
Trying to make a call and retrieve a very simple, one line, JSON file.
$(document).ready(function() {
jQuery.ajax({
type: 'GET',
url: 'http://wncrunners.com/admin/colors.json' ,
dataType: 'jsonp',
success: function(data) {
alert('success');
}
});
});//end document.ready
Here's the RAW Request:
GET http://wncrunners.com/admin/colors.json?callback=jQuery16406345664265099913_1319854793396&_=1319854793399 HTTP/1.1
Host: wncrunners.com
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2
Accept: */*
Referer: http://localhost:8888/jquery/Test.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Here's the RAW Response:
HTTP/1.1 200 OK
Date: Sat, 29 Oct 2011 02:21:24 GMT
Server: Apache/1.3.33 (Unix) mod_ssl/2.8.22 OpenSSL/0.9.7d SE/0.5.3
Last-Modified: Fri, 28 Oct 2011 17:48:47 GMT
ETag: "166a2402-10-4eaaeaff"
Accept-Ranges: bytes
Content-Length: 16
Content-Type: text/plain
Connection: close
{"red" : "#f00"}
The JSON is coming back in the response (red : #f00), but Chrome reports Uncaught SyntaxError: Unexpected token : colors.json:1
If I navigate directly to url itself, the JSON is returned and is displayed in the browser.
If I paste the contents of colors.json into JSLINT, the json validates.
Any ideas why I can't get this error and I never make it to the success callback?
EDIT - the jQuery.ajax() call above runs perfect at jsfiddle.net, and returns the alert 'success' as expected.
EDIT 2 - this URL works fine 'http://api.wunderground.com/api/8ac447ee36aa2505/geolookup/conditions/q/IA/Cedar_Rapids.json' I noticed that it returned as TYPE: text/javascript and Chrome did not throw the Unexpected Token. I've tested several other url's and the ONLY one that does not throw the Unexptected Token is the wunderground that is returned as TYPE: text/javascript.
Streams returned as text/plain and application/json are not being parsed correctly.
You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399 part to the URL (you can see this in your dump of the request).
What you're returning is JSON, not JSONP. Your response looks like
{"red" : "#f00"}
and jQuery is expecting something like this:
jQuery16406345664265099913_1319854793396({"red" : "#f00"})
If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json needs to be able to actually return a JSONP response.
If the same origin policy isn't an issue for your application, then you just need to fix the dataType in your jQuery.ajax call to be json instead of jsonp.
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows:
1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ].
2- add a script link to it just below the normal jQuery link.
3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({
crossOrigin: true,
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",
type : "GET",
success:function(data){
console.log(data);
}
})
I had the same problem and the solution was to encapsulate the json inside this function
jsonp(
.... your json ...
)
That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character