Tharu
Tharu

Reputation: 353

How to change url of ajax function depending the return value of beforesend() function?

I want to run a function inside beforesend() in jquery ajax. Depending on the return value of that function I want to change the URL of ajax request. For an example refer below.

If myFunction() returns a value grater than 1, I want to run url1 otherwise I want to run url2. How to achieve that?

myFunction() gives a value grater than 1. But always ajax runs the url2.

$.ajax({
    type: "POST",
    data: {
        fname: $('#com').val()
    },
    dataType: "json",
    beforeSend: function () {
        myFunction($('#com').val())
    },
    url: (myFunction($('#com').val()) > 1) ? url1 : url2,
    success: function (data) {
        if (data == 'success') {
            window.location.href = 'index.php?r=site/index';
        } else {
            alert("Already registered email");
        }
    },
    failure: function (errMsg) {
        alert(errMsg);
    }
});

Upvotes: 2

Views: 2003

Answers (3)

Nijat Asad
Nijat Asad

Reputation: 441

$.ajax({
    type: "POST",
    data: {
        fname: $('#com').val()
    },
    dataType: "json",
    beforeSend: function () {
        url = myFunction(parseInt($('#com').val())) > 1 ? url1 : url2;
    },
    url: url,
    success: function (data) {
        if (data == 'success') {
            window.location.href = 'index.php?r=site/index';
        } else {
            alert("Already registered email");
        }
    },
    failure: function (errMsg) {
        alert(errMsg);
    }
});

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Create a global variable something like:

var urlToSend;

and then assign it in beforeSend

$.ajax({
    type: "POST",
    data: {
        fname: $('#com').val()
    },
    dataType: "json",
    beforeSend: function () {
        urlToSend=myFunction($('#com').val()) > 1 ? url1 : url2;
    },
    url: urlToSend,
    success: function (data) {
        if (data == 'success') {
            window.location.href = 'index.php?r=site/index';
        } else {
            alert("Already registered email");
        }
    },
    failure: function (errMsg) {
        alert(errMsg);
    }
});

Upvotes: 0

Ankush Jain
Ankush Jain

Reputation: 7069

try this

$.ajaxSetup({
    beforeSend: function(jqXHR, settings) {
       settings.url ="new Url";
    }
});

Upvotes: 1

Related Questions