Parsing PHP variables to javascript

or should I put it a better way, getting a php variable to javascript

Once a form has been submitted, I want to get a value of a variable to javascript, so it will execute a javascript function once the user has submitted the form once all the criteria on the form have been validated

This is basically my snippet of code

<script type="text/javascript">
function sent(e){
    var noerror = <?php echo json_encode($noErrors); ?>;
    if (noerror === 1){
        window.alert("Message sent");
} else {
    window.alert("No message received");
}
// troubleshooting code
    //document.write(noerror);
    }
    </script>

This is doing my head in for the last few years, can’t get my head around it

If noerror is an object (as it will be if the value given to it is a json_encoded string) then it can never be equal to 1.

The error @felgall rightly pointed out to you aside, I’d strongly suggest to use AJAX for this kind of data handling – muddling JS and PHP like this very unclean and potentially insecure. For example with jQuery:

HTML / JS

<form action="post.php">
    <input type="text" name="formInput" />
    <input type="submit" name="formSubmit" />
</form>

<script>
    $('form').submit(function(event) {             
        event.preventDefault();
        
        var url = $(this).attr('action'),
            formData = $(this).serialize();
        
        $.post(url, formData).success(function(phpData) {
            var returnObject = $.parseJSON(phpData);
            
            if (returnObject.noError) {
                alert('Successfully submitted "' + returnObject.formInput + '"');
            }
        });
    });
</script>

PHP

<?php
    $data = $_POST;

    // do some stuff
    $data['noError'] = true;

    echo json_encode($data);
?>

OK, that was because I was testing the json_encode out, but it still doesn’t work even with as a non object

@m3g4p0p, I will give that a go

this data variable, since I have a lot of other variables in the forms being processed, but not ‘noError’, just other data. The $noError variable is only firstly defined by the php, changed by the form when it has successfully validated all the fields that are required. I.e, the $noError variable isn’t being in the $_POST data by the form if you get what I mean

Does the variable get output correctly if you view source? If so then you’ve successfully exposed a php variable to javascript.

$data is an associative array here; it doesn’t matter whether 'noError' is also a key of $_POST or not (there is no $noError variable btw!). You might want to read about arrays in the PHP manual.

Anyway, this was just an example to demonstrate how to pass variables from JS to PHP and back to JS via AJAX. Of course, you can return whatever you want; e.g. if you omit the $data = $_POST; line, you’ll just return a JSON encoded object with the single property 'noError'.

It does get the right output

The script (original) seems to be working now, though not 100% correctly, maybe this has something to do with the validation of the fields in the PHP isn’t being updated correctly

What is happening is that, when I don’t fill in all the fields correctly, it says “Message sent”, obviously, the PHP validation picks up the error. When I correct the mistake, the javascript alerts me to say “Message not sent”, but the PHP picks up no errors and sends the message

Evidently, the variable $noError isn’t being updated correctly to get the javascript to display the correct window alert. I hope I am not bordering on PHP, as this is in the javascript forum

Slightly different javascript to the one I posted before
>

function sent(e){
    var noerror = <?php echo $noErrors; ?>;
    if (noerror === 0){
        window.alert("Message sent");
    } else {
        window.alert("Message not sent");
    }
}

It’s not allowing me to post the script

So it’s exactly the wrong way up? Maybe you’re setting noerror wrong then… :smile: try

if (noerror !== 1)

The variable will never get updated, you’ll execute the PHP script anew each time you call it (probably via action="foo.php", I suppose?).

Have you viewed the source of the generated JavaScript to see if the PHP has put the correct value there? That will tell you if the problem is in the PHP or in the JavaScript.

I have viewed the source on execution of the script and the console, it does update after execution, but every time I put an error and correct said error, the wrong alert message comes up. I did try put the script on the last post, but this site didn’t want to know

I do use the action=“contact.php” tag (validates through the same php page), is that what is causing the problem

You can get code to show on Sitepoint by either highlighting it and clicking the </> icon, or you can put three back ticks before and after your code (a back tick looks like an apostrophe and is usually at the top left of your keyboard)

<script type="text/javascript">
  function sent(e){
  var noerror = <?php echo $noErrors; ?>;
  if (noerror === 0){
    window.alert("Message sent");
  } else {
    window.alert("Message not sent");
  }

undefined, boolean, or string?

  var noerror = <?php echo $noErrors; ?>;
  console.log((typeof noerror);

It has already been defined before php validation, and it’s an integer

Can you post a copy of what the JavaScript looks like AFTER the PHP has run.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.