ajax gif loader - ajax

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

Related

Datatable Editor 1.4 on JQUERY: async AJAX call. How I can to place after?

On index.html I have two pages JQM v.1.4.
In page-1 I´ve a form that get (nombreUsuario) and password and assign into respective vars.
In page-2 , I want to use the previous (nombreUsuario) for to get table that match with this nombeUsuario via AJAX on Datatable Editor 1.4.
My problem is that in page-1 the AJAX call is executed before that I enter nombreUsuario , therefore when pass to page-2 the table is empty , due the AJAX call was executed with variable empty , without nombreUsuario entry.
I´ve tried different code to get that AJAX call executed after entry nombreUsuario but I don’t get desired result . I´ve used async to false, but to do nothing .
Also, DataTable Editor AJAX document said :
Success: Must not be overridden as it is used internally in DataTables . Even so, I´ve used this option (taking jquery examples) and is true that don’t work (is yes, please tell me!) .
Now, will be more easy resolve it on JQM?. How can I to get nombreUsuario on page-1 and after pass to page-2 , then will execute AJAX call with this variable?
Any idea?. Thank you in advance!
index.html
<div data-role="page" id="page0">
<form id="formulario" >
<label> Usuario </label>
<input type="text" id="nombredeusuario" name="nombredeusuario">
<label> Password </label>
<input type="password" id="clave" name="clave" >
<input type="submit" value="Login" id="botonLogin">
</form>
...
<div data-role="page" id="page1">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Establecimiento</th>
<th>Telefono</th>
<th>E-mail</th>
<th>Nº de Plazas</th>
<th>Precio medio</th>
<th>E-mail (responsable)</th>
<th>Prueba (1) / Contrato (2)</th>
</tr>
</thead>
....
JS:
(form)
$('#formulario').submit(function() {
// recolecta los valores que inserta el usuario
var datosUsuario = $("#nombredeusuario").val()
var datosPassword = $("#clave").val()
...
JS (datatable editor 1.4)
$('#example').DataTable( {
//check. start
initComplete: function(settings, json) {
alert( 'DataTables has finished its initialisation.' );
},
//check.end
dom: "Tfrtip",
ajax: {
async: false, // don't work
url:"http://tripntry.com/_country/spain/b.cartasconmenu.front.back.demo/alacarte/php/clientes.php",
type: "POST",
data: function ( d ) {
d.site = $("#nombredeusuario").val(); // dont work!
//d.site = datosUsuario; //// dont work!
//d.site = "34280001"; // works (of course)
},
....
PHP (server side)
include( "../../php/DataTables.php" );
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Join,
DataTables\Editor\Validate;
$site=$_POST['site'];
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'clientes' )
->fields(
Field::inst( 'tipo' )->validator( 'Validate::numeric' ), //this field another use
Field::inst( 'site' )->validator( 'Validate::notEmpty' )
)
->where( 'site', $site)
->process( $_POST )
->json();

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

jQuery .append(html) command appending incorrectly

I am using a jQuery/Ajax call to append a partial view to a table. When the page loads, the partial view is created correctly. However, once the use attempts to append another item to the table, the formatting is incorrect despite the exact same partial view being used.
Here is the table. When this loads, the items are loaded onto the page correctly as the picture below illustrates:
<table id="fixedRows">
<thead>
<tr>
<th>State Code</th>
<th>Agent ID</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.BankListAgentId)
{
if (!String.IsNullOrWhiteSpace(item.AgentId) && item.FixedOrVariable.Equals("F"))
{
#Html.EditorFor(model => item, "FixedPartialView")
}
}
</tbody>
</table>
<br />
Add Another
Once you click the Add another link, this jQuery/Ajax call is activiated
<script type="text/javascript">
$(document).ready(function () {
$(".addFixed").click(function () {
//alert('test');
event.preventDefault();
$.ajax({
url: '#Url.Action("BlankFixedRow", "BankListMaster")',
cache: false,
success: function (html) { $("#fixedRows").append(html); }
});
});
$("#addVariable").click(function () {
event.preventDefault();
$.ajax({
url: '#Url.Action("BlankFixedRow", "BankListMaster")',
cache: false,
success: function (html) { $("#variableRows").append(html); }
});
});
});
</script>
That jQuery calls this method from the controller
public ViewResult BlankFixedRow()
{
SelectList tmpList = new SelectList(new[] { "AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NA", "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "US", "VT", "VI", "VA", "WA", "WV", "WI", "WY" });
ViewBag.StateCodeList = tmpList;
return View("FixedPartialView", new BankListAgentId());
}
Which calls this partial view
EDIT(a couple people noticed the id tag missing from the <tr>, this was just a copy/paste error for this post, the actual code has the id tag)
#model Monet.Models.BankListAgentId
#{
Layout = null;
}
#using (Html.BeginCollectionItem("BankListAgentId"))
{
<tr id="item-#Model.AgentId">
<td>
#Html.DropDownListFor(model => model.StateCode,
(SelectList)ViewBag.StateCodeList, Model.StateCode)
</td>
<td>
#Html.EditorFor(model => model.AgentId)
#Html.ValidationMessageFor(model => model.AgentId)
</td>
<td>
delete
</td>
#*<td>Delete</td>*#
</tr>
}
This is the same partial view that is called when the page first loads, which part of why I'm confused that the end result after hitting the Add another link turns out looking like this
EDIT
If you hit the Add another link twice, this is the result
EDIT
I've tried the following jQuery sucess commands with no luck
success: function (html) { $("#fixedRows > tbody:last").append(html); }
success: function (html) { $("#fixedRows tr:last").after(html); }
success: function (html) { $("#fixedRows > tbody").append(html); }
Here is the HTML that is rendered after the Add another link is clicked. I included the opening <form> tag for the form below it to show that the new rows are nowhere to be found.
<form action="/BankListMaster/Edit/11" method="post">
<fieldset>
<legend>Stat(s) Fixed</legend>
<table id="fixedRows">
<tr>
<th>State Code</th>
<th>Agent ID</th>
<th></th>
<th></th>
</tr>
<tr id="item-1164998320">
<td>
<select id="item_StateCode" name="item.StateCode"><option value="">HI</option>
<option>AL</option>
..
<option>WY</option>
</select>
</td>
<td>
<input class="text-box single-line" id="item_AgentId" name="item.AgentId" type="text" value="1164998320" />
<span class="field-validation-valid" data-valmsg-for="item.AgentId" data-valmsg-replace="true"></span>
</td>
<td>
delete
</td>
</tr>
<tr id="item-1164998219">
<td>
<select id="item_StateCode" name="item.StateCode">
<option value="">HI</option>
<option>AL</option>
..
<option>WY</option>
</select>
</td>
<td>
<input class="text-box single-line" id="item_AgentId" name="item.AgentId" type="text" value="1164998219" />
<span class="field-validation-valid" data-valmsg-for="item.AgentId" data-valmsg-replace="true"></span>
</td>
<td>
delete
</td>
</tr>
<tr id="item-0352926603">
<td>
<select id="item_StateCode" name="item.StateCode">
<option value="">GA</option>
<option>AL</option>
..
<option>WY</option>
</select>
</td>
<td>
<input class="text-box single-line" id="item_AgentId" name="item.AgentId" type="text" value="0352926603" />
<span class="field-validation-valid" data-valmsg-for="item.AgentId" data-valmsg-replace="true"></span>
</td>
<td>
delete
</td>
</tr>
</table>
<br />
Add Another
</fieldset>
</form>
Add Another
<form action="/BankListMaster/Edit/11" method="post">
EDIT
Here is a screen shot of the table in Chrome's debugger after the Add Another link is clicked. As you can see, the data pulled from the table is loaded properly in respective <tr> tags, however the empty row (which is sent via the same partial view as the rest) doesn't have any of the same table elements. The screen shot below that shows Response, however, which does include the <tr> tags
EDIT
I put a console.log(html) line in the success Ajax function so it now reads
success: function (html) {
console.log(html);
$("#fixedRows > tbody").append(html);
}
Here is the console output (state edited for readability)
<input type="hidden" name="BankListAgentId.index" autocomplete="off" value="3f7e0a92-8f20-4350-a188-0725919f9558" />
<tr>
<td>
<select id="BankListAgentId_3f7e0a92-8f20-4350-a188-0725919f9558__StateCode" name="BankListAgentId[3f7e0a92-8f20-4350-a188-0725919f9558].StateCode">
<option>AL</option>
..
<option>WY</option>
</select>
</td>
<td>
<input class="text-box single-line" id="BankListAgentId_3f7e0a92-8f20-4350-a188-0725919f9558__AgentId" name="BankListAgentId[3f7e0a92-8f20-4350-a188-0725919f9558].AgentId" type="text" value="" />
</td>
<td>
delete
</td>
</tr>
What a complete nightmare...
First off, the HTML that was being returned as viewable in Chrome's debugger was fine, however when I clicked on "View Source" for the page, I could not see anything but what was originally loaded. After finding this post, I found that this is normal. I then used this Chrome add-on to finally see that the <tr> and <td> tags were being stripped out. By simply adding an opening and closing tag to the append statement, I got the returned items to append to the table.
$(".addFixed").click(function () {
$.ajax({
url: '#Url.Action("BlankFixedRow", "BankListMaster")',
dataType: 'html',
cache: false,
success: function (html) {
$("#fixedRows > tbody").append('<tr>' + html + '</tr>');
}
});
});
I see a few things here. You're referencing <tbody> in some of your code but I don't see it anywhere in the page. So first I would suggest using <thead> and <tbody>. In your partial view I see <tr "item-#Model.AgentId"> which should have an id.
You should also remove the onclick handler and the delete button and put that in with the rest of your JavaScript. Set a class on your delete links instead.
For links that don't need urls and are only used for attaching JavaScript handlers, I recommend using href="javascript:void(0)" as this would prevent the browser from doing anything special with href="#" so then you'll be able to remove the calls to preventDefault().
As to the source of your problem, $("#fixedRows tbody").append(html) is the code you want so no need to try after(). It looks like your html is getting stripped. Try setting the dataType attribute in the $.ajax() call to html.

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 function that works in Firefox but not in IE 6

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.

Resources