Mooseman
Mooseman

Reputation: 18891

JS Variable in jQuery ajax data

jQuery:

function myajax(var){
  $.ajax({
    url : 'ajax.php',
    type : 'POST',
    dataType : 'html',
    data: {
      if(undefined != var){ variable : var, }
      content : $("#myinput").val()
  }
}

However, when calling the above function, the console shows Unexpected token ( for the line with the if. How can I do this successfully? Thanks!

Upvotes: 0

Views: 3312

Answers (2)

Vamsi Abhishek
Vamsi Abhishek

Reputation: 137

You can actually do the validation in "beforeSend"

function myajax(var){
  var requestData;
  $.ajax({
    url : 'ajax.php',
    type : 'POST',
    dataType : 'html',
    data: requestData,
    beforeSend : function(xhr){

      requestData = $("#myinput").val();
  }
}

Something like this might solve your problem

Upvotes: -1

epascarello
epascarello

Reputation: 207501

You have an if statement inside of an object! You can not do that.

Move the logic outside of the object.

function myajax(var) {

    var data = {
        content: $("#myinput").val()
    };
    if (undefined !== var) {
        data.variable = var;
    }
    $.ajax({
        url: 'ajax.php',
        type: 'POST',
        dataType: 'html',
        data: data
    });

}

Upvotes: 2

Related Questions