I have three files:
index.php
ajax.php
function.php
I want to pass a global variable from index.php to function.php via ajax.php.
So the alert message in index.php should be "2". But in fact, the result is "1" because function.php does not know the $global_variable.
Here is the code:
index.php
<?php
$global_variable = 1;
?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$.ajax({
type: "POST",
url: 'ajax.php',
success: function(data) {
alert(data);
}
});
</script>
ajax.php
<?php
include 'function.php';
$result = process_my_variable(1);
echo $result;
?>
function.php
<?php
function process_my_variable($new_variable) {
global $global_variable;
$result = $global_variable + $new_variable;
return $result;
}
?>
I do not want to pass the global variable to ajax call, because my real project has many variable like this, and they should not to display because of security.
How to do this?
$.ajax({
type: "POST",
url: 'ajax.php',
data:{
global_variable:<?php echo $global_variable?>
},
success: function(data) {
alert(data);
}
});
You can send it with data object to ajax.php page
and at ajax.php page you can fetch it by:
<?php
include 'function.php';
$global_var=$_POST['global_variable'];
$result = process_my_variable($global_var);
echo $result;
?>
index.php and ajax.php (with the included function.php) are different programs. They do not share variables.
You either need to store the data somewhere that both programs can get at it (such as in a SESSION) or pass the data from index.php to the browser, and then send it to ajax.php in the query string or POST body of the Ajax request.
Related
I want to execute a PHP script on a button click, which downloads an image from a URL to my server, through AJAX JQuery.
Here is the AJAX code in the .html file:
In the head section:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
In the body section:
<button type="button" id="btntest">Test PHP</button>
<script>
$("#btntest").on('click',function(){
alert("start");
var data = {"image-url" : "/serverfolder/Image.png","path" : "https://example.com/Image.png"};
$.ajax({
type: 'POST',
url: "test.php",
data: data,
success: function(resultData) { alert("success"); }
});
});
</script>
The code in the test.php file:
<?php
$params = $_POST['data'];
$path = $params['path'];
$image_url = $params['image-url'];
$data = file_get_contents($path);
$new = $image_url;
file_put_contents($new, fopen($data, 'r'));
?>
The problem: I don't get the "success" alert, instead I get an Internal server error for the test.php file. If test.php file only looks like this:
<?php
$params = $_POST['data'];
$path = $params['path'];
$image_url = $params['image-url'];
?>
The success alert appears, but that doesn't help me, because I want to download the file from the $path to the server directory $image_url. Any help appreciated on how to get this to work.
you can send data in ajax like that
data:{data:data}
that is ok
or you can send data like
data:{image_url : "/serverfolder/Image.png",path : "https://example.com/Image.png"}
in this shape you dont need to decode in php file and use like it
$path = $_POST['path'];
$image_url = $_POST['image_url'];
THAT'S IT
I'm trying to pass Database table from PHP (using Object-Oriented approach) to Javascript using Ajax (json_encode) which I've done successfully. The problem, however, is that the values that are inside the $data variable are printed in my body tag with a huge whitespace after it.
Server Side:
<?php
require_once "Database.php";
Class Product extends Database
{
public function getAllProducts(){
$sql = $this->connectDB()->query("SELECT * FROM product");
while($row = $sql->fetch()) {
$data[] = $row;
}
echo json_encode($data);
}
}
$p = new Product();
$p->getAllProducts();
?>
Client side:
$(function() {
getProductData();
});
function getProductData(){
$.ajax({
url: "Product.php",
type: "get",
dataType: "json",
success: successAjax,
error: errorAjax,
complete: function(xhr, status) {
console.log(xhr);
console.log(status);
}
});
}
function successAjax($jsonarray){
console.log($jsonarray);
}
Output (Note that body tags aren't being outputted):
<body>
"[{"id":"1","0":"1","name":"john","1":"john"},
{"id":"2","0":"2","name":"bob","1":"bob"}]"
</body>
Is there any way to prevent echo json_encode from printing data in HTML if all I want to do is pass it from PHP to javascript?
Try to send out the json http header in first place on product.php
header('Content-Type: application/json');
here is my simple code
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
success:function(response){
$('#getcart').html(response);//want to display $return_value (from action page)
$('#getcart2').html(response);//want to display $return_value2 (from action page)
}
});
Here i am sending request to action.php
and if in action.php i have echo two variables separately for example.
$return_value = " //Some html here "; echo $return_value;
$return_value2= "//some other html"; echo $return_value2;
So the question is in ajax i have function with argument response . how i will be able to receive these both variables from php and display it in different divs.
i hope you guys help me. thanks.
Send the responses as JSON.
In PHP
$return = array( $return_value, $return_value2 );
echo json_encode($return);
In Javascript
var response = JSON.parse(response);
$("#getcart").html(response[0]);
$("#getcart2").html(response[1]);
your could return a json from action
echo json_encode(array('cart' => $return_value, 'cart2' => $return_value2));
then in your js,
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
dataType: 'json',
success:function(response){
$('#getcart').html(response.cart1);//want to display $return_value (from action page)
$('#getcart2').html(response.cart2);//want to display $return_value2 (from action page)
}
});
You need to use json_encode in order to get multiple records or data.
action.php
<?php
header('Content-Type: application/json');
$array = array(
'var1'=> 'var value 1',
'var2'=> 'var value 2'
// more variables to go
);
echo json_encode($array);
?>
and then read your variables in JS
dataType: 'json',
success:function(response){
console.log(response.var1);
console.log(response.var2);
$('#getcart').html(response.var1);
$('#getcart2').html(response.var2);
}
You can use json_encode to create an object like:
$array = [
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
];
echo json_encode($array)
Then add dataType: 'json' to your ajax options. The response then will be an object like:
{
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
}
Where you can access the specific values with e.g. response.return_value2 and thus separate them.
I'm trying to use AJAX to check variables in the database, and if it's true, then it should make it header to a certain page, except in this testing phrase, I'm not checking any variables. I'm just testing if it'll header off to that certain page if I call the function. I started at test1.php, but it should've called the ajax function, and immediately header off to test3.php, but it didn't. I'm not sure what I did wrong. Please take a look:
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function nopassAjax(url,timeout) {
$.ajax({
type: "POST",
url: url,
error: function(xhr,status,error){alert(error);},
success:function(data) {
setTimeout(function() { timeoutAjax(url,timeout); }, timeout);
}
});
}
</script>
test1.php
<?php
include('ajax.php');
echo "<script>";
echo "nopassAjax('test2.php',1000);";
echo "</script>";
?>
test2.php
<?php
//checks some stuff in the database
//if true, header off to test3.php
header("Location: test3.php");
?>
test3.php
<?php
echo "Hello";
?>
From your question I'm assuming you want to redirect to the page that's returned from your AJAX call. You can't do this from PHP alone.
Javascript:
$.ajax({
method: "POST",
url: someUrl
}).fail( function( error ) {
alert( error );
}).done( function( response ) {
window.location = response;
});
PHP:
<?php
echo "test3.php";
?>
I have a problem to pass value to my php script via Ajax, there is my code :
I send value to ajax via a href link :
After scan directory i get links of my files on href :
<?php echo $file; ?>
My js function to receive value :
function getfilename(content) {
alert(content); // i can see my value here
$.ajax({ //not work
type: 'POST',
url: 'script.php',
data:{song: content},
async: false,
success: function(response) {
alert(response); //nothing
});
}
My script.php
$album = $_POST['song'];
echo $album;
I dont understand why it does not work.
Thank you for your help!
Try changing
<?php echo $file; ?>
To this
<?php echo $file; ?>
Maybe your page is refreshing before the ajax data loads.
When you use the link element it will automatically go to the location in the href after it executes the onclick event. Leaving it empty will reload the page.
I would recommend you to add a "return false;" as the last instruction of the onclick.
<?php echo $file?>
Hope this helps.
Looking to your js code your success callback is missing a "}" in the end of function.
// $file = 'teste';
<?php echo $file?>
function getfilename(content) {
alert(content);
$.ajax({
type: 'POST',
url: 'script.php',
data:{song: content},
async: false,
success: function(response) {
alert('Response: ' + response); //Alerts Result
}
});
}
// Script.php
<?php
echo $_POST['song']
?>