Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    May 2012
    Posts
    89
    Thanks
    51
    Thanked 0 Times in 0 Posts

    Using a conditional within an ajax request?

    Hi

    I have an ajax request, and want to set up a conditional within it based on a variable that was sent to the ajax function (inputSwitch), but am not getting the syntax correct. Here's the first part of the request:



    $.ajax({
    type: "POST",
    url: "mypage.php",

    data: {post1:var1, post2:var2, post3:var3},


    What I want is for the data object to be...

    data: {post1:var1, post2:var2},

    So..

    if (inputSwitch == 'method1') {

    data: {post1:var1, post2:var2, post3:var3},
    }

    else {

    data: {post1:var1, post2:var2}
    }


    ...but javascript doesn't seem to like conditionals within ajax requests.

    I tried setting up a conditional at the start of the function before the request, putting each object within a var, and then placing the correct var in the data object, but that's no go either.

    Can someone please explain the correct syntax, or if it can be done at all?

    Thanks for your time and help.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    Quote Originally Posted by shaunthomson View Post
    I tried setting up a conditional at the start of the function before the request, putting each object within a var, and then placing the correct var in the data object, but that's no go either.
    Show us this code because it's a good idea to do this. There must be something wrong with it.

  • #3
    New Coder
    Join Date
    May 2012
    Posts
    89
    Thanks
    51
    Thanked 0 Times in 0 Posts
    Thanks Devnull

    Here's the Ajax that's working:

    data: {post1:var1, post2:var2, post3:var3},

    and here's what I'd like to do:

    (var dataVar is created in same function, but before Ajax code

    var dataVar = "{post1:var1, post2:var2, post3:var3}"

    data: dataVar,


    That syntax doesn't work - is there something obvious I'm doing wrong?

  • #4
    New Coder
    Join Date
    May 2012
    Posts
    89
    Thanks
    51
    Thanked 0 Times in 0 Posts
    Never mind mate - I took the quotes off so that it's not a string. I didn't realise you could just place an object into a var without it being a string.

    Thanks for taking a look.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •