I trying to update code from extjs2 to extjs4. But I have a some problem with load event in Ext.data.DataProxy.
Ext.define('App.data.DwrProxy', {
extend: 'Ext.data.DataProxy',
constructor: function(config){
App.data.DwrProxy.superclass.constructor.call(this);
this.invoker = config.invoker;
},
load: function(params, reader, callback, scope, arg) {
if (this.fireEvent("beforeload", this, params) !== false) {
if (!this.invoker) {
alert("'invoker' property is not specified");
return;
}
this.reader = reader;
this.callback = callback;
this.scope = scope;
this.arg = arg;
params.gridState = params.gridState || {};
if (params.sort != null)
params.gridState.sortField = params.sort;
if (params.dir == 'ASC')
params.gridState.descendingOrder = false;
if (params.dir == 'DESC')
params.gridState.descendingOrder = true;
if (params.start != null) {
params.gridState.pageNo = Math.floor(params.start / params.limit);
if (isNaN(params.gridState.pageNo))
params.gridState.pageNo = 0;
}
if (params.limit != null)
params.gridState.pageSize = params.limit;
this.invoker.call(
scope || this,
params,
arg,
{
callback: Ext.bind(this.success, this),
errorHandler: Ext.bind(this.failure, this)
}
);
} else {
callback.call(scope || this, null, arg, false);
}
}
});
As I know, Ext.data.DataProxy load event don't support in extjs4. So, how to use this function?
I used read instead and it worked for me.
Related
I want to refresh my data whenever the app is resumed from the background. Actually, I want this functionality on only one page, not the whole app. I am using the Prism OnAppearning method in my model view. After capturing a photo with the camera when the control moves back to the app and OnApearning method is called again. How to avoid this situation? I tried OnSleep and OnResume in model view but these also have the same behavior.
I have attached my view model code below. ClockInTriggered
called when user wants to mark attendance with the face. RecognizeUser method get call for taking a picture from Camera. After taking picture method OnAppearning gets a call which is annoying.
private async void ClockInTriggered()
{
string action = await App.Current.MainPage.DisplayActionSheet(AppResources.Select_Activity, AppResources.Cancel, null, Activities.Select(x => x.Name).ToArray());
if (action == AppResources.Cancel || action == null)
return;
Activity SelectedRole = Activities.SingleOrDefault(x => x.Name == action);
ClockInVisibility = false;
LoadingIndicator = true;
LoadingText = "";
var recResult = await RecognizeUser();
if (recResult == false)
{
ClockInVisibility = true;
LoadingIndicator = false;
return;
}
var locResult = await GetCurrentLocation();
var revGeoResult = await GetReverseGeoLocation();
LoadingText = AppResources.Done_;
await Task.Delay(1000);
if (recResult && locResult && revGeoResult)
{
Attendance attendance = new Attendance()
{
DateNTime = DateTime.Now,
CheckType = "CheckIn",
ActivityId = SelectedRole.Id,
LocationInfo = ReverseGeoCoding,
Lati = Lati,
Longi = Longi
};
var result = await AddAttendanceEntry(attendance, "CheckIn");
switch (result)
{
case "true":
List<Attendance> unsortedAttendance = await GetEmployeeStoredAttendance();
Attendance = unsortedAttendance.OrderByDescending(x => x.DateNTime).ToObservableCollection();
break;
case "false":
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.We_could_not_clock_you_in__Please_try_again_,
AppResources.OK);
ClockInVisibility = true;
LoadingIndicator = false;
return;
default:
await App.Current.MainPage.DisplayAlert(AppResources.Error, result,
AppResources.OK);
await navigationService.NavigateAsync("/MasterLayout/NavigationPage/MainPage/TimeAttendance");
break;
}
}
else
{
ClockInVisibility = true;
LoadingIndicator = false;
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.We_could_not_clock_you_in__It_can_be_due_to_location_or_face_detection_problem__Please_try_again_,
AppResources.OK);
return;
}
LoadingIndicator = false;
TimeGradient1 = "#FFB75E";
TimeGradient2 = "#DA2020";
ClockOutVisibility = true;
}
private async Task<bool> RecognizeUser()
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await App.Current.MainPage.DisplayAlert(AppResources.No_Camera, AppResources.No_camera_is_available_, AppResources.OK);
return false;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Small,
CompressionQuality = 60,
Directory = "Recognition",
Name = DateTime.Now + "-Identify.jpg"
});
if (file == null)
{
return false;
}
RecognitionResult = await Identify(file.GetStream());
if (RecognitionResult.ReturnType == null)
{
await App.Current.MainPage.DisplayAlert(AppResources.Alert, RecognitionResult.Status, AppResources.OK);
return false;
}
bool result = await GetCurrentLocation();
return true;
}
private async void RefreshLogAndButtons()
{
LoadingIndicator = true;
LoadingText = AppResources.Loading___Please_Wait_;
ClockInVisibility = false;
ClockOutVisibility = false;
await Task.Delay(2000);
await GetCurrentLocation();
await GetReverseGeoLocation();
List<Attendance> unsortedAttendance = await GetEmployeeStoredAttendance();
Attendance = unsortedAttendance.OrderByDescending(x => x.DateNTime).ToObservableCollection();
if (Attendance.Count != 0 && Attendance != null)
{
ActivateButton();
try
{
TotalTime = await TimeDifferenceCalculator(Attendance);
}
catch (Exception e)
{
}
}
else
{
ClockInVisibility = true;
LoadingIndicator = false;
}
}
public void OnAppearing()
{
RefreshLogAndButtons();
}
public void OnDisappearing()
{
}
Need direction on how to code for the three instances to then assign values to the variables using isWarmBlooded method ..
```Animal.prototype.isWarmBlooded = function(species){
if(this.species === "Fish"){
return this.species = false;
}
if(this.species === "Monkey" || this.species === "Bird"){
return this.species = true;
}
if(this.species !== "Fish" || this.species !== "Monkey" || this.species !== "Bird"){
return "Could not determine if warm-blooded";
}
};
//Call the isWarmBlooded method on three Animal instances
//and assign the values to each variable below.
var warmBloodedAnimal = Animal.prototype.isWarmBlooded("Monkey");
var coldBloodedAnimal;
var notWarmOrColdAnimal;```
var Animal = function (species){
this.species = species;
};
Animal.prototype.isWarmBlooded = function(species){
if (this.species === "Fish"){
return false;
}
else if(this.species === "Monkey" || this.species === "Bird"){
return true;
}
else{
return "Could not determine if warm-blooded";
}
};
var warmBloodedAnimal = new Animal("Monkey");
console.log(warmBloodedAnimal.isWarmBlooded());
I am developing Custom Component for Joomla.
I did well in validating field by adding custom rule. But if entered value does not pass through my validation, it gives error as "Invalid Field: My Field Name"
I want to replace this with my own message.
I know I can use "JText::_('LANGUAGE_STRING'). But I'm not sure where do I need to add it.
I have custom rule called "validemails" which returns false in client side as well as server side validation.
My Client side Validation is: (components/com_helpdesk/models/forms/create.js)
jQuery(document).ready(function () {
document.formvalidator.setHandler('validemail', function (value) {
var emails = [value];
if (value.indexOf(';') !== -1) {
emails = value.split(';');
}
else if(value.indexOf(',') !== -1) {
emails = value.split(',');
}
regex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var result = false;
emails.each(function (value) {
result = regex.test(jQuery.trim(value));
if (result === false) {
return false;
}
});
return result;
});
});
My Server Side Validation is: (components/com_helpdesk/models/rules/validemail.php)
use Joomla\Registry\Registry;
JFormHelper::loadRuleClass('email');
class JFormRuleValidemail extends JFormRuleEmail {
public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null) {
$emails = array($value);
if (strpos($value, ';') !== false) {
$emails = explode(';', $value);
}
else if (strpos($value, ',') !== false) {
$emails = explode(',', $value);
}
foreach ($emails as $email) {
if (!parent::test($element, trim($email))) {
return false;
continue;
}
}
return true;
}
}
Please note that I'm developing Front-end view of Component not back-end.
Well fortunately, I got my server side validation working by this way:
use Joomla\Registry\Registry;
JFormHelper::loadRuleClass('email');
class JFormRuleValidemail extends JFormRuleEmail {
public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null) {
$emails = array($value);
if (strpos($value, ';') !== false) {
$emails = explode(';', $value);
}
else if (strpos($value, ',') !== false) {
$emails = explode(',', $value);
}
foreach ($emails as $email) {
if (!parent::test($element, trim($email))) {
***$element->addAttribute('message', JText::_('COM_HELPDESK_ERROR_EMAIL').' '.$value);***
return false;
continue;
}
}
return true;
}
}
I got the solution. May be it will be useful for other googlers. Below is a code snippet for client side validation. Put below code in your custom JS:
jQuery('.validate').click(function (e) {
var fields, invalid = [], valid = true, label, error, i, l;
fields = jQuery('form.form-validate').find('input, textarea, select');
if (!document.formvalidator.isValid(jQuery('form'))) {
for (i = 0, l = fields.length; i < l; i++) {
if (document.formvalidator.validate(fields[i]) === false) {
valid = false;
invalid.push(fields[i]);
}
}
// Run custom form validators if present
jQuery.each(document.formvalidator.custom, function (key, validator) {
if (validator.exec() !== true) {
valid = false;
}
});
if (!valid && invalid.length > 0) {
error = {"error": []};
for (i = invalid.length - 1; i >= 0; i--) {
label = jQuery.trim(jQuery(invalid[i]).data("label").text().replace("*", "").toString());
if (label) {
if(label === 'Subject') {
error.error.push('Please Enter Subject');
}
if(label === 'Description') {
error.error.push('Please Enter Description');
}
if(label === 'Priority') {
error.error.push('Please Select Priority');
}
if(label === 'Email CCs') {
error.error.push('Please Enter proper Emails in CC section');
}
if(label === 'Email BCCs') {
error.error.push('Please Enter proper Emails in BCC section');
}
}
}
}
Joomla.renderMessages(error);
}
e.preventDefault();
});
In our application we use MvcContrib for generating links with the exception of cross area links where Contrib seems to be not working properly (or we are doing something wrong). In services we have a function that generates a List< ZakladkaModel > which contains url and other properties used in generating tabstrib via custom html helper. That function takes as an argument an id of database object and UrlHelper to help in link creating.
m_service.GenerowanieZakladkiDlaKontrolera_ARCH_Akt(idAktu, new UrlHelper(this.ControllerContext.RequestContext));
Then in the GenerowanieZakladkiDlaKontrolera_ARCH_Akt we have something like this:
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Akt", Url = "" });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Wzmianki", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.ARCH_WzmiankiController>(c => c.Index(idAktu)) });
if (tekstJednolity.StanTekstuJednolitego == "RB" || tekstJednolity.StanTekstuJednolitego == "SW")
{
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "t.j. aktu", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.ARCH_TekstJednolityController>(c => c.Edytuj(tekstJednolity.Id)) });
}
else
{
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "t.j. aktu", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.ARCH_TekstJednolityController>(c => c.Raport(tekstJednolity.Id)) });
}
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 1", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek1Controller>(c => c.Index(idAktu)) });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 2", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek2Controller>(c => c.Index(idAktu)) });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 3", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek3Controller>(c => c.Edytuj(idAktu)) });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 4", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek4Controller>(c => c.Edytuj(idAktu)) });
Now the problem is that on some co-workers computers it generates links to actions properly and on some it looks like it takes a ranedom area from our app and tries to make an invalid link. We could use a simple url.Action("action","controler") which works fine on all but we would prefer MvcContrib :). Does anyone have any idea why this occurs? Or can share an alternative?
It seems that LinkBuilder which is used under doesn't use GetVirtualPatchForArea at all which as I read is MVC bug. So i decided to make my own HtmlHelper which uses that method:
public static string ActionArea<TController>(this HtmlHelper urlHelper, Expression<Action<TController>> expression) where TController : Controller
{
RouteValueDictionary routeValues = GetRouteValuesFromExpression(expression);
VirtualPathData vpd = new UrlHelper(urlHelper.ViewContext.RequestContext).RouteCollection.GetVirtualPathForArea(urlHelper.ViewContext.RequestContext, routeValues);
return (vpd == null) ? null : vpd.VirtualPath;
}
public static string ActionArea<TController>(this UrlHelper urlHelper, Expression<Action<TController>> expression) where TController : Controller
{
RouteValueDictionary routeValues = GetRouteValuesFromExpression(expression);
VirtualPathData vpd = urlHelper.RouteCollection.GetVirtualPathForArea(urlHelper.RequestContext, routeValues);
return (vpd == null) ? null : vpd.VirtualPath;
}
public static RouteValueDictionary GetRouteValuesFromExpression<TController>(Expression<Action<TController>> action) where TController : Controller
{
if (action == null)
{
throw new ArgumentNullException("action");
}
MethodCallExpression call = action.Body as MethodCallExpression;
if (call == null)
{
throw new ArgumentException("Akcja nie może być pusta.", "action");
}
string controllerName = typeof(TController).Name;
if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("Docelowa klasa nie jest kontrolerem.(Nie kończy się na 'Controller')", "action");
}
controllerName = controllerName.Substring(0, controllerName.Length - "Controller".Length);
if (controllerName.Length == 0)
{
throw new ArgumentException("Nie można przejść do kontrolera.", "action");
}
// TODO: How do we know that this method is even web callable?
// For now, we just let the call itself throw an exception.
string actionName = GetTargetActionName(call.Method);
var rvd = new RouteValueDictionary();
rvd.Add("Controller", controllerName);
rvd.Add("Action", actionName);
var namespaceNazwa = typeof(TController).Namespace;
if(namespaceNazwa.Contains("Areas."))
{
int index = namespaceNazwa.IndexOf('.',namespaceNazwa.IndexOf("Areas."));
string nazwaArea = namespaceNazwa.Substring(namespaceNazwa.IndexOf("Areas.") + 6, index - namespaceNazwa.IndexOf("Areas.") + 1);
if (!String.IsNullOrEmpty(nazwaArea))
{
rvd.Add("Area", nazwaArea);
}
}
//var typ = typeof(TController).GetCustomAttributes(typeof(ActionLinkAreaAttribute), true /* inherit */).FirstOrDefault();
/*ActionLinkAreaAttribute areaAttr = typ as ActionLinkAreaAttribute;
if (areaAttr != null)
{
string areaName = areaAttr.Area;
rvd.Add("Area", areaName);
}*/
AddParameterValuesFromExpressionToDictionary(rvd, call);
return rvd;
}
private static string GetTargetActionName(MethodInfo methodInfo)
{
string methodName = methodInfo.Name;
// do we know this not to be an action?
if (methodInfo.IsDefined(typeof(NonActionAttribute), true /* inherit */))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,
"Nie można wywoływać metod innych niż akcje.", methodName));
}
// has this been renamed?
ActionNameAttribute nameAttr = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), true /* inherit */).OfType<ActionNameAttribute>().FirstOrDefault();
if (nameAttr != null)
{
return nameAttr.Name;
}
// targeting an async action?
if (methodInfo.DeclaringType.IsSubclassOf(typeof(AsyncController)))
{
if (methodName.EndsWith("Async", StringComparison.OrdinalIgnoreCase))
{
return methodName.Substring(0, methodName.Length - "Async".Length);
}
if (methodName.EndsWith("Completed", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,
"Nie można wywoływać kompletnych metod.", methodName));
}
}
// fallback
return methodName;
}
static void AddParameterValuesFromExpressionToDictionary(RouteValueDictionary rvd, MethodCallExpression call)
{
ParameterInfo[] parameters = call.Method.GetParameters();
if (parameters.Length > 0)
{
for (int i = 0; i < parameters.Length; i++)
{
Expression arg = call.Arguments[i];
object value = null;
ConstantExpression ce = arg as ConstantExpression;
if (ce != null)
{
// If argument is a constant expression, just get the value
value = ce.Value;
}
else
{
value = CachedExpressionCompiler.Evaluate(arg);
}
rvd.Add(parameters[i].Name, value);
}
}
}
Hope this helps people with similiar problems. Some of the code above i got from mvc2-rtm-sources modified to my needs http://aspnet.codeplex.com/releases/view/41742
I have asked a question like this before, and the answer was great but the more I looked at my code the more confused I got, and after 10hrs my brain is shot and I'm in need of help. So all my content is loaded dynamically via Jquery's $.post and loaded into #content-container. Now I included my entire Jquery file to show you why I am getting so confused as how to get this to work without re-writing all the code. As you can see, and what I'm thinking, is that the history plugins such as BBQ, and history.js seem to be out of the question because I don't use anchor tags and the multitude of .live('click', funcition() { I have use different classes and id's for various reasons. I also believe that rules out using the hash and linking it to a single class via .trigger(), executing the AJAX(hope that makes sense). The only option I have left is actually kinda my question. Would it be possible to load the dynamic content into #content-container still using the $.post with $.load() or window.location and actually have the previous content loaded when the browser back button is clicked.
I greatly appreciate the help, really.....
$(document).ready(function() {
$(window).load(function () {
});
$('#map').hide();
$('#informational-container').hide();
$('.clickable').click(function(){
$('#map').hide();
});
function getTotalDealCount() {
$.post('../service/service.getTotalDealCount.php', {}, function(data) {
if(data.success) $('#deal-counter').append(data.results);
}, 'json');
return false;
}
function loadMap(lat, lon) {
var latlng = new google.maps.LatLng(lat, lon);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
}
function getLatLon(address, zipcode) {
$.post('../service/service.getLatLon.php', { address: address, zipcode: zipcode }, function(data) {
if(data.success) {
var res = data.results;
var coordinates = res.split('_');
loadMap(coordinates[0], coordinates[1]);
} else {
return false;
}
}, 'json');
return false;
}
function getAddressZipcode(id) {
$.post('../service/service.getAddressZipcode.php', { id: id }, function(data) {
if(data.success) {
var res = data.results;
var location = res.split('_');
getLatLon(location[0], location[1]);
} else {
return -1;
}
}, 'json');
return false;
}
$('#how-it-works').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m1');
});
$('#why-post-a-deal').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m2');
});
$('#who-are-we').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m3');
});
$('#contact-us').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m4');
});
$('#post-deal-img').live('click', function() {
$('#content-container').load('post.php');
});
$('.post-deal-inputs').live('click', function() {
$('.post-deal-inputs').live('click', function(e) {
$(this).val('');
$(this).removeClass('post-deal-inputs')
.addClass('post-deal-inputs-clicked');
});
});
$('#df5').live('click', function() {
$('#df7').val('');
$('#df7').hide();
});
$('#df6').live('click', function() {
$('#df7').show();
});
$('#post-how-to-link').live('click', function() {
apprise();
});
$('#terms').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m5');
});
$('#disclaimer').live('click', function() {
$('#content-container').load('../module/module.string.php #string-m6');
});
$('#post-deal-button').live('click', function() {
var dealForm = $('#deal-form').serialize();
var company = $('#df1').val();
var description = $('#df2').val();
var zipcode = $('#df4').val();
var starts = $('#df7').val();
var ends = $('#df8').val();
if(company == '' || company == 'Company') {
apprise('A company name is required!');
return false;
}
if(description == '' || description == 'Deal') {
apprise('A deal is required!');
return false;
}
var swear = swearFilter(description);
if(swear != false) {
apprise('Please remove the naughty word `' + swear + '` from your deal.');
return false;
}
if(zipcode == '' || zipcode == 'Zipcode') {
apprise('A zipcode is required!');
return false;
}
if($('#df7').is(':visible') && typeof(ends) != 'undefined') {
var res = validateDate(starts);
if(res == false) {
apprise('Please select a valid start date!');
return false;
}
}
if(typeof(ends) != 'undefined') {
var res = validateDate(ends);
if(res == false) {
apprise('Please select a valid end date!');
return false;
}
}
if(ends == '') {
apprise('A deal end date is required!');
return false;
}
if($('#df7').is(':visible') && $('#df7').val() == '') {
apprise('If its not a one day sale a start date is required!');
return false
}
$.post('../service/service.postDeal.php', { dealForm: dealForm }, function(data) {
if(data.success == true) {
apprise('Your deal has been posted, thank you!');
window.location = '../root/index.php';
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured and your deal has not been posted. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('The zipcode you supplied was not in our database. Please enter the city ' +
'and state/province in the following prompts to add your location.' , {'confirm':true}, function() {
insertNewLocation(zipcode);
});
}
if(data.fail == 3) {
apprise('A zipcode is required!');
}
}
}, 'json');
return false;
});
function validateDate(string) {
if(string.toLowerCase().indexOf('-') >= 0) {
var dateArray = string.split('-');
var year = dateArray[0], month = dateArray[1], day = dateArray[2];
if(year.length == 4 && month.length == 2 && day.length == 2) return true;
else return false;
}
return false;
}
function swearFilter(string) {
var ret = false;
var filter = [];
var stringArray = string.split(' ');
for(var i = 0; i < stringArray.length; i++) {
if(jQuery.inArray(stringArray[i], filter) > -1) {
ret = stringArray[i];
break;
}
}
return ret;
}
function insertNewLocation(zipcode) {
var city = '';
var state = '';
if (/[^a-zA-Z 0-9]+/g.test(zipcode)) {
apprise('The zipcode should contain only numbers, letters or both!');
return false;
}
apprise('Enter the name of the city:', {'input':true}, function(_city_) {
if(/[^a-zA-Z]+/g.test(_city_)) {
apprise('The city should contain only letters!');
return false;
}
city = _city_;
apprise('Enter the state in 2 letter abbreviated format:', {'input':true}, function(_state_) {
if (/[^a-zA-Z]+/g.test(_state_)) {
apprise('The state should contain only letters');
return false;
}
if(_state_.length > 2) {
apprise('The state should only be 2 letters in length');
}
state = _state_;
$.post('../service/service.insertNewLocation.php', { city: city, state: state, zipcode: zipcode }, function(data) {
if(data.success == true) {
apprise('Thank you, you may now submit you deal!');
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured and your location has not been added to our database. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('A zipcode is required!');
return false;
}
}
}, 'json');
return false;
});
});
}
$('#search-type-button').live('click', function() {
var search = $('#search-type-text').val();
var keyword = $('#keyword-type-text').val();
if(search == '') {
apprise('A zipcode or city and state combo to search for deals in your area!');
return false;
}
if(keyword == 'Keyword') {
apprise('If you want to add a keyword to you deal, make sure its unique!');
return false;
}
$.post('../service/service.loadDealsByCityOrZipcode.php', { search: search, keyword: keyword }, function(data) {
if(data.success) {
$('#content-container').html(data.results);
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured locating the deals. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('There are no deals within the zipcode you provided, be the first to add one!');
return false;
}
if(data.fail == 3) {
apprise('There are no deals matching the tag you supplied!');
return false;
}
if(data.fail == 4) {
apprise('A zipcode or city and state combo to search for deals in your area!');
return false;
}
}
}, 'json');
return false;
});
$('.deals-queried-deal').live('click', function() {
var id = this.id;
$('#comment-link').show();
$.post('../service/service.loadDealDescription.php', { id: id }, function(data) {
if(data.success == true) {
$('#content-container').html(data.results);
var res = getAddressZipcode(id);
if(res != -1) $('#map').show();
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured loading the deal you selected. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
} else if(data.fail == 2) {
apprise('The deal you selected does not exist! ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
} else if(data.fail == 3) {
apprise('An error has occured loading the deal you selected. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
}
}
}, 'json');
return false;
});
$('.vote-down').live('click', function() {
var id = this.id;
var vote = 0;
$.post('../service/service.tallyVote.php', { id: id, vote: vote }, function(data) {
if(data.success == true) {
apprise('Thank you for your vote!');
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured when voting for this deal. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('You have already voted for this deal!');
return false;
}
}
}, 'json');
return false;
});
$('.vote-up').live('click', function() {
var id = this.id;
var vote = 1;
$.post('../service/service.tallyVote.php', { id: id, vote: vote }, function(data) {
if(data.success == true) {
apprise('Thank you for your vote!');
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured when voting for this deal. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('You have already voted for this deal!');
return false;
}
}
}, 'json');
return false;
});
$('#email-button').live('click', function() {
var emailAddress = $('.email-textbox').val();
var from = $('#from-textbox').val();
var message = $('#email-div').html();
var atpos = emailAddress.indexOf("#");
var dotpos = emailAddress.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= emailAddress.length) {
apprise('Please enter a valid email address!');
return false;
}
if(emailAddress == '') {
apprise('An email address is required!');
return false;
}
if(from == '') {
apprise('Your name is required!');
return false;
}
$.post('../service/service.emailDeal.php', { emailAddress: emailAddress, from: from, message: message}, function(data) {
if(data.success == true) {
apprise('The deal has been sent, we hope they enjoy it!');
return true;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured sending the email. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('An email address is required!');
return false;
}
}
}, 'json');
return false;
});
$('.comment-link').live('click', function() {
var id = this.id;
$.post('../service/service.loadComments.php', { id: id }, function(data) {
if(data.success == true) {
$('#content-container').html(data.results);
return true;
}
if(data.success == false) {
apprise('An error has occured retrieving the comments for this deal. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
}, 'json');
return false;
});
$('.post-comment-button').live('click', function() {
var id = this.id;
var comment = $('#comment-textarea').val();
var author = $('#post-comment-whois').val();
var swear = swearFilter(comment);
if(swear == true) {
apprise('Please remove the word "' + swear + '" from your comment.');
return false;
}
if(comment == '') {
apprise('Please fill out a comment first!');
return false;
}
$.post('../service/service.postComment.php', { id: id, comment: comment, author: author }, function(data) {
if(data.success == true) {
$.post('../service/service.loadComments.php', { id: id }, function(data) {
if(data.success == true) {
$('#content-container').html(data.results);
return true;
}
if(data.success == false) {
apprise('An error has occured retrieving the comments for this deal. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
}, 'json');
return false;
}
if(data.success == false) {
if(data.fail == 1) {
apprise('An error has occured while attempting to post your comment. ' +
'The error has been emailed to our support department to have the issue fixed, we apologize :(');
return false;
}
if(data.fail == 2) {
apprise('Please fill out a comment first!');
return false;
}
}
}, 'json');
return false;
});
});`
Use history.js to pushState and then window.history.back()