0

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!

2 Answers 2

2

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
    });

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

Comments

-1

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

1 Comment

what is variable : var, -1

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.