Jonathan
Jonathan

Reputation: 724

Calling a JS function via PHP

this is my JS:

function showErrorMsg() {
    modal.style.display = "block";
}

I want to call that function via php:

if(empty($from) || empty($first_name) || empty($last_name) || empty($_POST['message'])) {
    // CALL showErrorMsg();
}

The PHP line is called whenever I click a button in a mail-form, and it checks if any of the fields are empty.

I tried this:

if(empty($from) || empty($first_name) || empty($last_name) || empty($_POST['message'])) {
        echo "<script type='text/javascript'>showErrorMsg();</script>"
    } else {
        mail($to,$subject,$message,$headers);
        mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
        echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";

    }

But that gave me an HTTP 500 error..

The JS is in its own file called modal.js.

NOTE: The JS is basically just a example. There's alot more confusing stuff in it, so a JS function is needed. Just wanted to clarify this before someone came and gave me tips on how PHP can change style properties. ;)

Upvotes: 0

Views: 68

Answers (1)

Robert Schwindaman
Robert Schwindaman

Reputation: 182

As @hassan linked above in his comment,

What is the difference between client-side and server-side programming?

The problem here is a misunderstanding between a script that is executed server-side vs client-side. Javascript (except NodeJS) is a client-side language. This means it doesn't get executed by the server, and cannot run server code. It is executed by the browser. In other words, all of your Javascript runs immediately AFTER your PHP script(s) complete.

This means that you need to output the Javascript in a way that uses a click listener to invoke an AJAX request to your PHP (server) by sending an HTTP request to one of your other PHP files.

Upvotes: 1

Related Questions