Javascript call php header [duplicate] - javascript

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 :)

Related

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

stop php loop with html button

Is it possible to stop the PHP loop with a button that appears in my js page?
Here the post request:
$("#startLoop").click(function () {
var postData = {
'data': "some data",
};
$.post("http://mySite/?controller=myController&action=startLoop", postData)
.done(function (data) {
});
});
my php code:
public function startLoop()
{
$ArrayObj = getDataFromDB();
foreach($ArrayObj as Obj)
{
sleep(1);
echo "row<br>";
}
}
After that, I need to stop php loop with html button.Is it possible?
It is not possible for the client (browser) to interact with what's going on behind the screens on the server (PHP).
Short answer.
No it is not possible
Long answer
PHP is server site, JS is client side. they are not really connected. AJAX just opens a php page ande returns the value. but it could be any page.
You wouldn't necessarily want PHP to be running any would-be endless loops in a single script awaiting outside interruption; I'd suggest you use something like Node.js for an operation like that - along side the socket.io package you could do this exactly, just in javascript.

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']);
}

How to call php codes inside javascript [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I want to check the inputs of a form if they are empty and then i want to use php codes for user registeration.
<script>
$('#submitbutton').click(function(){
if($('#usernameinput').val() == ''){
alert('Input is blank');
}
else {
//here i want to use php codes for example;
$bgl = new mysqli("localhost", "root", "", "users");
if ($bgl->connect_errno) {
echo "Failed to connect to MySQL: (" . $bgl->connect_errno . ") " . $bgl->connect_error;
}
$username = mysql_real_escape_string($_POST['username']);
.....
.....
..... /and so on..
}
});
</script>
In this case you most likely want to use $.ajax() to call a PHP page that supplies this information.
jQuery.ajax()
There is no such thing as php and javascript working together like that. Javascript in run on client side and php is run on server side. The best you can to is to pass and retrieve values to and from a php page and then use those values as intended.
You have a few options here. The first is to post the form to a PHP page after the JavaScript validations (just use the form action) or use Ajax and call the PHP page, as Robin says.
That's not posible, you can embed javascript into php code but not vice versa.
The best way to implement that is developing a REST service and retrieving data with AJAX.

Categories

Resources