Regha Putra
Regha Putra

Reputation: 35

Why my ajax call only not working on the first time? but working on the next call

this is my web API method :

[HttpPost]
    public ActionResult InsertCompany(Company value)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~")));
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = client.PostAsJsonAsync($"{WebConfigurationManager.AppSettings["URL"]}/Company/InsertCompany", value).Result;
            if (response.IsSuccessStatusCode)
            {
                return Json(new { success = true, responseText = "Data berhasil ditambahkan!" }, JsonRequestBehavior.AllowGet);
            }
        }

        return Json(new { success = false, responseText = "Data gagal ditambahkan!" }, JsonRequestBehavior.AllowGet);
    }

and this is my ajax call :

function PostData() {
$.ajax
({
    url: 'InsertCompany',
    type: 'POST',
    dataType: 'json',
    data: {
        CompanyName: $('#CompanyName').val(),
        JoinDate: GetDateTimeNow()
    },
    success: function (response) {
        if (response !== null && response.success) {
            location.reload();
            alert(response.responseText);
        }
        else {
            alert(response.responseText);
        }
    },
    error: function (response) {
        alert('error: ' + response.responseText);  // 
    }
});
}

this is how I call the ajax :

$('#btnSubmit').click(function () {
PostData();
});

this is GetDateTimeNow() method :

function GetDateTimeNow()
{
var date = new Date();
var day = date.getDate();       // yields date
var month = date.getMonth() + 1;    // yields month (add one as 
'.getMonth()' is zero indexed)
var year = date.getFullYear();  // yields year
var hour = date.getHours();     // yields hours 
var minute = date.getMinutes(); // yields minutes
var second = date.getSeconds(); // yields seconds

// After this construct a string with the above results as below
var time = day + "/" + month + "/" + year + " " + hour + ':' + minute + ':' 
+ second; 
return time;
}

this is my html element :

<button type="submit" class="btn btn-primary" id="btnSubmit">Submit</button>
<input type="text" class="form-control" id="CompanyName" placeholder="Enter Company Name">

this is response for the first time i call ajax:

error: undefined

and this is the second response and so on for the ajax call :

Data berhasil ditambahkan!

my question is why my ajax call not success only on the first time I call after load page? but success on the second time and so on, any idea what happen?

Upvotes: 2

Views: 3884

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

Two changes needed:-

1.Use e.preventDefault();:-

$('#btnSubmit').click(function (e) {
   e.preventDefault();PostData();
});

2.Check that company name not empty then only do the ajax call:-

function PostData() {
   if($.trim($('#CompanyName').val()) != ''){
   //put your complete ajax call code inside it
   }
}

Note:-

problem arise when you hit submit without checking company name is having value or not? an empty data goes via ajax call and you got undefined.

preventDefault() is just use to stop normal posting(Page refresh) of the form (if you have), when you click button.

Upvotes: 1

Related Questions