0

I'm not sure what's going on here, but the following code works perfectly by returning and logging my data:

function myFunction() {
  var itemArray = JSON.parse('<?php echo json_encode($items);?>');

  //console.log(itemArray);
  var promo_code = document.getElementById("promo_code").value;
  $.ajax({
       type:'POST',
       url:'validateCode',
       data:{promo_code:promo_code},
        _token: '{{ csrf_token() }}',
        success:function(data){
          console.log(data);           

        }
    });

  }

But as soon as I add function logic into my success block it says "myFunction() is not defined"

function myFunction() {
  var itemArray = JSON.parse('<?php echo json_encode($items);?>');

  //console.log(itemArray);
  var promo_code = document.getElementById("promo_code").value;
  $.ajax({
       type:'POST',
       url:'validateCode',
       data:{promo_code:promo_code},
        _token: '{{ csrf_token() }}',
        success:function(data){
          console.log(data);


          function(data){
            let results = [];
            $.each(itemArray, function(index1, value1) {
                let result = false;
                $.each(data.promo_codet_id.code.rule_type, function(index2,value2) {
                    if(value1.frame_number === value2.frame){
                        result = true;
                        break;
                    }
                });
                results.push(result);
            });
            console.log(results);
          }

        }
    });

  }

2 Answers 2

1

You should not re-declare the function again inside the function, just put this:

success:function(data) {
  console.log(data);
  let results = [];
  $.each(itemArray, function (index1, value1) {
    let result = false;
    $.each(data.promo_codet_id.code.rule_type, function (index2, value2) {
      if (value1.frame_number === value2.frame) {
        result = true;
        break;
      }
    });
    results.push(result);
  });
  console.log(results);
}
Sign up to request clarification or add additional context in comments.

Comments

0

function(data){ is missing the function name, also you're not calling it after declaring.

Additionally if you want to break out from $.each, you need to return false:

function getResults(data) {
  let results = [];
  $.each(itemArray, function(index1, value1) {
    let result = false;
    $.each(data.promo_codet_id.code.rule_type, function(index2, value2) {
      if (value1.frame_number === value2.frame) {
        result = true;
        return false;
      }
    });
    results.push(result);
  });
  return results;
}

const results = getResults();
console.log(results);

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.