The $.Ajax success method is ineffective in ASP MVC

I have gone through multiple posts on this topic, but unfortunately I am unable to resolve my issue. It seems quite challenging for me: I am facing an obstacle with a simple C# code that is supposed to retrieve the tracking status of a submitted factor in the ShoppingController class. Here is the code snippet:

  public string StatusOfFactor( string guid )
    {
        // note that guid was being trimmed in javascript

        Factor factor = (from Factor fact in db.Factors
                         where fact.TrackingCode.ToString() == guid
                         select fact).First();
        return factor.StatusOfFactor;

Additionally, I have a JavaScript function that calls this method as shown below:

function TrackPurchase() {
    var txtTrackingPurchase = $("#inputpeygiry");
    var guid = $.trim(txtTrackingPurchase.val());
    var urlMain = 'ShoppingController/StatusOfFactor';
    alert(urlMain);

    $.ajax({
        type: 'GET',
        url: urlMain,
        cache: false,
        data:  guid,
        success: function (returnVal) { 
            alert("I am sucess function");
            $("#StatusOfFactor").html(returnVal);

        },
        error: function (e) {
            $("#StatusOfFactor").text("nothing is really exist");
        }
    });    
}

Please note that there is a textbox with id="inputpeygiry" which captures the tracking code entered by the user. The above JavaScript function is triggered upon clicking the button below:

  <input type="button" class="btn btn-success pull-left" id="btnpeygiry" value="Track Purchase" onclick="TrackPurchase()"/>

The main issue at hand is that the success function never gets called! Can someone please assist me in resolving this dilemma?

Answer №1

Are you using jQuery version 3.0 or above? If so, callback methods have been removed in this version. You can utilize jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead for handling your AJAX requests.

For more information, please refer to the documentation of jQuery Get

$.ajax({
    type: 'GET',
    url: urlMain,
    cache: false,
    data:  guid,
})
.done(function (returnVal) { 
    alert("I am sucess function");
    $("#StatusOfFactor").html(returnVal);

}).
fail(function (e) {
    $("#StatusOfFactor").text("nothing is really exist");
});

Answer №2

To get everything working properly, switch the GET method to POST.

Update the controller code to:

[HttpPost]
public string CheckFactorStatus( string trackingCode )
{
    // Ensure that the tracking code is trimmed in JavaScript
    Factor factor = (from Factor fact in db.Factors
                     where fact.TrackingCode.ToString() == trackingCode
                     select fact).First();
    return factor.StatusOfFactor;
}

Modify the JavaScript code as follows:

function VerifyPurchase() {
var txtTrackingPurchase = $("#inputpeygiry");
var trackingCode = $.trim(txtTrackingPurchase.val());
var urlMain = 'ShoppingController/CheckFactorStatus';
alert(urlMain);
    $.ajax({
        type: 'POST',
        url: urlMain,
        cache: false,
        data:  trackingCode,
        success: function (returnVal) { 
            alert("Success! Function executed");
            $("#StatusOfFactor").html(returnVal);

        },
        error: function (e) {
            $("#StatusOfFactor").text("Unable to retrieve information.");
        }
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying JSON information using AngularJS

Hi there! I'm displaying some sample data retrieved from the server using AngularJS. In this code snippet, I have utilized the GetNames() function within ng-init. Is it appropriate to call this function in ng-init in order to display data when the pa ...

Combine and store downloaded stylesheets in the browser into a single file

My task involves transforming a website page along with all its external stylesheets into a single HTML file with inline CSS. This is not for usage in emails, but rather to incorporate styled sections of that page into another website's page. After so ...

HTML5 Boilerplate and optimizing the critical rendering path by deferring scripts and styles

Previously, I constructed my website layouts using the HTML5 Boilerplate method: incorporating styles and Modernizr in the head section, jQuery (either from Google CDN or as a hosted file) along with scripts just before the closing body tag. This is an exa ...

Avoiding Multiple Clicks on Anchor Tags in AngularJS

After implementing the sharing functionality, I have noticed that it works fine but there is a repeating issue with the user list. Every time the 'a' tag is clicked multiple times, the user list gets repeated. Can someone guide me on how to resol ...

AJAX fails to retrieve a result

I've been attempting to grasp the concept of using ajax, but unfortunately I have not been able to receive any response. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta ...

I'm confused about what I did wrong with Node.js. The server.js is up and running, but I'm unable to view the

I have made some progress so far and I am currently running this code on Putty. var http = require('http'); var fs = require('fs'); const PORT = 8080; http.createServer(function(request, response) { var url = request.url; switc ...

Using AJAX to call a PHP class that extends, the included classes are not being passed along

When trying to call a function through AJAX from a PHP class that extends another class, I encountered an issue. The class being extended was not included in the same file but rather in a separate one. Here's a breakdown of my code: Client: $(' ...

How can we invoke a page method in ASP.NET Web Forms using a "GET" request?

Is it possible to call page methods in ASP.NET Web Forms using a "GET" request? Currently, I am able to call the page method using an Ajax "POST" request, but I am struggling to do so with a "GET" request. Could you please provide some suggestions or exam ...

How can HtmlUnit be used to identify and address website pages that display errors?

I've encountered an issue while trying to access this Ajax page through my Java program using the HtmlUnit 2.15 API. It seems that the problem arises from a broken link to a missing file located here. This is the snippet of code I'm working with ...

Strange Actions with JQuery Drag-and-Drop Functionality

Apologies for my limited experience with JQuery UI, but I am in the process of creating a web-based chess engine for 2 players using JavaScript. Instead of point and click, I have decided to implement a user-friendly drag and drop feature for non-mobile us ...

What are the best ways to keep a django page up to date without the need for manual

Currently, I am in the process of developing a Django website focused on the stock market. Utilizing an API, I am pulling real-time data from the stock market and aiming to update the live price of a stock every 5 seconds according to the information pro ...

Using Node.js to separate applications on the same URL based on different paths

We currently have a server hosting one domain, where we have placed apps separately using specific URL paths. For instance, the front-end of our app is mapped to the main URL (/). Requests to / will be directed to the front-end app, while adding /api in ...

Numerous animated elements within A-frame

Is there a way to incorporate animation into an A-Frame glTF model, causing it to smoothly move 5 spaces to the left and then 5 spaces forward? Below is my current code: <a-gltf-model color="#FFFFFF" width="1" height="1" de ...

Separate repositories used to integrate HTML/CSS and JavaScript MVVM framework in Git workflows

At this point in my project, there is a specific scenario that I am facing: We are utilizing one repository (r1) for the HTML/CSS development work by our UI designer, along with some minimal JavaScript. I have cloned this repository r1 to my local system ...

Tips for redirecting a page in React by forcing a route

Attempting to implement the guidance from this Stack Overflow solution on how to "go back home" after closing a Modal... import React, { Suspense, useState } from 'react'; import { BrowserRouter, Route, Switch, useHistory } from "react-route ...

Animating a progress bar with JQuery

Having issues with displaying a progress bar using jquery and javascript, as it is not appearing on the page. var show_time = Math.floor(Math.random() * 10000) + 5000; setTimeout(function() { $("#progress").hide() }, show_time); var myCountdown = $( ...

Is it possible to incorporate an automatic medication name suggestion feature into my EHR system by leveraging the databases available through [MedlinePlus, Dailymed, NLM, RxNorm]?

Currently faced with a challenge in developing an Electronic Health Record (EHR) system. Specifically, I am struggling to implement the medication autocompleting functionality where users can type in a medication name in an input box. I intend to utilize ...

The type {properties .....} is incompatible with the type ActionReducer<AdminState, Action> in Angular 12 using NGRX

Implementing NGRX library for redux to organize the state of the application in a structured way: export interface ApplicationState { adminState: AdminState } export interface AdminState { adminProductCategory: ProductCategoryState; adminProdu ...

jQuery JSON ajax response problem with knockout.js data binding

I've encountered an issue where a code example working with static JS-based JSON formatted data fails to work when the same data is parsed through Ajax. HTML CODE: <table> <thead> <tr><th>File Name</th>< ...

Are you familiar with using double conditional rendering in a React application?

Currently, I am in the process of creating a small clothing store application using React as a way to expand my skills. One feature I have implemented is a filter by price section. However, I am looking for a solution to handle cases where no items fall wi ...