ajax method and SyntaxError : Unexpected token ":" - javascript

I'm in trouble with a simple script. I need to parse some xml response from a webservice
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function callws() {
$.ajax(function(){
type:"GET",
contentType: 'text/xml',
dataType:"xml",
url:"http://thewebservice/service.action?my=parameter",
timeout:4000,
async:false,
success: parseXml,
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.textStatus);
}
}); // ajax
function parseXml(xml) {
$(xml).find("result").each(function(){
$("#risposta").append($(this).find("row").text() + "<br />");
});//each
} //function parse
} // termine callws
I don't understand why nothing work! I've only an error log from Chrome console
SyntaxError : Unexpected token ":" at line 12 (contentType: 'text/xml',)
I try to use other parameters but all the rows below the first (type:"GET") seems wrong... imho the syntax is ok in all of the script!
Advices?
Vito

I think you have the ajax syntax wrong. The first parameter is a regular ole' object, not a function. Try this:
function callws() {
$.ajax({
type:"GET",
contentType: 'text/xml',
dataType:"xml",
url:"http://thewebservice/service.action?my=parameter",
timeout:4000,
async:false,
success: parseXml,
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.textStatus);
}
}); // ajax
// termine callws
^ All I did was take out function()

$.ajax(function(){
supposed to be
$.ajax({

Related

jQuery.html() result, not interpreted as HTML by the browser

After a successful ajax call, I want to print the result on screen (in a DIV).
This result is a piece of HTML code.
$.ajax({
url: window.location.pathname + '/feedback-campaigns',
type: 'GET',
contentType: 'text/html',
success: function(data, textStatus, jqXHR) {
var result = data.campaigns.campaigns[0].text;
// result = "<b>TEST - do you see me?</b>"
$('.campaign-top-product-detail-page').html(result);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('NOK');
}
});
But, on screen I see this:
<b>TEST - do you see me?</b>
instead of the text in bold.
Use following
$.ajax({
url: window.location.protocol + '//' + window.location.host + window.location.pathname + '/feedback-campaigns',
type: 'GET',
contentType: 'text/html',
success: function(data, textStatus, jqXHR) {
var result = $.parseHTML(data.campaigns.campaigns[0].text); // result = "<b>TEST - do you see me?</b>"
$('.campaign-top-product-detail-page').html(result);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('NOK');
}
});
Update: write like this $.parseHTML(data.campaigns.campaigns[0].text);
It is because the response from server contains HTML entities, not actual HTML tags. To solve this, simply send the HTML such as <b>TEST - do you see me?</b>. (If you're using PHP on your server, then don't use htmlspecialchars on the output).
Remember that things like &lt will be not regarded as a part of HTML code but some character. So if you want to show the text which is bold, you should let it return as below
<b>TEST - do you see me?</b>
However, if you don't have permission to edit the result, other answers are good.

How to make a REST call using jquery's $ajax call?

I am using the answer given on this question.
As a result, my html page looks like this:
<!DOCTYPE html>
<html>
<head>
<script src="path\jquery-2.1.1"></script>
<script>
function myFunction() {
alert('Clicked!');
$.ajax({
url: "http://localhost:51399/api/webapi",
type: 'GET',
success: function (data) {
alert(data.error);
$('#demo').html(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>
When I click the button nothing happens. I am not sure if the ajax call is ever made or if there is no success on the callback. What am I missing and how can I fix it so that the GET REST call goes through to the URL I specified?
P.S.: I am a beginner at javascript and jquery.
Maybe try:
$.ajax({
url: "http://blockchain.info/latestblock",
type: 'GET',
success: function(data) {
$('#demo').html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("error: " + errorThrown + " || status: " + textStatus + " || data: " + jqXHR);
}
});
or (the more modern way):
function myFunction(){
$.ajax({
url: "http://blockchain.info/latestblock",
type: 'GET'
});
}
function handleData(data) {
$('#demo').html(data);
}
function handleError(jqXHR, textStatus, errorThrown) {
console.log("error: " + errorThrown + " || status: " + textStatus + " || data: " + jqXHR);
}
myFunction().fail(handleError)
myFunction().done(handleData);
Wold's answer above is completely valid. However, the issue with my code was that I was trying to reference the jquery.js file using its absolute path which is prohibited. Once I made the path relative (and added the extension...stupid me) the call went through.

jquery ajax function with json

Hi i am using this code to get contents from a json file but i am not able to show results
my code is
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
alert(data);
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
In google chrome i can see that the request status is 200 and data is loaded. here is the link from which i am copying code The Link.... Any help!!!!
Thanks
Your code doesn't work because the http://50.116.19.49/rest/user.json resource return a JSON response instead of JSONP (difference).
So you can't make cross-domain calls via ajax BUT you can create a some proxy script ON YOUR SERVER which will make it for you. Example:
cross-domain-call.php
<?php echo file_get_contents('http://50.116.19.49/rest/user.json');?>
And change your script to
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1/cross-domain-call.php',
dataType: 'json',
timeout: 50000,
success: function(data, status){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
});
Since you don't seem to have access to remote webservice to convert it to JSONP, here is a solution using Yahoo's YQL as a proxy. YQL will retrieve file contents from any remote site and return as xml or jsonp.
Working DEmo http://jsfiddle.net/Uh8cz/2/
You will notice the response object has additional properties created by YQL
var yqlBaseUrl = 'http://query.yahooapis.com/v1/public/yql?q=';
var restUrl = 'http://50.116.19.49/rest/user.json';
var yqlQuery = 'select * from json where url="' + restUrl + '" ';
var yqlFormat = 'format=json'
var jQueryCallback = '?'
var fullQueryUrl = yqlBaseUrl + yqlQuery + '&' + yqlFormat + '&' + jQueryCallback;
$.getJSON(fullQueryUrl, function(json) {
var jsonString = JSON.stringify(json.query.results.json.json, null, ' ')
$('body').append('<h1>Response</h1><pre>' + jsonString)
}) ​
If you can control the content of "user.json", wrap it around a function:
user.json content:
execute_jsonp({you_json)
your javascript:
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
data(); //execute the function that is sent
},
error: function(){
output.text('There was an error loading the data.');
}
});
function execute_jsonp(json){ //recreate the function so you may access the json as a parameter
alert(json);
}
});
Hope this helps ;)

Cross site HTTP authentication in JQuery

I want to see if it is possible to log into a third site that uses HTTP authentication. Ideally, the browser will store the credentials. Unfortunately this fails every time. Any help would be much appreciated, I'm using the base64 Jquery plugin, which I've tested to work.
So, two questions:
How can I view the HTTP status code?
Will this ultimately work, in principle?
<script>
$("#login_button").click(function() {
var username = 'myFunUsername';
var password = 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + $.base64.encode(username + ":" + password));
},
success: function(data) { $("#label").text("Logged in, yay!"); }
}).fail(function(){ $("#label").text("It didn't work"); });
});
Thanks!!
var user= 'myFunUsername';
var pwd= 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
crossDomain:true,
username :user,// Keep the variable name different from parameter name to avoid confusion
password:pwd,
xhrFields: { /* YOUR XHR PARAMETERS HERE */}
beforeSend: function(xhr) {
// Set your headers
},
success: function(data, textStatus, xhr) {
alert(xhr.status);// The status code
//Code for success
}
}).fail(function(){
//Fail code here
});
For more details on parameters refer to http://api.jquery.com/jQuery.ajax/

$.ajax URL inquiry

Will toDistance.php ran after calling this function? It seems like toDistance.php is not called. Thanks
function myAjax(volunteerDist, jid){
$.ajax({
type:'POST',
url: 'toDistance.php',
data : ({
distance:volunteerDist,
id:jid
}),
success: function(){
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});
Did you tried out by taking arguments on your success function? Try this code.
function myAjax(volunteerDist, jid){
$.ajax({
type:'POST',
url: 'toDistance.php',
success: function( data ){
///CHECK UR UPCOMING DATA
alert(data.jid);
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});
Will toDistance.php ran after calling this function?
If the data parameter is what the server expecting to get, Yes.
Use firebug, check what is going on with your request and stop guessing...
It seems OK. Try to track web traffic with FIddler and check if the script is called and the arguments.
If you're debbuging with Safari, Chrome or Firefox you can record the traffic.
Check for POST variables, script location etc.

Categories