pulling in html (json string) into javascript - ajax

i am trying to pull an html page into my javascript file, (essentaiily the webpage will consist of a JSON string) and then i would like to set that string to a js var for eval. i have tried the $.ajax method - currently to no avail.

jQuery.getJSON('my.json', function (obj) {
MyNS.Sub.doSomething(obj);
});

Related

How to attach html response (got from ajax request )with div tag in jquery?

Below is the code snippet which is hitting the url on server and getting the html response.I can see
the response inside firefox debugger but it does not display in div tag.
$.ajax({
url: url,
dataType: 'html',
data: '',
type: 'POST',
success: function(data) {
//in firefox debugger i can see complete html response inside data
$('#displayContent').html(data); // but here, it does not
// append the html inside div displayContent. Instead it makes
// the current page blank
}
});​
I don't get what mistake I'm making here Can I not directly assign the ajax html response to an selector(div tag in my case) with $('#displayContent').html(data)?
Instead of using html() method use append i.e.
$('#displayContent').append(data);
Or if you want to assign whole content direct to your element use load method
$(function(){
$('#displayContent').load(url);
});
If you've got a form tag on your page, and you're trying to submit it asynchronously with jQuery, your function will need to return false, to prevent the browser from handling the form.
Example:
$("form").submit(function () {
$.ajax(...);
return false;
});

JQuery UI Autocomplete not working in ASP.NET MVC

I am trying to implement an autocomplete in ASP.NET MVC 3, following this post
but I really can't get it to work. I have looked at a series of other posts and blogs, but no success so far.
I have a DB table which contains regions (in Japanese), like so:
1 ハイチ; 2 ドミニカ共和国; 3 南アフリカ
basically a [key, Name] pair.
In my repository I am doing the following call:
public IQueryable<Region> GetAllRegions()
{
return db.Regions;
}
Getting the raw data, which I pass to the controller, pair down the data according to input and the concatenate to a string like so:
public class RegionsController : Controller
{
Region_Repository rr = new Region_Repository();
public string FindRegions(string q)
{
List<string> regions = rr.GetAllRegions().Select(r => r.Name).Where(s => s.StartsWith(q)).ToList();
return string.Join("\n", regions);
}
}
The controller when accessed via server/Regions/FindRegions/?q=ハ return a page with the single entry "ハイチ" as expected.
On the page I have a textbox with id "#NewRegion" and the script
<script type="text/javascript">
$(document).ready(function () {
$("#NewRegion").autocomplete('#Url.Action("FindRegions", "Regions")');
})
</script>
which I placed underneath the textbox.
I have references to JQuery and JQueryUI from Google API which work since I am executing other JQuery and using the JQueryUI datepicker successfully on this page.
I tried placing the script in a separate file and hardcoding the url as '/Regions/FindRegions', but no change. I had a look in firebug (second day only, so not very proficient at using it yet) and the script doesn't seem to get executed.
The controller is called fine when accessed via URL, but anything I enter into the textbox does not get passed to the controller...
Can anybody see anything wrong with this?
According to the dark depths of the jQuery UI documentation, the parameter used when passing the autocomplete string to the server is called term, not q.
Update: And also, initialize with autocomplete({source: "#(...url...)"}).
Update 2: And also, return the type of data the Autocomplete widget expects, a JSON array of strings or a JSON array of objects.
I got it working in the following way. I changed the controller to return Json data like this:
public ActionResult FindRegions(string term)
{
var regionNames = rr.GetAllRegions().Select(r => r.Name).Where(s => s.Contains(term)).ToList();
return Json(regionNames, JsonRequestBehavior.AllowGet);
}
note: the AllowGet is there so I could check the result via url, so for debug only.
And the autocomplete script became:
$(function () {
$('#NewRegion').autocomplete({ source: '/Regions/FindRegions' } );
});
Now it works, but I am still not sure why.

How to get xml data using ajax in jquery?

I want to use ajax in jquery to get data for my page...
The problem is that the url which i call has some query strings to be sent along with it...
for example: the url which i call for getting data is:-
http://mysite.in.dataengine.aspx?t=abcde&token=h34jk3&f=xml
the data i get in response from this url can be in xml format or java script arrays(whichever i choose)
for eg...the xml wil look like this:-
<root version="1.0">
<Regions>
<Region SubCode="MWEST" RCode="west"/>
<Region SubCode="MCENT" RCode="north"/>
<Region SubCode="THAN" RCode="south"/>
</Regions>
</root>
and the javascript array would look like this :-
Region = new Array();
Region.push(new Array('MWEST', 'west'));
Region.push(new Array('MCENT', 'north' ));
Region.push(new Array('THAN', 'south'));
So when i get the data i want to store it in a drop down box.(using ajax)
Note I can get either xml OR javascript arrays as the returned data, not both together.
You can make an ajax call along with parameters like this:
var paramsData = "t=abcde&token=h34jk3";
$.ajax({
type: "GET",
url: "dataengine.aspx",
data: paramsData,
dataType: "xml",
success: function(xml){
//process xml from server
}
});
I would suggest you to get the data in JSON format, as Json comes natively to javascript and it much easliy manipulated using javascript as compared to XML. The easiest way i can see to work on your problem is to store all your data whether xml or json & put it inside a hidden div and then use jQuery to populate that data in a drop down box.
Here is an amazing jquery plugin with example that should ease your work
http://plugins.jquery.com/project/jqueryclientdb
Just parse it. I"m not sure if this will work, but it might:
xml = ...
region = new Array();
$(xml).find('Region').each(function() {
region.push(new Array($(this).attr('SubCode'), $(this).attr('RCode'));
});
Thanks for your help guys...but i have found the solution....Like i said...that i get in return either xml or javascript array...So..i'm using javascript arrays.. and using a function in jquery*($.getScript)* which fetches an external javascript code via ajax...Thus i am getting all my data now through ajax in jquery...

jQuery 1.5.2 displays [object XMLDocument] for empty responses

I have a Url from which I can get a string
If the response string contains something, everything goes well, but (god forbid!) if the result would be an empty string like "" jQuery 1.5.2 will display it as [object XMLDocument]
follow the codes plz :
$.post('/Applicant/RequestedJob/IsThereActivePeriod',{},
function(data){
if(data == '' )
{
//do something here!
}
else
{
console.log(data.toString());
// [object XMLDocument] will be printed in console.
}
});
Perhaps I should mention that it used to work perfectly on jQuery 1.4.4
any idea?
Regards :)
You should set the expected dataType of the response in your ajax call, like this:
$.post('/Applicant/RequestedJob/IsThereActivePeriod',{},
function(data){
if(data == '' )
openDialog('/Applicant/RequestedJob/AddRequestedJobWindow','pnlRequestedJob','Request Window');
else
{
msgbox.show(data.toString(),'Error', msgBoxButtons.okOnly);
console.log(data.toString());
}
},
'html'
);
Without this, jQuery tries to infer the response type, according to this:
Default: Intelligent Guess (xml, json,
script, or html).
With no returned content, it's apparently guessing XML. By passing it 'html' as the dataType, you force jQuery to interpret the response as HTML, and store the result in plain text.
As per some of the comments, an appropriate content-type header should allow jQuery to infer that your empty string is HTML, achieving the same result without setting the expected dataType explicitly in the ajax call.
The reason you get [object XMLDocument] is because data is an XML document object, and its toString() is being called.

What do browsers want for the Content-Type header on json ajax responses?

I am returning some json which needs to be handled by javascript as the response to an XMLHTTPRequest.
If I set the response's content type to "text/plain", all browsers but Chrome will accept it and pass it to my JS with no problem. However, Chrome will wrap the response in
<pre style="word-wrap: break-word; white-space: pre-wrap;">
before passing it to my javascript.
If I set the response's content type to the "proper" "application/json" all browsers but Firefox will accept it and pass it to my JS with no problem. Firefox, however will ask to save or open the response as a file.
What's the correct, cross-browser Content-Type?
You may solve the issue by parsing the response into the JSON object by using jQuery funcion parseJSON - http://api.jquery.com/jQuery.parseJSON/
The parameter you pass into the function is the JSON object string, which you extract from the response data:
function AjaxResponse (data) { // AJAX post callback
var jsonResult = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));
}
Tested (besides Chrome which problem this solves) in FF and IE8 for the following simple JSON result, for other browsers and more complex responses no guarantees...
NOTE: the content type in this case is text/plain or text/html I think - I've used the following ASP.Net MVC function to return the result
ContentResult System.Web.Mvc.Controller.Content(string content);
Where I returned the JSON object like
System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer
= new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonResponse = jsonSerializer.Serialize(
new { IArticleMediaId = 0
, ImageUrl = Url.Content(fullImgPath)
});
return Content(jsonResponse);
In ajaxFileUpload.js in uploadCallback() replace
io.contentWindow.document.body.innerHTML.innerHTML
with
$(io.contentWindow.document.body.innerHTML).html()

Resources