ajax - jquery - xml - webservice - web-services

I am trying to access the method GetWeatherByPlaceName from the service http://www.webservicex.net/weatherforecast.asmx. In my "data" attribute included city name as "newyork" but it is not showing any result. Please let me know if it is correct way of representing method name in the url.
$(document).ready(function(){
$.ajax({
type:"POST",
url:"www.webservicex.net/weatherforecast.asmx/GetWeatherByPlaceName",
data:"newyork",
contentType:"text/xml; charset=utf-8",
dataType:"xml",
success:function(msg){
$('span').html(msg);
}
});
});

I'm not sure if it will help, but the service should either receive an url encoded parameters string or a soap formated message.
So, i think you should replace your call by
$(document).ready(function(){
$.ajax({
type:"POST",
url:"www.webservicex.net/weatherforecast.asmx/GetWeatherByPlaceName",
data:"PlaceName=newyork",
dataType:"xml",
success:function(msg){
$('span').html(msg);
}
});
});

Related

Lucee ColdFusion.Ajax.submitForm

I'm converting a site from ColdFusion to Lucee (for the first time). In ColdFusion, after using the cfajaximport tag, I can run JS code similar to this:
ColdFusion.Ajax.submitForm('runMe', 'runCode.cfm', callback_testMe, errorHandler_testMe);
I seem to be unable to run this in Lucee. I'm looking for some kind of Lucee alternative, but can't seem to find anything.
Basically, I'm wanting to submit form data, run some server side stuff, then return the results without refreshing the page.
Any help would be greatly appreciated.
Lucee does not have CF UI tags, you're going to have to do this with jQuery AJAX or similar.
var formID = "runMe"; // formId Param
$("#"+formID).on("submit", function (e) {
e.preventDefault(); // Prevent page load
$.ajax({
type: "POST", // httpMethod Param
url: "runCode.cfm", // URL Param
data: $(this).serialize(),
success: function (data) {
console.log(data); // callbackhandler
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError); // errorHandler
}
});
})
This should do exactly the same thing and I even pointed out the similar params from ColdFusion.Ajax.submitForm

Coldfusion <cfsavecontent> variable displays correctly on page but does not save correctly to the DB

I have AJAX writing a result to <span id="response"></span>, which displays as expected. But, I need to convert to a CF variable so I can write the content to the database. Using
<cfsavecontent variable="JSONResponse"><span id="response"></span></cfsavecontent>
allows me to display the new JSONResponse variable on the page correctly, but when I take the same varible and write it to the database, it writes the <span id="response"></span> tag into the table - not the actual content. Does anyone have any suggestions? Thanks
Thanks #GSR & #Dan - I managed to work out a solution by forwarding on to a CFM page that writes to the DB, via another nested ajax post, based upon the response:
var postData = {username: "user#company.com", password: "Ruu3992032!883jj22uje"};
var ajaxResponse = $.ajax({
type: "post",
url: "https://api.company.com/v1/authenticate",
contentType: "application/json",
data: JSON.stringify( postData )
})
// When the response comes back, forward on to another cfm page with insert statement.
ajaxResponse.then(
function( apiResponse ){
$.ajax({
type: "post",
url: "WriteToDB.cfm",
data: jQuery.param({ payload: JSON.stringify( apiResponse ) }) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
})
}
);

Display JSON response text from ajax in jQuery Template

I need to pass the response from ajax call to a jquery template.The response json is not malformed.I have checked this by using alert statements in the ajax fn.When the response is passed to the template,it does not get recognized.For example,when I use ${field1} in template,nothing gets displayed in the browser.No error messages are displayed at the browser.Can someone help me fix this issue?
Json response from server:
{
"field1": 23432434,
"field2": "sometext",
}
Ajax fn:
function getinfo(uri)
{
jQuery.ajax({
url: 'http://{{request.META.SERVER_NAME}}'+uri,
success: function(info) {
return info;
},
async: false,
dataType: 'jsonp'
});
}
Template:
<script id="infoTemplate" type="text/x-jQuery-tmpl">
<div>${field1}</div>
</script>
Code to Bind JSON to template:
<script id="Template1" type="text/x-jQuery-tmpl">
{{tmpl(getinfo(uri)) "#infoTemplate"}}
</script>
Note: I can't use the following method to bind JSON with template.That's a long story.
function getinfo(uri)
{
$.getJSON('http://{{request.META.SERVER_NAME}}'+uri, function(data) {
$("#infoTemplate").tmpl(data).appendTo("#somedivid");
});
}
That's not how callbacks work. You're returning info to the callback function, and not to getinfo.
You either have to do something like you proposed after, or keep the result from the ajax call in a global var and call the tmpl function after while, to be sure that you have already got the answer from the ajax call. The first way is the way to go.

Get JSON data with jQuery from a .NET service: confused with ajax setup

I've just spent six hours trying to get this straight in my head and I haven't succeeded.
There's a HelloWorld .NET 3.5 web service on my local machine. Set up as required.
The service returns a List of custom structures.
I'm trying to consume it with jQuery 1.4.4.
When I try to do what the documentation says, I always get back an XML response from the service, which either causes parseerror in jQuery or gets passed as a dumb string to the success function. That is, however I combine dataType and accepts (which, according to the documentation, control how the received data is handled), I get an XML back.
But, when I do something that does not logically follow from the documentation, I successfully get my array of objects. That is, when I ignore dataType and accepts, and set contentType: "application/json; charset=utf-8" instead, it works fine. But contentType, according to the docs, control the data being sent to the server, not received.
In code:
$.ajax(
{
type: "GET",
url: "http://localhost:52624/Service1.asmx/HelloWorld",
dataType: "json",
//accepts can be anything, or it can be missing, doesn't matter, only depends on dataType
success: function(data, textStatus, jqXHR) {...},
error: function(jqXHR, textStatus, errorThrown) {...}
}
)
Result: error handler called, textStatus = parseerror.
$.ajax(
{
type: "GET",
url: "http://localhost:52624/Service1.asmx/HelloWorld",
dataType: "application/json",
//accepts can be anything, or it can be missing, doesn't matter, only depends on dataType
success: function(data, textStatus, jqXHR) {...},
error: function(jqXHR, textStatus, errorThrown) {...}
}
)
Result: Web service returns XML, it's passed to the success handler as string.
$.ajax(
{
type: "GET",
url: "http://localhost:52624/Service1.asmx/HelloWorld",
accepts: "json", // or "application/json"
success: function(data, textStatus, jqXHR) {...},
error: function(jqXHR, textStatus, errorThrown) {...}
}
)
Result: Web service returns XML, it's parsed and passed as IXMLDOMDocument2.
$.ajax(
{
type: "GET",
url: "http://localhost:52624/Service1.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {...},
error: function(jqXHR, textStatus, errorThrown) {...}
}
)
Result: Web service returns JSON, which gets partially parsed by jQuery (numbers and strings are parsed into properties of objects, but dates remain in the form of "/Date(1303003305724)/").
Questions:
Do I understand jQuery specs at all? Why is the parameter that is said to control sent data in fact controls received data?
What am I doing blatantly wrong?
What's the last step to get dates parsed by jQuery, too?
Looks like I'm going to answer that myself.
I'm not saying the following is the absolute truth. Rather, it is what I have found to be working.
First of all, I found three articles that explained a lot:
Using jQuery to Consume ASP.NET JSON Web Services
ASMX ScriptService mistake – Invalid JSON primitive
3 mistakes to avoid when using jQuery with ASP.NET AJAX
In short, the problem with .NET web services is that you have to call them in a special way:
Using a POST request (but see below), and
Providing Content-Type of application/json; charset=utf-8
This is by design and for security reasons.
The latter may not be avoided, you must provide that content type. And because content type does dictate how parameters are encoded in the request, you must encode your parameters in JSON.
This is where jQuery jumps in. For no reason jQuery would ignore contentType and encode your parameters in application/x-www-form-urlencoded. At which point the web service will dislike you for saying "here is JSON" and providing form-encoded stuff instead.
In these articles, the author recommends that you play a trick with jQuery by enclosing your JSON data in another pair of quotes so that it's interpreted as a string and doesn't get fiddled with by jQuery:
$.ajax({
type: "POST",
url: "ServiceName.asmx/WebMethodName",
data: "{'fname':'dave','lname':'ward'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {...}
});
This does work indeed.
Also, if you don't have any data, you still must provide an empty JSON object, {}, because if you don't, jQuery will not set Content-Length, and without Content-Length the web service will dislike you again (more security reasons).
However.
Since FW 3.5, it is possible to use GET with JSON-enabled .NET services. At which point you might wonder how JSON-encoded parameters align with GET requests. Here's how.
If your web service doesn't have any parameters, the call is simple:
$.ajax(
{
type: "GET",
url: "ServiceName.asmx/WebMethodName",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, jqXHR) {...}
}
);
And if there are parameters, then the call is also simple. What you have to do is provide additional quotes around parameters that should have them! This is because you want these quotes to appear as part of the form-encoded request. This way the form-encoded request will look sort of like json-encoded one:
$.ajax(
{
type: "GET",
url: "ServiceName.asmx/WebMethodName",
contentType: "application/json; charset=utf-8",
data: {DatePlaced:'"2011-05-13"'},
dataType: "json",
success: function(data, textStatus, jqXHR) {...}
}
);
This request will result in a request that looks similar to:
GET /ServiceName.asmx/WebMethodName?DatePlaced="2011-05-13" HTTP/1.1
Content-Type: application/json; charset=utf-8
Note the quotes that are required for JSON-like GET requests, but cause an error if you meant to ask for XML.
when posting to asp.net web services you always have to set the content type to that - it's their way of preventing json hijacking.
About the dates the easiest solution would be to return the dates as strings dealing date types on the client side will be a huge PITA (from my experience at least).
I think you don't understand the jQuery specs: (Specs)
dataType
Default: Intelligent
Guess (xml, json, script, or html)
The type of data that you're expecting
back from the server. If none is
specified, jQuery will try to infer it
based on the MIME type of the response...
Now. Look at your various cases.
Case 1: dataType: "json".
You receive "xml" but declare "json" => you get a parseerror because you can't parse xml as if it was json.
Case 2: dataType: "application/json".
"application/json" is NOT a valid data type, so jQuery defaults to string.
Case 3: No dataType.
jQuery makes its best guess, which turns out fine in your case.
Case 4: contentType: "application/json; charset=utf-8"
You ask for json data, and you don't specify the dataType. In this case you are lucky the Webservice does return json data, and jQuery guesses correctly that the data are in json format.
About the date formating, you want to look at:
How do I format a Microsoft JSON date?

elusive jQuery JSON Parser error

I have a an ajax call returning JSON to a loop to populate form fields. The raw data looks fine, but it never makes it though the loop and into the form, and an "Uncaught SyntaxError: Unexpected token :" error is thrown at line 1 of the document.
This is the ajax function:
$(function() {
$('#id_license' ).blur( function() {
q = $( '#id_license' ).val();
$.ajax({
datatype: 'json',
type: "POST",
data: 'lic='+q,
url: "/usr/xhr_license_search/?xhr",
success: function(data)
{ $.each(data, function(field, value){
$("#id_"+field).val(value);
});
console.log(data);
}
});
});
});
This is the raw JSON returned:
(manually anonymized)
{"First_Name":"Jon","Last_Name":"Doe","address":"2 A st.","city":"anthtown","grade":"T5","licNum":"08933","state":"TA","user":1099,"zipCode":09117}
I'm using json.dump() in Django to format the response.
Thank you in advance for your incites.
I've had this problem quite a few times before, it's something to do with the return dataType. By using $.get or $.post instead of $.ajax I've been able to solve the problem, so for you:
$.post('/usr/xhr_license_search/?xhr', 'lic='+q, function(data){
$.each(data, function(field, value){
$("#id_"+field).val(value);
});
}, 'json');
Doing that should give you no error.
I'm pretty sure JSON will be confused by the leading 0 in the zipCode; that shouldn't parse as a number, according to json.org . Are you sure you didn't intend that to be a string?
Try adding a pair of parentheses around the raw json, which makes it like
({"First_Name":"Jon","Last_Name":"Doe","address":"2 A st.","city":"anthtown","grade":"T5","licNum":"08933","state":"TA","user":1099,"zipCode":09117})