-1

I have the following ajax code:

<script type='text/javascript'>
$(document).ready(function () {
    $('.questionform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({  
            url :  "aplaygroundajaxtest.php",
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {     
 '<?php
if($data3["{$QuestionType}Percent"]<100){ ?>' alert("Alert Message OnClick"); '<?php ;} ?>'
            },
        });
    });
});
</script>

If the value in column {$QuestionType}Percent is less than 100, I want it to alert a message. However, it does not work. the source code shows the following:

<script type='text/javascript'>
$(document).ready(function () {
    $('.questionform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({  
            url :  "aplaygroundajaxtest.php",
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {     
 '' alert("Alert Message OnClick"); ''
            },
        });
    });
});
</script> 

I've tried escaping the " with \ and I've also tried double quotes around the php (in which case, the PHP still disappears in the source code, leaving empty double quotes).

I know that the issue does not lie with $data3["{$QuestionType}Percent"]<100 as it functions correctly elsewhere in my code - and the value in the column is indeed less than 100.

EDIT / UPDATE ---------------------------------------------->

The issue was two-fold: 1) I needed to get rid of the single quotes around PHP tags; 2) it wasn't receiving the value of $data3["{$QuestionType}Percent correctly.

In the URL to which the form posts (aplaygroundajaxtest.php), I corrected the latter issue; now, I'm using the variable $QuestionTypePercent. In the code below, print_r($QuestionTypePercent); shows 14 in the source and the if condition is correctly interpreted. The source shows 14 alert("Alert Message OnClick"); and I get the error Uncaught SyntaxError: Unexpected identifier. When I remove print_r($QuestionTypePercent); the error goes away and the code works. Why is print_r($QuestionTypePercent); interfering with my alert in the code below?

<script type='text/javascript'>
$(document).ready(function () {
    $('.questionform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({  
            url :  "aplaygroundajaxtest.php",
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {        
  <?php
print_r($QuestionTypePercent); // RETURNS 14 CURRENTLY
          if($QuestionTypePercent < 100){?>
                alert("Alert Message OnClick"); //REDIRECTSME TO aplaygroundajaxtest.php
                <?php } ?>

            },
        });
    });
});
</script>
Snoops
  • 215
  • 1
  • 12
  • 1
    Have you tried removing the `'` before and after your `` tags? – lucidiot Jul 12 '17 at 00:39
  • Why are you wrapping it in php in the first place? – guradio Jul 12 '17 at 00:40
  • @guradio I'm wrapping it because `if($data3["{$QuestionType}Percent"]<100){` is interpreting a column from MYSQL database – Snoops Jul 12 '17 at 00:41
  • @Lucidiot I started with that but, in that case, the PHP condition disappears entirely from the source. In other words, it alerts even if the percentage in that column is greater than 100. – Snoops Jul 12 '17 at 00:42
  • 3
    @Snoops: I think you're fundamentally misunderstanding how server-side and client-side code works. The PHP isn't disappearing, it's *executing*. What you see in the browser is the *result* of that execution. You should never see the PHP code in the browser, that would mean the server isn't working. – David Jul 12 '17 at 00:43
  • if the alert is not in the page then `if($data3["{$QuestionType}Percent"]<100` is not true. `$data3["{$QuestionType}Percent"]` is an unusual variable name, i would start by checking that –  Jul 12 '17 at 00:50
  • an `alert()` can not redirect you, something else is going on –  Jul 12 '17 at 02:35
  • @rtfm I get this error: `Uncaught SyntaxError: Unexpected identifier` at the alert line – Snoops Jul 12 '17 at 02:37

3 Answers3

1

If you want to remove the single-quotes, then remove the single-quotes. (You also have an errant semi-colon to remove.) Instead of this:

'<?php if($data3["{$QuestionType}Percent"]<100){ ?>' alert("Alert Message OnClick"); '<?php ;} ?>'

You want this:

<?php if($data3["{$QuestionType}Percent"]<100){ ?> alert("Alert Message OnClick"); <?php } ?>

The PHP code is functioning just fine, as you can clearly see in your output. But outside of the PHP code you have random single-quotes that don't belong there. PHP never touches those, it just outputs whatever's on the page that you put there.

David
  • 208,112
  • 36
  • 198
  • 279
  • Thank you for your reply. When I do that, however, the entire line `<>php if($data3["{$QuestionType}Percent"]<100){ ?> alert("Alert Message OnClick"); disappears from the source code and it doesn't run. – Snoops Jul 12 '17 at 00:46
  • @Snoops: What do you mean by "disappears from the source code"? How are you *examining* the source code? If you're looking at the resulting page in the web browser, then you're not *supposed* to see the PHP code there. PHP doesn't run in the browser, it runs on the server. – David Jul 12 '17 at 00:48
  • In playing with the code a bit more, it does appear to work, but only when I used `< 100`. In this case, `view source` shows `alert("Alert Message OnClick");`. If I change `< 100` to `> 0`, however, the code stopps working and `alert("Alert Message OnClick");` disappears from the source. For reference, the value in the `{$QuestionType}Percent` column is 33, so it should work with either. Any ideas why it would work with `<` but not `>`? – Snoops Jul 12 '17 at 00:57
  • @Snoops: If the code within the `if` block isn't executing then one can only conclude that the condition is `false`. You should check whatever assumptions you're making about the code and/or runtime values. I assure you, both the `<` operator *and* the `>` operator are successfully implemented in the PHP language. It's *far* more likely that you're making a false assumption somewhere than that PHP itself is somehow broken. – David Jul 12 '17 at 01:00
  • I've played around with it a bit more. Any time, I use a `<` symbol, `alert("Alert Message OnClick");` appears in `view source` even if the condition is not met. Both `<5` and `<100` show `alert("Alert Message OnClick");` in the source code. Any time I change this to a `>` symbol, `alert("Alert Message OnClick");` disappears from my source code. – Snoops Jul 12 '17 at 01:02
  • 1
    @Snoops: With all your "playing around", you might want to actually check the values being compared in your condition. Things like `var_dump` and `print_r` in PHP are very useful for that. https://stackoverflow.com/questions/3406171/php-var-dump-vs-print-r Stop trying to figure out how PHP comparison operators are broken. They're not. Instead, focus on your own logic and assumptions and find where *you* have made an error. – David Jul 12 '17 at 01:04
  • In my "playing around", I am looking at the values. I have the mysql table open right in front of me and I refresh it every time I reload my page. – Snoops Jul 12 '17 at 01:05
  • 1
    @Snoops: But you're *not* looking at your actual runtime PHP values. Given that the logic error you're trying to find is in your PHP code, that seems like a more reasonable place to look. I can't stress this enough... Stop assuming that the rest of your code *must be* flawless and correct and that PHP's comparison operators *must be* broken. The opposite is infinitely more likely. – David Jul 12 '17 at 01:07
  • 2
    @Snoops: Specifically, put something like `print_r($data3["{$QuestionType}Percent"])` just before that `if` block in your PHP code. Then see what it outputs to the page source. – David Jul 12 '17 at 01:10
  • 2
    `var_dump($data3["{$QuestionType}Percent"])` would give a more useful result –  Jul 12 '17 at 01:13
  • 1
    Heck, do both. Couldn't hurt. The point is, examine the value instead of assuming the value. – David Jul 12 '17 at 01:14
  • @David Thank you for your suggestion. There was, indeed, an issue with the value. I corrected that issue (the `if` condition is correctly interpreted), but the alert redirects me to my form's URL instead of displaying an alert on the page. I gave a detailed edit / update on this issue in the original post. I feel like there's a small syntax error in the alert that I need to fix but I can't figure out the issue. If you could help me out with this last issue, I would greatly appreciate it! – Snoops Jul 12 '17 at 02:28
  • @Snoops: An `alert()` won't perform a redirect. The details in the question seem to just talk about a syntax error from the debugging output. That is correct, just outputting values wouldn't produce correct JavaScript code. It was used just for debugging so you could see what your actual runtime value was. Now that you've seen it, you can remove that debugging output. (Or, if you want to keep it, output it to valid JavaScript code such as a variable declaration or something.) – David Jul 12 '17 at 09:29
0

Remove the

'

This should work

<script type='text/javascript'>
    $(document).ready(function () {
        $('.questionform').on('submit', function (e) {
            e.preventDefault();
            $.ajax({
                url: "aplaygroundajaxtest.php",
                type: "POST",
                data: $(this).serialize(),
                success: function (data) {
                    <?php
                    if($data3["{$QuestionType}Percent"] < 100){ ?>
                    alert("Alert Message OnClick");
                    <?php } ?>
                }
            });
        });
    });
</script>
Kevin P
  • 601
  • 3
  • 9
  • Thanks for your help, Kevin. This works....sometimes. The value in the `{$QuestionType}Percent` column is currently 33. When I copy the code exactly as you wrote it, the alert pops up; when I change `< 100` to `>0`, however, the code disappears from my source and it stops working. I am perplexed by this. why would the code misinterpret the `>` but not the `<`? – Snoops Jul 12 '17 at 00:53
-2

I have suggestions for you,

First, separate the PHP from your jquery not to make it messy, like this:

<?php
$ques = 0;
if($data3["{$QuestionType}Percent"]<100){ 
  $ques = 1;
}
?>  
<input type="hidden" value="<?php echo $ques; ?>" id="questype"/>
<script type='text/javascript'>
$(document).ready(function () {
$('.questionform').on('submit', function(e) {
    $.ajax({  
        url :  "aplaygroundajaxtest.php",
        type: "POST",
        data: $(this).serialize(),
        success: function (data) {      
           if( document.getElementById('questype').value == 1){
                alert("Alert Message OnClick");
           }
        }
    });
    e.preventDefault();        
   });
  });
 </script>

Or else, just echo out the alert if the if statement is true.

    $.ajax({  
        url :  "aplaygroundajaxtest.php",
        type: "POST",
        data: $(this).serialize(),
        success: function (data) {     
          <?php
           echo "if($data3['{$QuestionType}']Percent < 100 ){ 
            alert('Alert Message OnClick'); 
           }"; 
          ?>
        }
    });

Take note that this file is .php, therefore prior code is the php.

smzapp
  • 809
  • 1
  • 12
  • 33
  • The latter one is exactly what I'm looking for, but it completely ignores the PHP `if` condition. It runs the alert regardless of the value in the column. – Snoops Jul 12 '17 at 01:07
  • so you mean, you want a jquery if statement rather than PHP? that was your question though – smzapp Jul 12 '17 at 01:09
  • Edited my answer. Please check the second solution on if. – smzapp Jul 12 '17 at 01:15
  • @smzvax: `if($data3['{$QuestionType}Percent']<100)` is *server-side* code, what exactly is that change meant to do? – David Jul 12 '17 at 01:16
  • yeah it is a server-size. It will be translated into a jquery code. and jquery will execute the result of `if($data3['{$QuestionType}Percent']<100)`. – smzapp Jul 12 '17 at 01:18
  • @smzvax: That's... not how server-side and client-side code work. JavaScript isn't going to know what to do with a PHP variable. You can find considerably more information on the subject here: https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming – David Jul 12 '17 at 01:21
  • what is the value of `$data3['{$QuestionType}']` then? if this is a string, then it will be converted to something like `if(stringPercent<100)` and jquery can interpret this if `stringPercent` has a value. Check my edit – smzapp Jul 12 '17 at 01:25
  • @David .. I know server-side and client-side. I've been into web dev more than 5 years. I thought you were the one who asked the question and why you kept on checking my revisions though. – smzapp Jul 12 '17 at 01:32