getting error of pulling json from URL - javascript

I am getting error saying: SyntaxError: Unexpected token ':'. Parse error."
whether I do
url = 'http://api.openweathermap.org/v3/uvi/20,77/current.json?appid=c0d8761ca979157a45651a5c7f12a6be';
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
getJSONP(url, function(data){
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html><body>
or if I do :
url = 'http://api.openweathermap.org/v3/uvi/20,77/current.json?appid=c0d8761ca979157a45651a5c7f12a6be';
function CallURL() {
$.ajax({
url: url,
type: "GET",
dataType: "jsonp",
async: false,
success: function(msg) {
console.log(msg);
JsonpCallback(msg);
},
error: function() {
// ErrorFunction();
// break ;
}
});
}
function JsonpCallback(json) {
alert(json);
//document.getElementById('summary').innerHTML = json.result;
}
CallURL();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<body>
</body>
</html>

This url doesn't return JSONP, it's return JSON:
{"time":"2017-02-25T12:00:00Z","location":{"latitude":18.75,"longitude":76.75},"data":10.8}
OpeanWeather API support JSONP only for few calls, like http://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=c0d8761ca979157a45651a5c7f12a6be, other call support only JSON, XML or HTML (see https://openweathermap.org/current for details).
So use json in ajax type call:
url = 'http://api.openweathermap.org/v3/uvi/20,77/current.json?appid=c0d8761ca979157a45651a5c7f12a6be';
function CallURL() {
$.ajax({
url: url,
type: "GET",
dataType: "json",
async: false,
success: function(msg) {
console.log(msg);
},
error: function() {
// ErrorFunction();
// break ;
}
});
}
CallURL();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<body>
</body>
</html>

Related

How do I need to convert this to plain javascript or jquery?

I'm new to JavaScript and jQuery. I'm currenly having the following code in my javascript file, however it doesn't seem to be working. I'm using this from prototype.js :
var url = '/sip/TnsViewScreenResponse';
var myAjax = new Ajax.Request(url, {
method: "post",
headers:{
'X-Requested-By': 'XMLHttpRequest'
},
parameters: "tin=" + tin,
success: function transResult(response) {
document.getElementById('tinVersionsOf_' + tin).innerHTML
= response.responseText;
document.getElementById('ajax_loading_img').style.display
= 'none';
document.getElementById('tinVersionsOf_' + tin).style.display =
'block';
},
error: function transResult(response) {
document.getElementById('ajax_loading_img').style.display = 'none';
alert('Failure: Problem in fetching the Data');
},
}
);
return false;
This seems to be conflicting with the other jQuery files being used in the file, so I want to convert this to plain JavaScript or jQuery. I have tried the below but it doesn't seem to be working. How can I make this right ?
var url = '/sip/TnsViewScreenResponse';
var myAjax = $.ajax({
type: "POST",
url: url,
data: tin,
success: function transResult(response) {
$('#tinVersionsOf_' + tin).html(response.responseText);
$('ajax_loading_img').css("display","none") ;
$('#tinVersionsOf_' + tin).css("display","block");
},
error: function transResult(response) {
$('#ajax_loading_img').hide();
alert('Failure: Problem in fetching the Data');
},
}
});
The above code is getting skipped while being parsed in the browser, which I had checked with inspect element option in Google chrome.
Try This
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/sip/TnsViewScreenResponse",
data: JSON.stringify({ mydata: tin }),//where tin is ur data
success: function (result) {
//include your stuff
},
error:function(error)
{
// include your stuff
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

AJAX success and failure reporting

Trying to figure out how to report inside this popup only on failure. Currently this works, but it alerts for both success and failure:
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
alert(response);
console.log(response);
}
});
}
</script>
I have tried the following, but so far with no luck:
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
console.log(response);
},
error: function(response)
{
alert(response);
console.log(response);
}
});
}
</script>
Any help would be appreciated. Thanks!
* EDIT *
Here is the full code:
<?php
$static_password = "1234";
if(isset($_POST['data'])){
$submit_password = $_POST['data'];
if($submit_password == $static_password){
die("UNLOCK THE RECORD");
}
else{
die("SORRY WRONG PIN");
}
}
?>
<html>
<head>
<script src="js/jquery-3.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<h2>Simple AJAX PHP Example</h2>
UNLOCK
<p>Pin is "1234"</p>
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
alert(response);
console.log(response);
}
});
}
</script>
</body>
</html>
For the error callback to be executed, server must respond with status of 404, 500 (internal error), etc. When you write die('blah'); server responds with a status of 200, and the message that it died with. This is a successfull request as far as both AJAX and PHP are concerned.
You have to check the response
if($submit_password == $static_password){
die("UNLOCK THE RECORD");
}
then:
success: function(response)
{
if (response == 'UNLOCK THE RECORD') { /* success */ }
else { /* failure, do what you will */ }
}

Knockout bindings from a JSON

I'm new to knockout and trying to create my first script which update based on a JSO script which constantly change. The problem is i keep seem to get an unexpected error: Uncaught SyntaxError: Unexpected identifier.
<head>
<script type='text/javascript' src='knockout-3.3.0.js'></script>
<script type="text/javascript">
callService();
var Match = function(){
var self = this;
self.matches = ko.observableArray();
self.ajax = function (uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
error: function (jqXHR) {
console.log("ajax error " + jqXHR.status);
}
};
return $.ajax(request);
}
function callService(){
self.ajax(url + "matchticker.json" + requestData, 'GET').done(function (data) {
self.matches.removeAll();
for(int i = 0; i < data.Result.length; i++){
self.matches.push(..data..);
}
}
}
}
ko.applyBindings(new Match());
</script>
</head>
<body>
<ul class="list-group col-sm-12 col-xs-12" data-bind='foreach: matches'>
<li data-bind="html: match_id"></li>
</ul>
</body>
Many syntax errors here. Next time try linting your code first.
See if it works:
var Match = function(){
var self = this;
self.matches = ko.observableArray();
self.ajax = function (uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
error: function (jqXHR) {
console.log("ajax error " + jqXHR.status);
}
};
return $.ajax(request);
};
function callService(){
self.ajax(url + "matchticker.json" + requestData, 'GET').done(function (data) {
self.matches.removeAll();
for(var i = 0; i < data.Result.length; i++){
self.matches.push(data.Result[i]);
}
});
}
callService();
};
ko.applyBindings(new Match());

SOAP Envelope error

Hi I am a newbie to jQuery , I was just testing a sample SOAP request with the following code , but I am getting error ,Is this because of the server side or the code I have written is wrong? , I mean the syntax .Can anybody help me to check it ?
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
alert("get ready");
var soapMessage ='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soapenv:Header>'+
'<a:Action xmlns:a="http://www.w3.org/2005/08/addressing" soapenv:mustUnderstand="1">'+
'http://xxx/xxxx/xxxx/accountSummary'+
'</a:Action>'+
'</soapenv:Header>'+
'<soapenv:Body xmlns:ws="http://xx.xx.xxx.com/">'+
'<ws:accountSummary/>'+
'</soapenv:Body>'+
'</soapenv:Envelope>';
var url = "http://127.0.0.1/xxx/xxx/xxx/xx?wsdl";
$.support.cors = true;
$.ajax({
type: "POST",
url: url,
crossDomain:true,
dataType: "xml",
processData: false,
contentType: "text/xml; charset=\"utf-8\"",
success: function (soapResponse) {
alert("success: " + soapResponse);
},
error: function (soapResponse) {
alert("Soap" + soapMessage);
alert("Failed: " + soapResponse);
}
});
});
});
</script>

jQuery Ajax callback was not called. ParserError

I've a function that calls jquery ajax to hit a restful service developed in C#. the code is as follow
function refreshUsage(macAdd)
{
alert(macAdd);
ajax = $.ajax({
type: "GET",
data: {'mac': '1'},
dataType: "jsonp",
jsonp:false,
async:false,
jsonpCallback:'blah',
crossDomain: true,
cache: false,
contentType: "application/json; charset=utf-8",
url: "http://localhost:20809/api/keyGen",
ajaxSuccess: function(data)
{
data = JSON.parse(data);
console.log("data _" +data);
},
error: function(xhr, status, error) {
if (status === 'parsererror') {
console.log("resptext__" + xhr.responseText)
}
console.log("status _" +status);
console.log("error _" +error);
},
complete: function(response)
{
console.log("response _" +response);
},
});
}
var blah = function (data) {
alert(data);
//do some stuff
}
when i hit this given url, it's sending response in browser window. but when im trying to get the response text in ajax function it's coming undefined even though success code is 200 and success text is success. I'm getting following errors and no response:
resptext__undefined
status _parsererror
error _Error: blah was not called
This is example. Try this:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
$('#twitterFeed').html(text);
}
});
})
</script>
</head>
<body>
<div id = 'twitterFeed'></div>
</body>
</html>
Example of ThatGuy will explain you.
for me I had to ensure that the server is responding as expected by the jsonp callback I had to edit the response from the my php server as below
$data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['callback'] . '('.json_encode($data).')';
if your server does not reply in the format like
dataWeGotViaJsonp({"statusCode":201})
you will be getting that error
hope this helps

Categories