Get variable from PHP file using JQuery/AJAX
If I understand right, you need to use JSON. Here is a sample.
In your PHP write:
<?php
// filename: myAjaxFile.php
// some PHP
$advert = array(
'ajax' => 'Hello world!',
'advert' => $row['adverts'],
);
echo json_encode($advert);
?>
Then, if you are using jQuery, just write:
$.ajax({
url : 'myAjaxFile.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
},
error : function () {
alert("error");
}
})
And that's all. This is JSON - it's used to send variables, arrays, objects etc between server and user. More info here: http://www.json.org/. :)
How to use jquery ajax to get one variable from a php file to another php file
because $('.teamdelete') has no attr value ..
in your html you should put
<button class="teamdelete" value="<?php echo $arrayTeam['team_id']; ?>">Delete Team</button>
and in your javascript do this
var teamId = $(this).attr("value");
and in your php .. since the name of the post data = team_id you should do
$team_id = $_POST['team_id'];
Passing variable from PHP file to php file using Jquery
The passing part can happen in the script where the variable is defined, so in file1.php
. Then you get the following files:
file1.php
:
<?php
$user_rank = 123;
?>
<script>
function getRank()
{
$.ajax({
type: "GET",
url: "file2.php?user_rank=<?php echo $user_rank; ?>",
success: function(result){
$("#TargetRank").html(result);
}
});
};
</script>
file2.php
:
<?php
$user_rank = $_GET['user_rank'];
echo $user_rank;
?>
Access php variables of a template with ajax
First, maybe, you can change the request type to GET, because you don't post anything, but tried to get the information.
<script>
jQuery(document).ready(function($){
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
alert(result['advert']) // "Bye" alerted
},
error : function () {
alert("error");
}
});
});
</script>
EDIT:
Here is a functional script:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function(xhr, status, error) {
alert(error);
}
});
});
</script>
See the modifications:
- GET instead of POST
- console.log(result) to see the result
In my browser console:
Object { ajax: "Hello world!", advert: "Bye" }
Just to be sure, do you load your JQuery properly and do you work on a WAMP/LAMP server?
Can you post the entire files code?
EDIT2:
Check error in console and post it here, this is more easy to find the problem in the future with it.
how do i send a variable from jquery to a php file using ajax
You have to think differently about this. You can only request data from a server, not sent data to it. But while requesting data, you can pass data with your request.
Also, I really recommend not using jQuery. https://youmightnotneedjquery.com/
Checkout this post on how to request data with js: https://stackoverflow.com/a/29823632/4563136
(async () => {
const rawResponse = await fetch('https://yoururl.org/yourlink', {
method: 'POST',
body: JSON.stringify({
testDataKey: 'testDataString',
testData2Key: 'testData2String',
})
});
const content = await rawResponse.json();
console.log(content);
})();
You should then be able to access this data in PHP with $_POST: https://www.php.net/manual/en/reserved.variables.post.php
Just use var_dump($_POST) and it should print all variables back to your JS as a string. Use .text() instead of .json() and put the content variable into console.log(). You should see a pretty print of what you sent to the server.
How can I get a PHP variable to AJAX?
Good to use json while return back data from php to ajax.
$return_data = array();
if (condition){
$return_data['status'] = 'success';
} else {
$return_data['status'] = 'info';
}
echo json_encode($return_data);
exit();
Now, if you are return back json data to ajax, then you need to specify return data type into ajax call as below
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
dataType: 'json',
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
jQuery AJAX - send file and variable to PHP in single request
You can also append the number
key => value to to the form data as
form_data.append('number', variable1);
Then in Ajax call
data: form_data,
Related Topics
Cannot Send Session Cookie - Headers Already Sent
Use Openssl_Encrypt to Replace Mcrypt for 3Des-Ecb Encryption
PHP Sessions in a Load Balancing Cluster - How
How to Handle User Input of Invalid Utf-8 Characters
PHP - Extracting a Property from an Array of Objects
How to Convert Pascalcase to Snake_Case
PHP Integer and Float Comparison Mismatch
Mysqli_Stmt::Execute() Expects Exactly 0 Parameters, 1 Given
How to Bind SQL Variables in PHP
Applied Coupons Disable Free Shipping Conditionally in Woocommerce
Sum Specific Values in a Multidimensional Array (Php)
Correct Indentation of HTML and PHP Using Vim
Why, Fatal Error: Class 'Phpunit_Framework_Testcase' Not Found in ...
How to Compare 2 HTML Pages, and Output Only the Different Bits in Ruby or PHP
Data from Two Tables with Same Column Names