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.
Related
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 :)
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
i want to make a loop in jquery, Ajax and PHP.
my pages are:
shop.php
do_ajax.php
in the shop.php are variable $p_productid is 1 and $j_productid is $p_productid
var j_productid = <?= $p_productid ?>;
now i do j_productid++ so the output from $j_productid is 2
now i'm posting this with ajax to do_ajax.php
in the do_ajax.php are variable $pa_productid is $_POST['$j_productid'];
now i can place this on html, but i want to set this value in too the variable on $p_productid on shop.php
how i need to do this?
there is working a swipe system in this case so only with php it isnt working i need to work with jquery that's why am i doing this on this way. i got an another solution without AJAX but i want that you cant see on the client side the webpage is refreshing.
JQUERY
wipeLeft: function() {
var j_ProductId = <?= $g_ProductId ?>;
var j_Swiped = 1;
if (j_ProductId < <?= $l_LastProduct ?>){
j_ProductId++
//document.swiping.productid.value = j_ProductId;
//document.swiping.submit();
$.ajax({
url: 'do_ajax.php',
type: 'POST',
data: { swipe : j_Swiped,
productid : j_ProductId},
success: function (data) {
$('.product').html(data);
}
});
}
}
do_ajax.php
if(!empty($_POST['swipe'])){
$l_ProductId = $_POST['productid'];
echo $l_ProductId;
}
You need to understand that the JavaScript (even if generated dynamically by PHP) is not running the same time that PHP is running. Your workflow will be something like this:
PHP script (shop.php) is invoked
PHP script generates output, HTML and JS mixed.
These are all in server side until the web server sends the output to client (browser)
In browser HTML displays and JS runs with starting values that you generated previously by PHP. But in this time, PHP has been finished, not running anymore. PHP variables are not alive anymore.
JS interacts with the user in browser, we can say it's running continuously.
Triggered by an action (swipe) JS sends an (ajax) request from client side to server side. This request transfers the new value to server side, and invokes another PHP script (do_ajax.php). You do whatever you want with the new value (process it and or store it) in server side. You need to understand that you are in a completely disjunct scope in PHP than in your first PHP script. (distinct in time too)
If you want to be sure that, in case of a page reload, the (product ID) value will be the updated value, you need to store it somewhere (user session, key-value store, database, or any persistent) when you get it in server side (so in do_ajax.php) and later load this value in the beginning of your shop.php script ...which will pass it to the JS, and so on. The workflow starts again.
How can I send just one element from browser to server fast and without reloading browser page?
Is there an AJAX way to do this, that is a NON-FILE method? The opposite of ".load"?
.load works great sending a single element from server to browser without page reload.
How to do the opposite direction?
Browser is JavaScript.
Server is vxworks with windmarks.
PRESENT METHOD THAT WORKS BUT RELOADS PAGE:
Presently, the browser element is and I use submit to send it to the server, but this takes too long and reloads the browser page.
The element's innerHTML contains data formatted as a vxworks WINDMARK.
(When the vxworks server receives this submission, it reads the windmark and copies it to a 'C' string for backend software to process.)
If you're using jQuery and PHP then something like this should work:
JS:
$.ajax('doServerSuff.php?action1=saveLog', function() {
// do stuff after server received the data
});
PHP (doServerStuff.php):
<?php
if ($_GET['action1'] == 'saveLog') {
//do stuff
}
?>
You can get and send data using jQuery. using something like this:
$.post('urlfromserver',browserdata,function(datafromserver){
//do stuff
})
if you let me put a little bit more, it's a good idea to use JSON to send/receive data to/from server. Having that in mind, you can do something like:
$.post('urlfromserver',{browserdata: JSON.stringify(browserdata)},function(datafromserver){
javascriptObject = jQuery.parseJSON(datafromserver)
//do stuff
})
And in your PHP code, it would be as simple as using json_encode to send data to javascript and json_decode to receive data from javascript
UPDATE
Obtaining the data in the server should be as simple as requesting the object via post or get depending on your send method, and parsing the JSON.
In PHP, this is an example of obtaining data using the above code:
$dataFromBrowser = json_decode($_POST['browserdata'])
Use $.post in jQuery to send the data.
The load intruction can also be used to transmit data to the server:
$().load("url", {limit: 25}, function(){
//transmission finished
});
In this example the parameter limit with the value 25 wil be transmitted to the server.
Taken from:http://api.jquery.com/load/
You can simply do with the ajax call like this
$.ajax({
type: "POST",
url: "yourpage.php?id=someValue",
success:function(data){
//do some stuff here
});
I got it working. Here is the corrected JavaScript, from the above answer.
Here is how to change a single element at the server.
This is also an example of how to write to a vxworks windmark string at a vxworks web server, without reloading the page.
NOTE: no URL is specified, so that the same page is used.
$.ajax({
type: "POST",
url: "?general_page_to_MM_data_1_windmark=CCCCCCCCCCCCCC",
success:function(data_from_server){
}});
I am using the following click function for a purpose. What can I add so it will add 1 in a txt file when it is clicked? Like a counter on how many times it was clicked.
Thank you
$("#clearme").click(function(e) {
e.preventDefault();
// i have some stuff here
});
You can't access or edit files from the front-end. You'll need PHP or something. You can save it in a variable and pass it and process it with ajax. Something like this, untested:
var num = 0;
$button.click(function(){
$.ajax({
url: 'bla.php',
type: 'POST',
data: { num: ++num }
//...
});
});
And in PHP:
$num = $_POST['num'];
// Add to file stuff
you will have to modify the text file on the server. Send a ajax request every time the click event happens.
$("#clearme").click(function(e) {
$.post("url")
e.preventDefault();
// i have some stuff here
});
Text file where? On the server or the client machine?
If you're aiming for the client machine, javascript and jquery alone aren't going to work. There are security measures to prevent this so that would be hackers don't drop trojans on our machines every time we visit a website.
That leaves the server.
Accomplishing this depends entirely on the server side language/framework you are using (i.e. PHP, JSP, .NET).
You didn't post the reason behind needing to do this, so I'll offer the option of writing the value to a cookie instead of a file, but since you haven't told us more about what you're up to, this might not be a viable solution.