0

If div with class Easy is present in the body, I want AJAX to run the url urlEasy.php If div with class Medium is present in the body, I want it to run urlMedium.php

Attempt Using Jquery Global Variable

<script>
var UrlReplacer = {};
$(document).ready(function() {
    if ($("div").hasClass("Easy")){    
    UrlReplacer = "urlEasy.php";
    } elseif ($("div").hasClass("Medium")){ 
    UrlRreplacer  = "urlMedium.php";
    }
});
</script>

<script type='text/javascript'>
$(document).ready(function () {
    $('#classadderform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({  
            url : Urlreplacer ,
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {
            },
        });
    });
});
</script>

The AJAX runs fine when I directly write the desired url as shown below, so the issue is not related to the form, the AJAX, or the linked urls. I also know with certainty that a div with class Easy is present in the body. The issue is creating a global Jquery variable that I can then use to define the url.

<script type='text/javascript'>
$(document).ready(function () {
    $('#classadderform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({  
            url : "urlEasy.php",
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {
            },
        });
    });
});
</script>
Snoops
  • 215
  • 1
  • 12

1 Answers1

1

Put those in the same script tag to avoid globals and any scope issues, and then check the selectors length to see if the element exists in the DOM

<script type='text/javascript'>
    $(document).ready(function () {
        var url = $("div.Easy").length > 0 ? "urlEasy" : "urlMedium";

        $('#classadderform').on('submit', function(e) {
            e.preventDefault();
            $.ajax({  
                url : url + '.php',
                type: "POST",
                data: $(this).serialize(),
                success: function (data) {

                },
            });
        });
    });
</script>
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Just out of curiosity, is there a way that I could do this using globals? I've never been able to get JQuery globals defined by an if condition to work and this seems like it would be a fitting example to use to learn how to do so – Snoops Sep 01 '17 at 16:25
  • You really shouldn't , but just for demonstration, something like this -> https://jsfiddle.net/zrzykr9g/ – adeneo Sep 01 '17 at 16:30
  • Thanks so much! Why do you advise against using the global variable method? – Snoops Sep 01 '17 at 16:32
  • https://stackoverflow.com/questions/2613310/ive-heard-global-variables-are-bad-what-alternative-solution-should-i-use – adeneo Sep 01 '17 at 16:38