Cannot see js in mvc page using Firebug - json

I have a separate js file where I put my js. I can't even get into the js to debug it to see what the problem is.
Firebug prior to this page has inline js I can see (from my master page (_Layout.cshtml).
Once I get into this page, I get this from Firebug:
No Javascript on this page
If tags have a "type" attribute, it should equal "text/javascript" or "application/javascript". Also scripts must be parsable (syntactically correct).
I don't know what I'm missing to simply fill this dropdownlist.....
Here is my new js file with the contents:
$(document).ready(function () {
GetCategories();
});
function GetCategories() {
$.ajax({
type: "POST",
url: "Index/Category",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var listItems = "";
for (var i = 0; i < data.length; i++) {
listItems += "<option value='" + data.CategoryID + "'>" + data.Description + "</option>";
}
$("#Categories").html(listItems);
}
});
}
Here is the content of the html page. Note that my html is in my masterpage. So, I just need a simple script here...
<div title="JSON callback for dropdownlist">
<table>
<tr>
<td>
<select id="Categories">
</select>
</td>
</tr>
</table>
</div>
<script type="text/javascript" src="../../Scripts/JSON_DDL.js"></script>
Here is my result:
[{"CategoryID":1,"Description":"ECommerce","Projects":[]},{"CategoryID":2,"Description":"Medical","Projects":[]}]

I've had similar problems in the past with Firebug.
One course of action is that Firebug has crashed and is not reading properly, close and reopen the brower. It's not as common a problem as it used to be, but it does happen.
The second problem took me a long time to find when it happened to me... and it sent me crazy for a couple of hours - but the solution was very simple - sometimes if your JavaScript syntax is bad (e.g. missing a closing curly brace) it won't be read and the browser won't even display an error. Double check your code carefully.

Related

Why doesn't src work for templates?

The HTML script tag can be used to define named templates:
<script type="text/html" id="Lookup">
<label class="field-title" data-bind="text: Metadata.FieldTitle, css: { hasError: !IsValid() }"></label>
<div data-bind="html: Metadata.FieldIntro"></div>
<select class="form-control" data-bind="attr: { id: 'ff' + Metadata.FormFieldID }, options: Lookup, optionsText: 'Caption', optionsValue: 'Id', optionsCaption: Metadata.FieldIntro || 'Select an item...', value: Value, css: { hasError: !IsValid() }"></select>
</script>
According to MDN and msdn, I should be able to move the content of a template into a file and reference it like this:
<script type="text/html" id="Lookup" src="Lookup.html"></script>
According to Fiddler template files are being loaded (I have several). What stops knockout from using the templates when they aren't inline, and is there anything that can be done about it?
From the comments, script tags don't parse what they load into the DOM. I could use something like jQuery ajax to load, parse and inject but knockout uses the script node's id to reference the template, so the next question is how to make visible the fragment so loaded.
At a stab I surmise that I need to do something like this:
$(document.body)
.append("<div id='Lookup' style='display:none'></div>")
.load("Templates/Lookup.html" );
Close, but no cigar. Here it is corrected and wrapped up as a function:
function loadTemplate(name) {
if (name)
switch (name.constructor) {
case String:
$(document.body).append("<div id='" + name + "' style='display:none'></div>");
$("#" + name).load("Templates/" + name + ".html");
break;
case Array:
name.map(loadTemplate);
break;
default:
throw "Must be a string or an array of strings";
}
}
You can pass a single template name or an array of names.
Knockout happily uses the template.
Browsers don't know how to process programs written in text/html (yes, that sentence doesn't make a whole lot of sense, this is a hack you are using).
Whatever JavaScript you are using to process the templates is reading the childnodes of the script element in the DOM. It hasn't been written to check for a src attribute and load external content.

HTML from ajax request console logs as object

I am requesting some HTML content via an API using jQuery ajax. The data I get back console logs as an object, even when I parse it with jQuery.
Here is what I am doing
$.ajax({
url: ajaxUrl,
success: function(data){
var html = data
var parseData = $(html);
console.log(parseData);
}
});
I have tried dataType it made no difference. I have tried to find elements within the data return, but that returns the same.
The data I am returning does not have a doctype, html or body tag.
<div class="item">
<h2>Title</h2>
<p>...</p>
</div>
<div class="item">
<h2>Title</h2>
<p>...</p>
</div>
<div class="item">
<h2>Title</h2>
<p>...</p>
</div>
Am I doing something wrong, or is the data being returned wrong?
EDIT
Here is the console log
This is absolutely correct that you get an object in your console.
By default jQuery tries to guess the type of the content (what they call an "intelligent guess") and in your case it probably thinks this is HTML. Probably - because you did not provide us with an example of the thing you are asking.
After jQuery thinks this is HTML, it wraps it into a jQuery object, which I guess you see in your console.
Try to call console.log(data.find(".item").length) - I have a feeling the result will be 3.
To get the pure HTML you must use a dataType: "text". This will stop jQuery from attempts of parsing the data and will give you the raw string result.
Try the below
$.ajax({
url: ajaxUrl,
dataType: "html"
})
.done(function( html ) {
console.log( html );
});

ajax form submit with mootools

I have a site that I built way back in 2007.. I had done some ajax stuff, and it worked fine.. Today, that site owner contacted me and said he noticed the forms were no longer working.
I went to take a look and the console showed that upon submitting it was getting an error:
Refused to set unsafe header "Connection"
I assumed this had to be a change in browser security or something, since no code had changed and everything worked fine last time I looked at it.... So I did some googling and found some others mention this, and their solution was to update mootools.. I did, and what a headache, the entire API had changed.. So I fixed everything, and it seemed like it should all work, but it didn't.
$('application_form').addEvent('submit', function(e) {
new DOMEvent(e).stop();
updateText("Sending...");
var progress_bar = $('bar');
progress_bar.empty().addClass('ajax-loading');
this.send({
update: progress_bar,
onSuccess: function(e) {
progress_bar.removeClass('ajax-loading');
(function() { mySlide.slideOut() }).delay(1500);
}
});
});
This results in an ajax request going to the url [Object object], rather than the actual .php script specified in the application_form's action attribute... I tried specifying a url option to tell it not to go to [Object object] but no good...
Here's a jsfiddle with a working example based on yours.
It shouldn't be too hard to upgrade yours.
http://jsfiddle.net/K976E/3/
Here's the html code in case the jsfiddle gets gone.
<!DOCTYPE HTML>
<html>
<body>
<form id='application_form' action='http://www.scoobydoo.com/cgi-bin/scoobysnack'>
Count of Scooby Snacks: <input type='text' size='5' /><br />
<input id='submitButton' type='submit' value='Rut Roh Shaggy!'/>
</form>
<div id='bar' style='margin-top:20px'>
Yikes!
</div>
</body>
</html>
And here's the javascript (place in onLoad):
new Form.Request('application_form', 'bar', {
onSend: function(){
updateText("Sending...");
var progress_bar = $('bar');
progress_bar.empty().addClass('ajax-loading');
$('submitButton').set('value', 'Sending the form...').set('disabled', true);
},
onComplete: function(){
var progress_bar = $('bar');
progress_bar.removeClass('ajax-loading');
//(function() { mySlide.slideOut() }).delay(1500);
}
});
function updateText(txt){
// do something here...
}
... and no, I didn't re-enabled the submit button within the onComplete...

Prevent Ajax.BeginForm from HTML encoding output

#using (Ajax.BeginForm("Create", "Comment",
new AjaxOptions
{
UpdateTargetId = "newComment",
OnSuccess = "function() { alert('finished " + ViewData.Model.Id + "'); }",
}))
{
...
}
outputs the following markup:
<form action="/Comment/Create" data-ajax="true" data-ajax-mode="replace"
data-ajax-success="function() { alert('finished 34'); }"
data-ajax-update="#newComment34" id="form1" method="post">
As you can see, it has HTML encoded my javascript. How do I prevent this?
EDIT: I have multiple AJAX forms on my page so the onsuccess function needs to know which one called it. In my code, you can see I am trying to pass state to this function. If OnSuccess can only take a function name (and not state), then how can I achieve this?
Personally I would use a standard Html.BeginForm helper with HTML5 data-* attributes that I will AJAXify myself:
#using (Html.BeginForm(
"Create",
"Comment",
FormMethod.Post,
new { data_id = Model.Id }
))
{
...
}
which outputs:
<form action="/Comment/Create" data-id="some id here" method="post">
...
</form>
and then in a separate javascript file I would subscribe for the .submit event:
$(function() {
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataId: $(this).data('id'), // <- pass the data-id HTML5 attribute
success: handleSuccess
});
return false;
});
});
function handleSuccess(result) {
$('#newComment').html(result);
// fetch the data-id of the form that trigerred the AJAX request
var id = this.dataId;
// TODO: do something with this id
}
I prefer this technique compared to the Ajax.* helpers as it gives me all the control I might need. Another advantage is that we get a clear separation between script and markup making the code nice and tidy.
Don't.
The HTML encoding is correct behavior, and the attribute value (as seen from Javascript code) will not be encoded.
I believe that It's because MVC interprets the OnSuccess (and other vars) as the name of a Javascript function and not a bit of Script.
Make a helper function that performs the script you want to act on the submit.

PHP/JQuery/AJAX, few teething problems

Morning/Afternoon guys.
Writing some JQuery AJAX shizz and getting a bit stuck. I've got the actual proccess of calling the php file done perfectly, its just trying to get the html on the page to change in a way I want it to. I want to get rid of the a with the id of the one used in the ajax call etc, and replace it with the html passed from the PHP file. Code is as follows...
$(".save_places").click(function() {
$.ajax({
url: "{/literal}{$sRootPath}{literal}system/ajax/fan_bus.php",
type: "POST",
data: ({id : this.getAttribute('id')}),
dataType: "html",
success: function(msg){
$(this).before(msg);
$(this).empty();
alert(msg);
}
});
return false;
});
And the HTML is pretty simple;
<p class="links">
<img src="{$sThemePath}images/save_places.png" alt="Save to My Places" />
<img src="{$sThemePath}images/send_friend.png" alt="Send to a Friend" />
</p>
All the stuff in the success function is experimental mashing of code, any help please?
Thanks as always.
I think what you're after is .replaceWith(), like this:
$(this).replaceWith(msg);
This replaces the <a></a> with the content coming back in msg.
Also, if you're sure the elements have IDs, you can just do this:
data: {id : this.id},
linksPara.replaceChild(newElements, oldAtag);