jQuery Ajax callback was not called. ParserError - javascript

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

Related

getting error of pulling json from URL

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>

Can't post variable to PHP using AJAX

I am trying to send a variable to PHP using JavaScript but I don't get any response whatsoever. Any ideas?
PHP/HTML:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="dashmenu.js"></script>
</head>
<body>
<?php
$selection = $_POST['selection'];
if($selection == 'profile'){
?>
<p> it works
<?php
}
?>
<button id="button"> profile </button>
</body>
JS file (dashmenu.js):
$('#button').click(function() {
var menuSelection = "profile";
$.ajax({
type: 'POST',
url: 'dashboard.php',
data: {selection: menuSelection},
success: function(response) {
alert('success');
}
});
});
In your html file (let's say index.html) you could have:
$('#button').click(function() {
var menuSelection = "profile";
$.ajax({
type: 'POST',
dataType: "html",
url: 'dashboard.php',
data: {selection: menuSelection},
success: function(response) {
alert(response);
},error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + errorThrown);
}
});
});
In your dashboard.php, you should ONLY have code that processes requests, and returns (echoes) the desired output:
<?php
$selection = $_POST['selection'];
if($selection == 'profile'){
echo "It works";
}else{
echo "It failed";
}
?>
$('#button').click(function() {
var menuSelection = "profile";
$.ajax({
type: 'POST',
url: 'dashboard.php',
data: {selection: menuSelection},
success: function(response) {
alert('success');
}
});
});
Run this in your console in your browser.
Right-click > Console tab.
If you want to check whether this function has successfully bind to the button. If your browser returns you 'success' alert, meaning you include it wrongly I guess.
If nothing happen when you click, please include .fail() in your $.ajax()
Which will look like this:
$.ajax({
type: 'POST',
url: 'dashboard.php',
data: {
selection: menuSelection
},
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
}
});

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>

cannot get REST response using $.ajax()

Below is my method
function getCurrentUserName()
{
$.ajax({
type: "GET",
url: "http://localhost:8099/rest/prototype/1/space/ds",
crossDomain:true,
dataType: "jsonp",
success: function(resp){
alert("Server said123:\n '" + resp.name + "'");
},
error:function(e){
alert("Error"+e)
}
});
});
}
I am calling this on a button click , I do not see any alert , when i type the url on the browser I get the response in xml .but i do not get the response in the script.
Can someone please help me with this ? Am i missing something here ?
Thanks :)
Looks like a JSON parse error.
Try with the json instead of jsonp
function getCurrentUserName()
{
$.ajax({
type: "GET",
url: "http://localhost:8099/rest/prototype/1/space/ds",
crossDomain:true,
dataType: "json",
success: function(resp){
alert("Server said123:\n '" + resp.name + "'");
},
error:function(e){
alert("Error"+e)
}
});
});
}

Using XML file content loaded via Ajax outside of success call

I have this code:
$.ajax({
url: "lang_files/" + window.localStorage.language + ".xml",
dataType: 'xml',
success: function(data) {
var xml_node = $("resources", data);
$("#index_intro").text(xml_node.find('string[name="index_intro"]').text());
},
error: function(data) {
console.log("Error loading XML data");
}
});
It works fine, the .text() is set properly using the information from my XML file, I now want to be able to use the XML file across my application, and not just inside the success call, so I did:
var xml_node;
$.ajax({
url: "lang_files/" + window.localStorage.language + ".xml",
dataType: 'xml',
success: function(data) {
xml_node = $("resources", data);
},
error: function(data) {
console.log("Error loading XML data");
}
});
$("#index_intro").text(xml_node.find('string[name="index_intro"]').text());
This is not working though, I would like to understand why.
This is because ajax is asynchronous so at time you call xml_node, it is still undefined. Try this instead:
$.ajax({
url: "lang_files/" + window.localStorage.language + ".xml",
dataType: 'xml',
success: function(data) {
setIndexIntro($("resources", data));
},
error: function(data) {
console.log("Error loading XML data");
}
});
function setIndexIntro(xml_node)
{
$("#index_intro").text(xml_node.find('string[name="index_intro"]').text());
}

Categories