-1

I know this is very basic question but

Is this a good practice although code works fine?

I'm working on mvc project and i just need to confirm wether it is a good practice to do this or not?

code .cshtml

$(document).ready(function () {
    var serviceURL = '/AjaxTest/FirstAjax';
    if(serviceURL = null ) { alert ("BANG! error")}
    else {
        $.ajax({
                type: "POST",
                url: serviceURL,
                data: param = "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc,
                error: errorFunc
        });
    }
}

please share your comments.

tereško
  • 58,060
  • 25
  • 98
  • 150
Neo
  • 15,491
  • 59
  • 215
  • 405
  • Is it good practice to confirm that you have data before you attempt to do something that requires it be set? Is this not a little self explanatory? ;-) – David Barker Sep 18 '13 at 16:28
  • yes you can call ajax in else part also there is no any restriction when you call ajax method. it's just depend on how to make more interactive your code. – luckyamit Sep 18 '13 at 16:29
  • well i'm just an beginner .. and try to know few things which i can't find it on google thanks :) – Neo Sep 18 '13 at 16:36
  • possible duplicate of [Ajax call Into MVC Controller- Url Issue](http://stackoverflow.com/questions/9988634/ajax-call-into-mvc-controller-url-issue) – Neo Sep 18 '13 at 16:41

1 Answers1

2

I'm a big fan of one function per function. If you're routing logic, there's no reason NOT to "hide" that ajax call in a function:

$(function () {
     var serviceURL = '/AjaxTest/FirstAjax';
     if(serviceURL != null ) { 
         CallServiceAsync(serviceUrl);
     else {
         alert ("BANG! error")} 
     }
}

function CallServiceAsync(serviceUrl) {
   $.ajax({
                type: "POST",
                url: serviceURL,
                data: param = "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc,
                error: errorFunc
            });
}

I like to keep lengthy object calls hidden away for code readability

Jaime Torres
  • 10,365
  • 1
  • 48
  • 56
  • thanks a lot this make sense to me .. perfect answer given rather to just made some comments :) – Neo Sep 18 '13 at 16:35