简体   繁体   中英

In Ajax response my if condition is not working

Check the jquery code bellow. Here after process post request the response returning no_file_found but if condition not meeting and not hitting alert() . Whats wrong i am doing here?

$("#btnFoo").on("click", function () {
            var file_data = $('#formUploadImg').prop('files')[0];
            var form_data = new FormData();
            form_data.append('file', file_data);
            form_data.append('ProId', $(this).attr("img-upload-product-id"));
            $.ajax({
                url: '/mycontroller/upload',
                dataType: 'text',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function (response) {
                    console.log(typeof response);//it returns string
                    if (response == "no_file_found") {
                        alert("this not hits");//this alert not hits
                    }
                    
                },
                error: function (response) {
                    alert("Error");
                }
            });
        });

Please note i am using c# mvc5 and the response is comming from mvc5 controller. Mvc5 example bellow:

[HttpPost]
public JsonResult upload()
{
    return Json("no_file_found");
}

You need to use .trim() function to make sure all unseen spaces are removed from the response to be able to match the exact comparison == of no_file_found .

Edit: The reason it is not working is because you are returning "no_file_found" with double quotes "" added. But on the front end you are checking simply no_file_found - You need to use replace function to make sure all the double quotes are deleted from the response .

 var response = '"no_file_found"'; if (response.replace(/["']/g, "").trim() == "no_file_found") { alert("this hits"); //this alert hits }

The problem here is that you are returning a Json value - but your ajax is set to have a dataType: 'text'.

If you change dataType: 'json' all works as expeceted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM