dojo pass URL parameter into AJAX - ajax

I want to take URL parameter and pass to ajax function,
var queryParams = dojo.queryToObject(window.location.search.slice(1));
var data = dojo.toJson(queryParams, true);
console.log(data);
getCategory( data );
...
function getCategory(input){
dojo.xhrGet( {
// The following URL must match that used to test the server.
url: "http://js.localhost/dojo-release-1.5.0-src/json3.php",
handleAs: "json",
content: input,
on my URL parametetr, I pass in
?return_type=category&category_desc=Business2
when I view on firebug, the ajax request become ....
t?0=%7B&1=%0A&2=%09&3......
but data debug is correct, any idea what's wrong?
{ "return_type": "category",
"category_desc": "Business2" }

just found out that it doesn't need dojo.toJson
var queryParams = dojo.queryToObject(window.location.search.slice(1));
getCategory( queryParams );

Related

Ajax call results in 500 {internal server error}

I am trying to send json data through ajax call.
Following is the code I used. I'm using node.js as the backend. a_filters,b_filters,etc. are arrays. I googled the error but couldn't get the code to work.
var filters =
{
"a" : a_filters,
"b" : b_filters,
"c" : c_filters,
"d" : d_filters
};
$.ajax({
url : "query/get-filtered-data",
dataType : 'json',
async: "true",
data:JSON.stringify(filters),
contentType: 'application/json; charset=utf-8',
success : function(data){
},
failure: function(data){
alert('got an error');
}
});
EDIT : This is my server-side code.
var express = require('express');
var router = express.Router();
//the URL below is correct since it redirects from 'query/'
router.get('/get-filtered-data', function (req, res, next) {
console.log(req);
var filters = JSON.parse(req.body);
console.log("foo");
var a_filters = filters["a"];
var b_filters = filters["b"];
var c_filters = filters["c"];
var d_filters = filters["d"];
res.send(query);
});
conosle.log('foo') doesn't print anything.
console.log(req) has req.body empty.
Thanks a lot in advance.
Because you are referencing req.body, you need to use a router method that includes a body - post or put.
You may also need to include type: "POST" in your jQuery Ajax method.
There is a more general semantic question about whether you should use get with a query string to communicate parameters when retrieving data rather than using a request body, but that is an API design question rather than a cause of errors.

Relative URLs in AJAX requests in MVC application

I tried to make sense of the results I got (see ajax call below) in relation to this post:
Relative URLs in AJAX requests
The comments annotated with [WORKS and [FAILS] below show various URLs that worked and failed. Since the above post only talked about document based URLs, I tried to make the analogy that a method in a controller corresponds to a document and a controller to folder. However, the results below belie that analogy.
CAS is a MVC application which runs off the root of a website. Subject is a controller. Index, GetSubject and RegisterSubject are methods in the Subject controller.
Not all of these URLs should work. However, I cannot explain why one does another does not.
EDIT: UrlHelpers. I want to understand the rules. What are the rules for resolving a MVC type of url: http://[domain]/[MVC App]/[Controller]/[Method]/ [params] where params is like [p1/p2/ . . ].
I don't see the pattern. As noted below the document url = [http://localhost/cas/Subject/Index] when either method is called.
var ajaxService = (function () {
var ajaxGetJson = function (method, jsonIn, callback, errorCallback, controller) {
var ajaxUrl = getSvcUrl(method, controller);
var docUrl = document.URL; // at his point document url = http://localhost/cas/Subject/Index
//[WORKS] when ajaxUrl = ../GetSubject/359143 where 359143 is the id of Subject in database
// correctly resolves to http://localhost/cas/Subject/GetSubject/359143
//[FAILS] when ajaxUrl = ../RegisterSubject
// resolves to http://localhost/cas/RegisterSubject <-- notice Subject controller is missing.
//[FAILS] when ajaxUrl = /RegisterSubject --> resolves to http://localhost/RegisterSubject
//[WORKS] when ajaxUrl = "RegisterSubject" or "RegisterSubject/
// resovles to http://localhost/cas/Subject/RegisterSubject
//[FAILS] when ajaxURL = "GetSubject"/359143"
// resolves to http://localhost/cas/Subject/Index/GetSubject/359143
if (method === "RegisterSubject") { //workaround for the above failure
ajaxUrl = "http://localhost/cas/Subject/RegisterSubject";
}
$.ajax({
url: ajaxUrl, //getSvcUrl(method, controller),
type: "GET",
data: ko.toJSON(jsonIn),
dataType: "json",
contentType: "application/json",
success: function (json) {
callback(json);
},
error: function(json) {
errorCallback(json);
}});
}
// other AJAX types omitted
return {
ajaxGetJson: ajaxGetJson;
};
}

DOJO xhrGet how to use returned json object?

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);
}

Can't get $.ajax or $.get to work

I have this $.ajax (using jquery) code, it originally was the $.get that is now commented but for some reason I'm always getting the error and I can't find anything wrong with it =/, am I overlooking something?
$.fn.randomContent = function(options){
var contentArray = new Array();
var dType = "html";
var defaults = {
xmlPath: "../xml/client-quotes.xml",
nodeName: "quote"
};
var options = $.extend(defaults, options);
alert(options);
$.ajax({
type: "GET",
url: "../xml/client-quotes.xml",
dataType: "html",
success: function(){
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
},
error: function(){
alert("Something Went wrong");
}
});
/*$.get(defaults.xmlPath, function(){
alert("get");
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
}, type);//$.get*/
};
Here's the getRandom() function:
function getRandom() {
var num = contentArray.length
var randNum = Math.floor(Math.random()*num)
var content = "";
for(x in contentArray){
if(x==randNum){
content = contentArray[x];
}
};
alert(content);
return content;
}
It could be that the browser is caching your GET requests. In this case, either:
ensure the server is controlling your cache options (using cache-control settings of private or no-cache)
change the method of your AJAX call to POST instead of GET
differentiate your GET request by adding querystring parameters that change with each request
I prefer option #1, specifically because POST operations are intended to change something on the server, and so we should use that method when our actions do in fact modify server state. GET requests on the other hand, are requests that do nothing more than read data.
I feel a GET request is more appropriate for this task, and so in my own code I would prevent the caching of the response.
Does that url have to be absolute? I've never tried doing ajax requests with a "../" in it. Do you have FireBug installed? You could examine the response header from the sever.

Set ajax request in joomla using mootools

I am having a prob for ajax request in joomla using mootools.
var url = '<?php echo JURI::base();?>index.php?option=com_test&task=getselectmode&selectedid='+$('parent_question').value;
var params ={method: 'post',update:'test'};
var myAjax = new Ajax(url, params);
myAjax.request();
My prob is that, is there any to set onComplete event of the ajax request.
i have set it as below on above code but nothing happen.
onComplete: function(response) { alert('Response: ' + response); }
Can you please provide full code of how to use ajax using mootools 1.1 ??
Thanks in advance
just add the onComplete to the params object, no need to add the event seaprately. also, you can use this.response.text. it can all look a bit more compacted - depends on your preference. if you don't plan on reusing the object, just call it direct and don't assign it to a variable either:
new Ajax(url, {
method: "get",
update: $("someelement"),
onComplete: function() {
alert(this.response.text);
}
}).request();
if you do something with the response text, you may want to remove the update: bit. if you need to evaluate the response (as javascript), use evalResponse: true instead of eval(this.response.text);. also handy - evalScripts: true|false if you want to do something from the server side along with the response.
This should work:
var ajaxObj = new Ajax ('index.php?option=com_yourcomponent&view=yourview&format=raw', {
method: "get"
});
ajaxObj.addEvent('onComplete', function (data) {
// data is the response text
// use as desired
});
// this initiates the call
ajaxObj.request();
maybe:
var a = new Ajax( url, {
method: 'post',
data: { parfoto: foto },
onComplete: function( response ){
..........
}
}).request();

Resources