Ajax function that works in Firefox but not in IE 6 - ajax

i have a Ajax function that works in Firefox but not in IE 6
my ajax script :
<script type="text/javascript">
function actualiserDLIS(){
var url = 'administration/gestionUtilisateurs.do?method=actualisationDLIs';
var params = 'DR='+encodeURIComponent(document.getElementById('selectDR').value);
var myAjax = new Ajax.Request(
url,
{ method: 'post',
parameters: params,
onComplete: majDLIS
});
}
function majDLIS(retour){
if (retour.status == 200)
{
alert("Retour Status: "+retour.responseText);
document.getElementById('tableDLI').innerHTML = retour.responseText;
}else{
document.getElementById('tableDLI').innerHTML = "uncool";
}
}
</script>
in my <body>
[...]
<table class="tabForm" id="tableDLI">
<c:forEach var="DLI" items="${sessionScope['fiscalite.AdministrationGestionUtilisateurForm'].DLISUtilisateur}" varStatus="status" >
<tr>
<td class="label_tableau_type1 width200px" ><c:out value="${DLI.code}"/>
</td>
<td class="width150px" colspan="3"><html:checkbox property="DLI(${status.count-1})"/>
</td>
</tr>
</c:forEach>
</table>
[...]
in my alertI'm recovering well my data that I want to display in my tableDLI

Apparently you're using Prototype. First I must mention that targeting IE6 is wrong, worse, it's evil. It's well known that this browser is broken in all sorts of ways. You probably have javascript errors in the browser, what are they?
Here is a what can be a useful link.

Related

Fallback (default) image using Angular JS ng-src

I'm trying to set an image source using data returned from a modal. This is inside an ng-repeat loop:
<div id="divNetworkGrid">
<div id="{{network.id}}" ng-repeat="network in networks">
<span>
<table>
<tr>
<td class="imgContainer">
<img ng-src="{{ ('assets/img/networkicons/'+ network.actual + '.png') ||
'assets/img/networkicons/default.png' }}"/>
</td>
</tr>
</table>
</span>
</div>
</div>
As is apparent, I want to populate default.png when the network.actual model property is returned as null. But my code is not picking up the default image, though the first image is coming up fine when available.
I'm sure this is some syntax issue, but cant figure out what's wrong.
I have just found out, that you can use both ng-src and src on an img tag and if ng-src fails (variable used does not exists etc.), it will automatically fallback to src attribute.
What I imagine is happening is the src is returning a 404 even if network.actual is null. For example, first value:
('assets/img/networkicons/'+network.actual+'.png')
is evaluating to a 404 src URL, something like ('assets/img/networkicons/null.png'). So in the OR selection, it's truth-y, but the resource is 404. In that case, you can set the fallback via onError with something like:
<img ng-src="{{('assets/img/networkicons/'+network.actual+'.png')}}" onerror="this.src='assets/img/networkicons/default.png'" />
CodePen to demo use cases - http://codepen.io/jpost-vlocity/pen/zqqerL
angular.module('fallback',[]).directive('fallbackSrc', function () {
return{
link: function postLink(scope, element, attrs) {
element.bind('error', function () {
angular.element(this).attr("src", attrs.fallbackSrc);
});
}
}
});
<img ng-src="{{url}}" fallback-src="default-image.jpg"/>
angular.module('fallback', []).directive('actualSrc', function () {
return{
link: function postLink(scope, element, attrs) {
attrs.$observe('actualSrc', function(newVal, oldVal){
if(newVal != undefined){
var img = new Image();
img.src = attrs.actualSrc;
angular.element(img).bind('load', function () {
element.attr("src", attrs.actualSrc);
});
}
});
}
}
});
<img actual-src="{{url}}" ng-src="default.jpg"/>
link
Interesting way to use ng-src. I haven't tested how that expression would be handled but I would suggest doing it a more stable way:
<img ng-src="{{ networkIcon }}" />
And in your controller:
$scope.networkIcon = network.actual ? 'assets/img/networkicons/' + network.actual + '.png' : 'assets/img/networkicons/default.png';
Edit: Just to clarify, I'm not suggesting the best way to do this is to bind the image source directly to the scope but rather to move the image fallback logic outside of the view. In my applications I often do it in the services that retrieve the data or on the server itself and send an image URL so the client only has to worry about a single property.
Edit to address repeater:
angular.forEach($scope.networks, function(network) {
network.icon = network.actual ? 'assets/img/networkicons/' + network.actual + '.png' : 'assets/img/networkicons/default.png';
});
<tr ng-repeat="network in networks">
<td><img ng-src="{{ network.icon }}" /></td>
</tr>
<div id="divNetworkGrid">
<div id="{{network.id}}" ng-repeat="network in networks">
<span>
<table>
<tr>
<td class="imgContainer">
<img ng-src="{{'assets/img/networkicons/'+(network.actual || 'default' )+'.png'}}"/>
</td>
</tr>
</table>
</span>
</div>
</div>
The inline or will work if the the queried variable is undefined. The above will fix your issue
You can supply the alternative image after OR operator like this:
{{ book.images.url || 'Images/default.gif' }}

The event dispatched from a html page is not received by main.js in my firefox extension

In my firefox extension I need user input to do further computations on my extension.
I used a panel to do this. With panels I can get input form user and pass it to my content script and emit this from there using self.port.emit and receive it on main.js using panel.port.on. But my problem is panels auto hide. I want to show my panel until user closes it.
I tried getting the above scenario by opening a html page using window window.open. But I could not pass the user input from my html window to main.js. I used the following code.
MY SR.html code
<!DOCTYPE HTML>
<html>
<head>
<title>Title</title>
<script>
var t= {
CallExtension : function(e) {
var text = document.getElementById("p").value;
var element = document.createElement("MyExtDE");
element.setAttribute("phNu", text);
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("SREvent", true, false);
element.dispatchEvent(evt);
}
}
</script>
<style>
table{ padding-top:30px;}
h1{ color:orange; }
td{ font-family:"Arial"; font-size:12px; }
</style>
</head>
<body>
<table cellspacing=5 cellpadding=5 align="center" border=0>
<tr>
<td colspan=3><h1>MyRMN Start Registration</h1></td>
</tr>
<tr>
<td>Phone Number</td><td>:</td><td><input type="text" id="p" name="pn"/>
</td>
</tr>
<tr>
<td><input type="button" id="btnSSubmit" value="Submit"
onclick="t.CallExtension(event);" /></td>
</tr>
</table>
</body>
My main.js code
function SR(){
try {
win = window.open(data.url("SR.html"), "SR",
"chrome,centerscreen");
win.document.defaultView.addEventListener("SREvent", S1Submit, false, true);
//window.window.document.defaultView.addEventListener("SREvent", S1Submit, false,
true);
} catch(e) {
prompts.alert(null, "main() SR", " Exception: " + e);
}
}
function S1Submit(evt){
var text = evt.target.getAttribute("phNu");
prompts.alert(null, "main() S1Submit", text);
if (text) {
mSR(text);
}
}
UPDATE
I introduced page-mod in my main.js page and i could not still communicate with my main.js
from my webpage.
main.js
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
function StartRegistration(){
try {
winSReg = window.open(null, data.url("SR.html"), "Title",
"chrome,centerscreen", null);
} catch(e) {
prompts.alert(null, "Title", "SR Exception: " + e);
}
}
pageMod.PageMod({
include: data.url("SR.html"),
contentScriptFile: data.url("SR.js"),
onAttach: function(worker) {
worker.port.on("gotInput", function(inputValue) {
doSomethingWith(inputValue);
});
}
});
SR.JS
function SubmitSReg(){
try {
var text = document.getElementById("p").value;
alert("SR.js text:" + text);
self.port.emit("gotInput", text);
} catch(e) {
alert(e);
}
}
SR.Html
<!DOCTYPE HTML>
<html>
<head>
<title>SR</title>
<script type="text/javascript" src="SR.js"></script>
<style>
table{ padding-top:30px;}
h1{ color:orange; }
td{ font-family:"Arial"; font-size:12px; }
</style>
</head>
<body>
<table cellspacing=5 cellpadding=5 align="center" border=0>
<tr>
<td colspan=3><h1>Title</h1></td>
</tr>
<tr>
<td>Phone Number</td><td>:</td><td><input type="text" id="p"
name="pn" /></td>
</tr>
<tr>
<td><input type="button" id="btnSSubmit" value="Submit" onclick =
"SubmitSReg()"/></td>
</tr>
</table>
</body>
</html>
Any kind of help is greatly appreciated.
Thanks in advance
Your approach is right but there's a missing part: in order to allow communication between the main.js and your static page you need to use a page-mod matching your static page local url.
Add this to your main.js:
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: data.url("SR.html"),
contentScriptFile: [data.url("script.js")],
onAttach: function(worker) {
worker.port.on("gotInput", function(inputValue) {
doSomethingWith(inputValue);
});
}
});
And also create a data/script.js file containing:
/* Here add a listener to the form's submit event and then
get the input element and its value.
Then do this with yhe input value:
*/
self.port.emit('gotInput', inputValue);
This way you achieve communication between your page and the addon main.js.

Knockout observableArray not binding

I am trying to bind an observableArray from an ajax server read but not able to bind it to the html. The json data is returning but not sure how to parse or get it to bind. I am new to Knockout.
Code:
<html>
<head>
<title></title>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.3.5/knockout.mapping.js"></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<script>
function SurnameViewModel() {
var self = this;
self.Surnames = ko.observableArray();
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/CID",
dataType: 'json',
data: { "Name": "d", "CID": "17" }, // <==this is just a sample data
processdata: true,
success: function (result) {
self.Surnames= ko.mapping.fromJS(result.data);
alert(self.Surnames()); // <== able to see the json data
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
// Activates knockout.js
$(document).ready(function() {
ko.applyBindings(new SurnameViewModel())
});
</script>
</head>
<body>
<h2>Surnames</h2>
<table>
<thead><tr>
<th>ID</th><th>Surname</th>
</tr></thead>
<tbody data-bind="foreach: Surnames">
<tr>
<td data-bind="text: Surnames().id"></td>
<td data-bind="text: Surnames().homename"></td>
</tr>
</tbody>
</table>
</body>
</html>
Json Data Returned from the alert
data: "[{"id":3,"homename":"DCosta"}]"
What am doing wrong here?
Edit: Working code
This is what worked for me.
I change this
ko.mapping.fromJS(result.data, {}, self.Surnames);
to
ko.mapping.fromJSON(result.data, {}, self.Surnames);
and in the html from this
<tr>
<td data-bind="text: Surnames().id"></td>
<td data-bind="text: Surnames().homename"></td>
</tr>
to this
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: homename"></td>
</tr>
You have two problems:
In your view when using the foreach binding you are "inside" of the context of the array so you don't need to write out the array name (Surnames()) again:
<tbody data-bind="foreach: Surnames">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: homename"></td>
</tr>
</tbody>
When you are getting back the data from the server you are overriding the Surnames array, the correct way of using the mapping plugin here:
ko.mapping.fromJS(result.data, {} /* empty mapping options */, self.Surnames);
Or
self.Surnames(ko.mapping.fromJS(result.data)());
Note the () in the above code, you need this because the ko.mapping.fromJS(result.data) will return an ko.observableArray without getting its underlaying value with the () you would end up with your Surnames containing another ko.observableArray

How to retrieve multiple records from Jquery to my RazorView page

I have a button "btnGetAddress" on my razor page .On clik of this button,I am calling a Jquery to get my addressItmes object to be displayed on to my View page.
On clicking "btnGetAddress" I am able to hit my "JsonResult GetAddresses()" and retrieve records within my Jquery (success: function (data)).and this data has multiple address records. But I do not know how to take this data to my view .Please help me to get my data to be displayed on to my View
When my page get loaded,the user will see only the "btnGetAddress" button .When the user click on the btnGetAddress, it will call the Jquery Click function to fetch all address records from database and display each set of records on the page
$("#btnGetAddress").click(function () {
debugger;
var selected = $("#ddlType").val();
if (selected == "")
{ selected = 0; }
var dataToSend = {
SelectedTypeId: selected
};
$.ajax({
type: "GET",
url: '#Url.Action("GetAddresses", "Content")',
data: { SelectedTypeId: selected },
success: function (data) {
debugger;
},
error: function (error) {
var verr = error;
alert(verr);
}
});
pasted below is my JsonResult GetAddresses() which gets called to retrieve addressItems
public JsonResult GetAddresses()
{
model.AddressItems = AddressService.RetrieveAllAddress();
// My AddressItems is of type IEnumerable<AddressItems>
return Json(model.AddressItems, JsonRequestBehavior.AllowGet);
}
Here is my razor View Page where the address records are to be displayed.
........................
<input type="submit" id="btnGetAddress" name="btnSubmit" value="Show Addresses" />
if (!UtilityHelper.IsNullOrEmpty(Model.AddressItems))
{
foreach (var AddressRecord in Model.AddressItems)
{
<fieldset >
<legend style="padding-top: 10px; font-size: small;">Address Queue(#Model.NumRecords)
</legend>
<table>
<tr>
<td>
<span>Index</span>
</td>
<td>
</td>
<td>
<input type="submit" id="btnDelete" name="btnSubmit" value="X" />
<br />
</td>
</tr>
<tr>
<td>
<span>Address1</span>
<br />
</td>
<td>
#Html.EditorFor(model => AddressRecord.Address )
#Html.ValidationMessageFor(model => AddressRecord.Address)
</td>
</tr>
<tr>
<td>
<span>Description</span>
<br />
</td>
<td>
#Html.EditorFor(model => AddressRecord.Description)
#Html.ValidationMessageFor(model => AddressRecord.Description)
</td>
</tr>
<tr>
<td>
<input type="submit" id="btnSave" name="btnSubmit" value="Save" />
</td>
<td>
<input type="submit" id="btnDelete" name="btnSubmit" value="Delete" />
</td>
</tr>
</table>
</fieldset>
}
}
<fieldset>
Or is there any better way to achieve my objective?
Since you are getting the data via ajax you should use a jquery template engine. Basically get the data the way you are and on success you do something like
<script language="javascript" type="text/javascript">
$(function () {
$.getJSON("/getprojects", "", function (data) {
$("#projectsTemplate").tmpl(data).appendTo("#projectsList");
});
});
</script>
<script id="projectsTemplate" type="text/html">
<section>
<header><h2>Projects</h2></header>
<table id="projects">
<th>Name</th>
{{tmpl(items) "#projectRowTemplate"}}
</table>
</section>
</script>
<script id="projectRowTemplate" type="x-jquery-tmpl">
<tr>
<td>${name}</td>
</tr>
</script>
<div id="projectsList"></div>
Now each template engine is different but the above gives you an idea of what you can do
If you want to return JSON object in your controller, you are going have to turn your view into a string and return it as part of the message. If you google there are some methods out there that can do this.
However, I really think that's the hard way, why not take the data you get from the JSON in the controller and put it in a MODEL and then return your VIEW with the model data passed in. I think that's the easier way.

ajax gif loader

can you tell me where and how to put an ajx loading.gif?
my html code is below
<div class="searchbox">
<input id="Search" onkeyup="searchKeyUp(event)
" name="Search" class="searchtextbox"/>
</div>
</td>
<td width="57"><br> <img onclick="search(); return false;" style=" cursor:pointer" eight="30" onmouseover="this.src='images/j3.jpg'" type="image" src="images/j1.jpg" onmouseout="this.src='images/s1.jpg';" alt="" width="57" ></td>
</tr>
</table>
<div>
<table cellspacing="0" cellpadding="0" border="0">
<tr valign="left">
<td><div class="resultCss" content="tableId" id='resultDiv'>
</div></td>
</tr>
</table>
Before your AJAX request starts , display the ajax_load.gif and after it ends, remove it.
Tip: Make sure you have only 1 AJAX request sent to your server at a time like https://www.buxfer.com
build in on the position you want to have it and give display:none on it. In search() before AJAX Call edit the display:none to block and hide the image onSuccess off the AJAX function again.
You need to place gif file to any proper place and set "display:none;"
You can use my function based on jQuery. It automatically shows or hide the spinner on every ajax call.
function simpleAjax(pageUrl , divId , spinnerId , formId , isFormEnabled)
{
var dataVar ='';
var d = new Date();
if(isFormEnabled)
dataVar = $('#'+formId).serialize();
$.ajax(
{
type: 'GET',
url: pageUrl,
cache:false,
data:dataVar,
success: function(response){ $('#'+divId).html(response); $('#'+spinnerId).hide(); },
beforeSend: function(){ $('#'+spinnerId).show();},
error: function(m){ alert(m); },
complete: function(){}
});
}

Resources