1

Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.

<form method="post" action="/membership-change-success" id="PaymentForm">
    <input type="hidden" name="planChosen" id="planChosen" value="" />
</form>

On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.

<script>
    var hash = window.location.hash;
    var currentPlan = "( < PLAN CHOICE > )";
    $(".planChoice").click(function(event){
          var isGood=confirm('Are you sure you want to change your plan?');
          var success;
          $("#planChosen").val($(this).data("plan"));
          $.ajax({
              url: '/ajax/planCheck.php',
              type: "POST",
              dataType: 'json',
              data: ({plan: $(this).data("plan")}),
              success: function (data) { //This is what is not working I can't get it to return true
                  success = data;
              }
          });
          if(success) {
              if (isGood) {
                  $("#PaymentForm").submit();
              }
              window.location = '/membership-change-success';
          } else {
              alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
          }
      });

My PHP for the ajax response looks like this.

    <?php

require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');

$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
    echo json_encode(true); // I've tried with out jason_encode too
} else {
    echo  json_encode(false);
}

And that's pretty much it if you have any suggestions please let me know.

So I've tried to do it another way.

      $(".planChoice").click(function (event) {
          var isGood = confirm('Are you sure you want to change your plan?');
          var success;

          $("#planChosen").val($(this).data("plan"));
          if (false) {
              if (isGood) {
                  $("#PaymentForm").submit();
                  alert('you did it');
              }
          } else {
              alert(isSuccessful($(this).data("plan")));
              //alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
          }
      });

and I have an ajax function

  function isSuccessful(plan) {
      return $.ajax({
          url: '/ajax/planCheck.php',
          type: "POST",
          dataType: 'json',
          data: {plan: plan}
      });
  }

The alert tells me this [object XMLHttpRequest]

any suggestions?

2 Answers2

3

$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response

     $.ajax({
          url: '/ajax/planCheck.php',
          type: "POST",
          dataType: 'json',
          data: {plan: $(this).data("plan")}
      })
      .then(function(success) {
          if (success) {
              $("#PaymentForm").submit();
          }
          // if `form` is submitted why do we need to set `.location`?
          // window.location = '/membership-change-success';
      } else {
          alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
      }
      }, function err(jqxhr, textStatus, errorThrown) {
           console.log(errorThrow)
      })
guest271314
  • 1
  • 15
  • 104
  • 177
  • The issue may be due to fact that there is no dom element with class `plainChoice` though `$(".planChoice").click...` is used in the code.Also there is a `$(this)` inside the ajax – brk Aug 11 '17 at 16:19
  • @brk That is possible. `$(this)` would reference the clicked element - if the elements exists - if not then we do we even get an error at `jQuery()` call before reaching `$.ajax()`? The answer is "no" https://jsfiddle.net/39Ltsg3s/ – guest271314 Aug 11 '17 at 16:23
  • @brk https://stackoverflow.com/questions/45639894/how-to-catch-when-a-selector-is-passed-to-jquery-that-does-not-exist-in-docume – guest271314 Aug 11 '17 at 16:35
  • I don't get any fatal errors. I just can't get it to successfully be true even though it should pass as true. either the POST isn't making it properly or the if isn't getting satisfied properly. – OverBakedToast Aug 11 '17 at 16:41
  • @OverBakedToast What does `console.log(success)` within `.then()` log? – guest271314 Aug 11 '17 at 16:45
  • I tried to do this and it just broke I'm not sure exactly why or why it doesn't give me any response but I'll post what I tried – OverBakedToast Aug 11 '17 at 16:56
  • Is there an element having `class` set to `"planChoice"` at HTML? Do you prevent the default action of `
    ` submission at `click` event handler of an `` element within `
    ` element?
    – guest271314 Aug 11 '17 at 16:59
  • I've tried the .done and the .then responses and my IDE says unresolved function or method done() / then() – OverBakedToast Aug 11 '17 at 17:32
  • There is a planChoice element in the HTML I just left it out because it functions properly. – OverBakedToast Aug 11 '17 at 17:36
  • I'm getting a [object XMLHttpRequest] now when I try to return the ajax function. – OverBakedToast Aug 11 '17 at 18:18
  • Here is your jsfiddle request but it's not really functional --- https://jsfiddle.net/#&togetherjs=dKhEGTKKzv – OverBakedToast Aug 11 '17 at 18:30
  • The code at jsfiddle is different from code at Question https://jsfiddle.net/n1kagr0v/ – guest271314 Aug 11 '17 at 23:58
0

You should use the following form for your ajax call

$.ajax({
    url: '/ajax/planCheck.php',
    type: "POST",
    dataType: 'json',
    data: ({plan: $(this).data("plan")}),
    success: success = data
    })
    .done(function(response) {
        if(success) {
            if (isGood) {
                $("#PaymentForm").submit();
            }
            window.location = '/membership-change-success';
        } 
        else {
          alert('Please make sure you deactivate your listings to the 
          appropriate amount before you Downgrade.')
        }
    });

the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.

mandy1339
  • 496
  • 3
  • 11