PHP file called by javascript and another php file - javascript

I have a php file (I will call ORIGINAL) which do some calculations (through db mysql). I want to read this php from javascript. For that operation I have used ajax function and my php uses echo $result to print the data I need.
Everything is perfect here.
What happends now, I am creating another php file which need to call the ORIGINAL php file. If I want to call it, I must change the echo to return which is normal. This causes that my javascript call doesnt work.
Do you have a solution which work for both situations?
Thanks in advance.

Do you mean something like this?
original_php_file.php:
<?php
require_once "other_php_file.php"; // include all of the other files contents
// all code contained within original_php_file
?>
You were being pretty broad with your request (not including file names or code), so this is all I can assume you need.
Tell me if it helps :-)

Just send one more parameter into your ajax request to tell that ORIGINAL php file what type of output it should return.
Into your ORIGINAL file check for that output so you can understand from where that request come and what output you should return.
$.ajax({
url: 'ORIGINAL.php',
data: 'data=test&output=1',
success: function(r){
// here you have your output
}
});

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

Save variable to text file serverside using jquery

I am trying to save a variable for counting the views of my personal website, I dont need to use php because its literally a viewcount. I know how to retrieve the count from the server using $.post, but how would I retrieve it (Edit: In the simplest way possible.)?
The website I'm trying to do it with is http://artsicleprojects.com/
Thanks in advance!
You will need PHP for this question, because it is dealing with server-side actions. First, you need to make a server-side script to increment the text file's number. Then, you will need to make a client-side script to make a request to the server. This script increments a number in the text file every time the request is made. Anyway, here's how I would do it (Note: this code is un-tested):
PHP:
<?php
/*Reads and collects current count.*/
$rfile = fopen("views.txt", "r") or die("Unable to open file!");
$count = fread($rfile,filesize("views.txt"));
fclose($rfile);
/*Increments the count.*/
$wfile = fopen("views.txt", "w");
$ncount = $count + 1;
fwrite($wfile, $ncount);
fclose($wfile);
?>
Note on code: for this code to work correctly, you may need a text file already made (views.txt), in the same directory as the PHP script, with a single "0" written in it.
JavaScript (with jQuery):
$.post("phpscript.php", function(data, status){
console.log(status);
});
This also is supposed to be in the same directory as the script to work.

Ajax after success, how to pass data to a variable to php

I have script like this
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
I don't know how I can pass data response to php code ?
For Example: if I alert response, it's show 123 .so I want pass value 123 to a variable in php
$id = 123
response is the result passed BY php, not TO php. What's passed to php is the id and the task.
In your tab.php, you can access these two values :
<?php
$id = $_POST['id'];
$task = $_POST['task'];
//do anything you want with it...
?>
This is not the right workflow. PHP executes on runtime, so every time the page has finished loading you can't really put variables back into PHP (unless you reload the page). This is where AJAX comes in, so you can call PHP scripts from JavaScript / jQuery and don't have to reload the page every time.
The right thing to do is to either store the variable you have generated in the tab.php script in a database, $_SESSION, $_COOKIE or something similar like so:
//put this at the top of all your php scripts you want to use the variable in
session_start();
//now store the variable you wanted to pass (in tab.php)
$_SESSION['returnValue'] = $myValue;
Now if you want to use the variable in other pages just echo it like so (remember to add session_start() at the top of the PHP script.
echo $_SESSION['returnValue'];
First of all, start by reading this
To answer your question,
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
The result from id and task are sent via $_POST (type:"POST") to the page tab.php (url:"./tab.php"). If you want to do that on a different page, just change the url in your ajax call: url:"./any_other_page.php" and the posted values will be sent there
Finally, read THIS post as well. It is greatly written and very well explained.
Hope it helps!
Keep on coding!
Ares.

How to pass a value from JavaScript in php?

Translate translator from Google. So that did not swear if something is not clear. Itself from Russia.
The question arose. How to pass the value of the alert in the javascript in the variable $ value in php, and write it in the case file. And another question: how to hide the alert? or use instead to visually it was not visible, but the value was passed?
//a lot of code
{
console.log(data);
alert(data['value']);
}
});
So. Also there is a PHP script that writes logs (current page and the previous one) to a file. According to this principle here:
//a lot of code
$home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$referer = $_SERVER['HTTP_REFERER'];
$value = how the value of the java script to convey here?;
$lines = file($file);
while(count($lines) > $sum) array_shift($lines);
$lines[] = $home."|".$referer."|".$value."|\r\n";
file_put_contents($file, $lines);
It is necessary that the value of js is transferred to the php-script and write to the file. How to do it? Prompt please. I am a novice in all of this.
PHP scripts run before your javascript, which means that you can pass your php variables into javascript, but not the other way around. However, you can make an AJAX POST request from JavaScript to your PHP script, and grab the POST data in PHP through the global $_POST variable.
Assuming you use jQuery, your JavaScript would look something like:
// assign data object:
var data = { value: "test" };
// send it to your PHP script via AJAX POST request:
$.ajax({
type: "POST",
url: "http://your-site-url/script.php",
data: data
});
and your PHP script would look like:
// if the value was received, assign it:
if(isset($_POST['value']))
$value = $_POST['value'];
else
// do something else;

Using Ajax to require different php page

I want to use jquery ajax to change the content of my div elemnt by requiring different php files.
here is the ajax code :
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num
},
success:function(result){
$("#right_bot").html(result);
}
});
the project_functions.php would be something like :
$result = '<?php require "Panels/Project/Main/main.php" ?>';
echo $result;
I can see the value being outputted , but the html comment out the php part
<!--?php require "Panels/Project/Main/main.php" ?-->
It just comments out the php. Is there a way i load different php files into my div ?
In the main.php file , It has php code , html code , and some style tags. Can I use ajax to load all this into the div element ? or I have to echo all my html code ?
You can't do this like that. What you want is that all PHP is excecuted on the server and only the result has to be returned.
You can't send php-code back to javascript and try to run it there, PHP is a serverside language, it will only work on the server. Javascript is clientside, it will only run in the browser.
If you where to send <?php echo 123; ?> back to Javascript, you'll get exactly that as result, not 123.
The solution in your case is to make project_functions.php really require it. This will include the main.php, all it's functions and output.
require "Panels/Project/Main/main.php";
Some suggested reading:
http://www.codeconquest.com/website/client-side-vs-server-side/
A trick which might help you: Paste the link to your urlbar, and add the variables to it. The result you get in your screen is what Javascript will output. Note: This only works for method=get, not post.
In this case browse to /project/Functions/project_functions.php and do the simple require per my code above. That output will be send to Javascript.
Send a parameter in the ajax request 8for example type):
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num, type: "main"
},
success:function(result){
$("#right_bot").html(result);
}
});
And then in php-file get the type variable:
if($type == "main") {
require "Panels/Project/Main/main.php"
}
else {
require "Panels/Project/Main/sthelse.php"
}
You should also have some sort of same function name or something to output the results of the file;
<?php
function printResult() { }
echo printResult();
Try:
$result = file_get_contents('Panels/Project/Main/main.php');

Categories

Resources