I'm trying to execute a cross domain request for data from a wordpress blog using YQL. This is the code from my first attempt:
var g = {data:""}
function getWP() {
var targeturl = "http://www.mysite.com";
var url = "http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(targeturl)+
"%22&format=xml'&callback=?";
var successfunc = function(data) {
if(data.results[0]){
g.data = data.results[o];
} else {
var errormsg = '<p>Error: could not load the page.</p>';
alert(errormsg);
}
}
$.ajax({
url: url,
success: successfunc
});
}
When I tried this ajax call, the data object returned was an empty string. However, when I did this:
$.getJSON(url, successfunc);
the proper JSON object was returned. What is the difference between the two calls? And more importantly, why did only the second one work?
The difference is that you are not specifying your data type or content type
Add
$.ajax({
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: successfunc
});
to your ajax call
$.getJSON() uses data type json while the $.ajax() doesn't. If you want to use standard $.ajax() you'll have to specify datatype explicitly. For cross-domail calls use datatype jsonp instead of json. But I think YQL works with json as well.
Related
I'm trying to capture a list of filters in an ajax request, but although I can capture a single filter, when I try to capture a list, I just get an empty list for some reason.
Below is the relevant part of my view and the ajax (jQuery) function. When I try and send a single filter with $.ajax({ .... 'filters': fixed }) this works but fails with a list.
Update: trying data: {'filters': JSON.stringify([fixed])}, does pass the data through as a string to django '["fixed"]' (which I can handle if I don't use getlist but .get and then json.loads() but I think there must be a simpler method here.
def quotes_results_filter_view(request):
results_filters = request.GET.getlist('filters') or []
quotes_results = request.session['quotes_results']
for results_filter in results_filters:
.......
Ajax function:
$(document).ready(function () {
$('#id_filter').change(function (e) {
var fixed = $(this).val()
console.log(fixed)
$.ajax({
url: '/users/filters/',
data: {
'filters': [fixed]
},
dataType: 'json',
success: function (data) {
console.log(data)
}
})
When you send a list through jQuery it changes the keyword to
so in Django you probably have to get like this:
request.GET.getlist('filters[]')
Ok this one should be easy for someone who knows this sort of thing better. I am going to limit the scope of the code I provide because this works in one variation (fiddler).
This problem is simple to explain: I have a method in WCF that takes a string as a parameter. The method expects a request with a wrapped body style. If I create a simple object in fiddler and send it over it works. Something like {"submission":"something"}. If I do this in via ajax in JSON it does not work. I get a bad request error saying it is not allowed... this is cross domain but this is not the problem, I add the appropriate headers in the method to handle this. In this case the method is never being called (it is like it is an issue with the signature).
Here is the thing though... if I make a really simple class with one property of a string and pass in an object it works fine. Passing objects in a wrapped body style work fine. Trying to do this with a "primitive type" such as a string does not... any ideas?
THIS DOES NOT WORK (but does work via fiddler)....
var datain = new Object();
datain.submission = "mysubmission";
var dataToSend2 = JSON.stringify(datain);
$.ajax({
type: "POST",
url: "http://localhost:8000/ServiceModelSamples/Service/rest/Reflect",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend2,
success: function (item) {
debugger;
alert(item);
},
error: function (xhr) {
debugger;
alert(xhr);
}
});
WITH THIS CONTRACT....
[OperationContract]
[WebInvoke(Method = "*",
RequestFormat = WebMessageFormat.Json,
BodyStyle=WebMessageBodyStyle.WrappedRequest)]
string Reflect(String submission);
THIS DOES WORK....
var spec = new Object();
spec.submission = "mysubmission";
var dataToSend3 = '{"thespecial":' + JSON.stringify(spec) + '}';
$.ajax({
type: "POST",
url: "http://localhost:8000/ServiceModelSamples/Service/rest/Reflecting",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend3,
success: function (item) {
debugger;
alert(item);
},
error: function (xhr) {
debugger;
alert(xhr);
}
});
WITH THIS CONTRACT...
[OperationContract]
[WebInvoke(Method = "*",
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string Reflecting(Special thespecial);
Yes, you can't send the primitive data types without wrapping in xml.
you can check the complete request structure after enabling the help in endpoint behavior
suppose you have endpoint name "api" for webHttpBinding then you can enable the help using following
< webHttp helpEnabled = "true " />
After configuring it you can see the help as follow
http://localhost:<port>/test.svc/api/help
This will show the actual request format.
Like to pass string you can use the following format wrapper
<string xmlns="http://schemas.microsoft.com/2003/10/
Serialization/">Hello World</string>
or you can use stream input parameter
Click here to implement streaming
var p = JSON.stringify(parameter);
console.log(p);
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: p,
success: function(status) {
console.log(status);
}
});
console.log(p) shows {"o_fname":"hh","o_lname":"jkhk","o_email":"uifh#bjvh.com","o_phone":"","b_name":"bmnbmbm,b","b_address":"","b_city":"","b_postal":"","b_phone":""}
but in my http://abc.com/ajax.php page print_r($_POST) is giving me an empty array Array()
var p = JSON.stringify(parameter);
That is your problem.
When you pass string data to .ajax, it sends it “as-is” – but PHP only popuplates $_POST if it receives data encoded as application/x-www-form-urlencoded.
So don’t make your data into a string, but pass your parameter object directly as value for data – then jQuery will take care of sending it the right way, so that PHP understands what it is supposed to do with it.
I think park of the problem may be that in data: you're passing the parameter details, but to the function on the other side of the jQuery you're passing a parameter name and nothing else.
Try:
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: {parametername:p},
success: function(status) {
console.log(status);
}
});
With parametername replaced with the parameter name ajax.php is expecting.
Supposing I have the following code which returns a Javascript object which I can read in Firebug's console:
FB.api('/me',function(apiresponse){
console.log(apiresponse);
});
How can I then use the data from apiresponse in an Ajax request on the same page?
Currently my Ajax request looks as follows:
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
I know very little about Javascript, but reading around the subject leads me to think I have to convert the Javascript object to a JSON string. Is that correct? Am I on the right track?
You could put your AJAX call inside the handler for the API call like below..
FB.api('/me', function(apiresponse){
console.log(apiresponse);
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
});
one possible way:
define a global variable in your javascript, e.g. var myVar1;
set apireponse to the global variable in your FB.api callback (i.e. where u call console.log)
reference the var myVar1 in your ajax fcn.
How can I access the data returned from the xhrGet outside of the get itself? Firebug shows that the "json" object has an array called results, which stores the json Object from the response, but when I try to access it it is null. So: how do I access the received data on the last code line?
var json = dojo.xhrGet({
url :'/disease_web/graphMlDownload/getEdgeInformation/', handleAs:"json",content : { edgeid : edgeId, graphname:this._canvas.path},
load:function(response){
return response;
}
});
console.log(json.ioArgs);
console.log(json.results);
By default dojo.xhrGet is called asynchronously, so console.log(json.results) is null because it's run just after dojo.xhrGet, but before response comes from server.
var xhrGet = dojo.xhrGet({
url: "/some_rul",
handleAs: "json",
handle: function(response) {
console.info(2,'response',response);
console.info(3,'xhrGet.results[0]',xhrGet.results[0]);
}
});
console.info(1,xhrGet.hasOwnProperty('results'));
The result is:
1 false
2 response - ['some data from server']
3 xhrGet.results[0] - same data as in 'response' accessed via xhrGet
The simplest way to access your retrieved JSON data is to assign it to a document-level variable within the xhrGet load function:
var fetchedData = null;
function parseResponse() { /* do something meaningful */ }
dojo.xhrGet({
url: "{{dataUrl}}dojo/LICENSE",
handleAs: "json",
preventCache: true,
load: function(response){
// save for later
window.fetchedData = response;
// do whatever processing we want with the returned data
parseResponse();
},
error: function(error){
alert("Couldn't fetch your data: " + error);
}
});
Yeah, no. I've since learned a much better way, and forgot to come back and fix this answer, so it deserves the downvotes it's accrued.
The proper way to deal with data fetched from dojo.xhrGet, jQuery.ajax, or any other asynchronous data fetch is to write a function to process its results, and pass it to xhrGet as the load argument, like so:
var request = dojo.xhrGet({ url :'/disease_web/graphMlDownload/getEdgeInformation/',
handleAs: "json",
content : {edgeid : edgeId, graphname:this._canvas.path},
load: doSomethingWithMyEdges
});
function doSomethingWithMyEdges(json_results) {
console.log(json_results);
}