Calling a JS function via PHP - javascript

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. ;)

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.

Related

Javascript call php header [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
I have the following javascript code:
function like(){
if(loged) {
if(liked) {
likes-=1;
liked = false;
document.getElementById('alike').src = "img/icons/like.png";
} else if(disliked) {
dislikes-=1;
disliked = false;
likes+=1;
liked = true;
document.getElementById('alike').src = "img/icons/like1.png";
document.getElementById('adislike').src = "img/icons/dislike.png";
} else {
likes+=1;
liked = true;
document.getElementById('alike').src = "img/icons/like1.png";
}
} else {
<?php header("Location:login");?>
}
}
I want to redirect the user to the login page how can i user php inside javascript to this. I do not want to have to use any other things like ajax etc. Thanks.
You do not need to use PHP header() to redirect with JS. You can simply use the window.location property:
window.location.href = "your_url";
//or
window.location = "your_url";
//or
location.href = "your_url";
//or
location = "your_url";
As mentioned in the other comments, to redirect in javsascript you want to use something like window.location.href = "your_url";.
Here's a bit of extra information as well to help you out in the future, as you seem to have misunderstoon the relationship between PHP and JavaScript.
In a nut shell, you can't call PHP functions from javascript. PHP code and javascript code run at two very different times in the request cycle. PHP is run by the server and JavaScript is run by the client (browser)
PHP
When you load a webpage a request will be sent by your client (browser) to a server, which receives it and returns a response.
PHP runs on the receiving server and it's job, very simply put, is to generate a response to send back to the browser. So it may generate html, javascript, etc.
You can use PHP to output html for example <?php echo 'Hello world'; ?>.
Once PHP has sent it's response that's it, it's game over for PHP.
HTML and JavaScript
The requesting browser will receive the response that the server sent and will then handle it. For HTML it will render a page and any JavaScript will be run.
Javascript can't interact with the PHP in anyway at all, since the PHP code was run on the server, while the javascript runs on the client.
It's important to understand the different between client and server, otherwise you'll find yourself running into similar problems going forward :)

Button On click call jquery function and acess php

I am very new to Wordpress and Woocommerce. I have few doubts wrt jquery in Wordpress. Say i have a function
function test(){
alert("test");
<?php
error_log("Test ---------------------------- ", 0);
?>
}
and a button:
<input type="button" id="btnclick" onclick="test();" value="Test" />`
error log is printing on page load but not on click. But i want to execute code inside php block only when user clicks on button.Is there a way to achieve this ? Thanks in advance`
jPO has already explained how to solve this in a good way, but I thought I should explain why this happens.
PHP is executed on the server. Once the page has been sent to the client, the PHP is no more. JavaScript happends on the client, and can be executed as long as the user is viewing the webpage. Since they do not live during the same timeperiod they are not aware of each other and can not be mixed in that way.
When you visit the page in your browser, the browser sends a request to the server. On the server the PHP interpreter goes through the code of the requested page, executing everything between <? and ?>. It does not understand what the other stuff around it is - it could be HTML, JS, plain text, anything, the PHP interpreter does not know and does not care. That is why it writes to the error log on page load.
When the PHP interpreter is done it has produced a document looking like this:
function test(){
alert("test");
}
That is sent to the client, and the JS (without any instruction to write to the error log) is run on the client when the button is pushed.
Not possible like that. If you'd like to do so. You need something like ajax method in php which you can call. Let's say you have a file in the root of your project called ajax.php, there you can define a function named test(), then you have to have a $_REQUEST translator, which calls your function test(), so the ajax.php would look like this
<?php
// checks if you sent a parameter named method and calls the method
// if you provide parameter named params it will send them too
if(isset($_REQUEST)){
if(isset($_REQUEST["params"]))
ajax($_REQUEST["method"],$_REQUEST["params"]);
else
ajax($_REQUEST["method"]);
}
function ajax($function,$data = null){
$function($data);
}
function test(){
error_log("Test ---------------------------- ",0);
}
and your ajax would look like this
function test(){
$.ajax({
url:"ajax.php",
data:{
method:"test"
}
});
}
hope it helps

Run a php function using jQuery

I've got this php function located in the base /home/index.php
function addEmail() {
$email = htmlentities($_POST['email']);
if (wp_create_user($email, '7777777', $email)) echo 'OK';
die();
}
I've also got this jQuery function located in /home/js/assets.js. The function checks to see if the email is valid and if so, should run the php function above.
$('#submit_btn').click(function () {
var entered = $('#ms_id-2 > input#input_fld').val();
if (isValidEmailAddress(entered) == false) {
alert('Sorry, the email you entered is invalid. Please try again.');
//console.log('No Validation!');
} else {
alert('Thank you. Your email address has been added to the list.');
}
});
So basically, if the email is valid, I need the code to execute that function in index.php. What's the quickest way to do this?
Create a PHP resource which invokes the desired logic. Something as simple as this might do the trick depending on what you want it to do:
<?php
require('index.php');
addEmail();
?>
Then make an AJAX request to that resource:
$.post('theNewPage.php', { 'email' : entered }, function (response) {
// handle the response in some way
});
The point is that JavaScript and PHP can't execute each other's code. One is client-side, one is server-side. They run at different times in different environments. And they communicate by way of HTTP requests in this case.
So if you have code server-side that you want to execute, then you create a page which executes it and you make an HTTP request (in this case an AJAX request) to that page to execute it. The response in the callback function in the JavaScript code will contain the result of that page (which in this case appears to be an echo of 'OK'). You'd examine that response and perform whatever action you intend to perform on the page.

How to use assign php variables from Javascript variable through a function. Values are not determined from html elements [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 8 years ago.
I don't see how this would be possilbe using AJAX. The variable I am trying to get doesn't come from an html element, but from predetermined variables. After two variables are set, this code executes which is a function:
// javascript function
function writetofile(file_name, api, wellname){
<?php
//something along the lines of this:
$file_handler = fopen(file_name, "r");
$api = api;
$wellname = wellname;
$result = $api." : ".$wellname;
fwrite($file_handler, $result);
$fclose($file_handler);
?>
}
The PHP code in the .php file that contains the javascript function is run on the server and is never sent to the client. The javascript code; the function itself, is run on the client (web browser) where there is no PHP.
Since, on the server, there are no file_name, api, and wellname parameters the PHP is sure to fail.
// javascript function
function writetofile(file_name, api, wellname) {
// The stuff here in the php block gets run on the server
// before anything is ever sent to the web browser.
// This opens a file (on the server), writes something to it,
// and closes the file. It produces NO output in the page.
// The PHP itself is never sent to the browser.
<?php
//something along the lines of this:
$file_handler = fopen(file_name, "r");
$api = api;
$wellname = wellname;
$result = $api." : ".$wellname;
fwrite($file_handler, $result);
$fclose($file_handler);
?>
}
This is what gets sent to the browser:
// javascript function
function writetofile(file_name, api, wellname) {
}
Clearly, if you call that function from within the browser, nothing happens, because there is no function body.
If you want to use the file_name, api, and wellname that were (somehow) specified on the client browser to run some PHP on the server, you must send those variables to the server, probably with an AJAX POST request to a url like example.com/php_process/dostuff.php, where "dostuff.php" would read the POST variables (like with any form) and do something with them. It should then respond with the results, or at least a status indicator.
How to do an AJAX POST from Javascript is another question, which has lots of answers on SO already.

Passing data from PHP to JS and JS to PHP

Hi I'm trying to learn PHP and javascript, therefore I tried to do an exercise about passing data but I didn't understand the js function and currently unable to do anything.
Here is the code
php-code.php
$v1=$_GET['v1'];
$v2=$_GET['v2'];
$v3=$_GET['v3'];
//Some operations about them
echo $output;
my-js.js
var v1 = $('#v1 option:selected').val();
var v2 = $('#v2 option:selected').val();
var v3 = $('#v3 option:selected').val();
//This is where I want to pass these variables to my php file and get the output
//But i don't know how
js-execute.php
//this is where my js gets the variables at first
PHP is a server-side language while JavaScript is a client-side one. This means that PHP will be executed when someone requests a page, but the browser will only get the result of the PHP code. On the other hand, JavaScript is sent to the browser and the browser will execute it at the appropriate time (when the page loads or when an event happens). That's why if you look at the source code of a page, you will be able to see the JavaScript code, but never the PHP code.
If you want to pass values from JavaScript to PHP, you will need to make a remote call to a PHP file. PHP isn't like JavaScript – once it's done running its code, it won't be able to respond to anything without a reload of the page.
The easiest way to send something to a PHP file and fetching the result with JavaScript can probably be achieved with JQuery. It has a function $.get which will fetch a given URL. Just be sure to properly validate the input on the server side – never trust user input.
JavaScript (using JQuery to send v1, v2 and v3 to page.php)
function requestPage(v1, v2, v3) {
$.get('page.php', {'v1':v1, 'v2':v2, 'v3':v3}, function(data) {
alert(data);
});
}
PHP (a trivial example)
// Be sure to properly validate input!
if(isset($_GET['v1']) && is_scalar($_GET['v1'])) {
echo strrev($_GET['v1']);
}

Categories

Resources