1

I want to check some user inputs with an if statement and depending on them, specify some parameters to send as an ajax request.

My approach doesn't work at all. It's just not valid code:

$.ajax({
    method : "GET",
    url : "test.php",
    data :
        if (...) {
            a: "abc",
            b: "def"
        }else{
            b: "ghi",
            c: "jkl"
        },
    success : function(data) {
        console.log(data)
    },
    error : function(data) {
        console.log(data);
    }
});

Does anybody have a better idea?

2 Answers 2

5

I think the cleanest way is to place your condition before the request call :

var data;

if (...) {
    data = {a: "abc",b: "def"};
}else{
    data = {b: "ghi",c: "jkl"};
}

$.ajax({
    method : "GET",
    url : "test.php",
    data : data,
    success : function(data) {
        console.log(data)
    },
    error : function(data) {
        console.log(data);
    }
});

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

You may use a self executing function to set data as:

var i = true;
$.ajax({
  method: "GET",
  url: '/echo/js/',
  data: (function() {
    if (i)
      return { a: "abc", b: "def" }
    else
      return { b: "ghi", c: "jkl" }
  })(),
  complete: function(response) {
    console.log(response)
  },
  error: function() {
    console.log("Error")
  },
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.