Just playing around with ajax and php and I have a simple question.
These are the following relevant files.
file.php
<?php
$bla = $_GET['pid'];
echo $bla;
?>
HTML
HTML Code of example site URL: somesite.com/blabla.php?pid=3
(It contains a single button which when you click it is supposed to get the $_GET value from the URL which is 3)
<!DOCTYPE html>
<html>
<head>
<title>Some Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button class="fa fa-icon" onclick="someFunction()"></button>
</body>
</html>
JS:
<script>
function someFunction(){
$.ajax({
method: 'POST', //I've tried 'GET' here too. doesnt make a difference
url: "file.php",
success: function(result)
{
alert(result);}
});
}
</script>
As noted by the commenters below: I've also tried the following
<script>
function someFunction(){
$.ajax({
method: 'POST', //I've tried 'GET' here too. doesnt make a difference
url: "file.php",
data: {pid: 3}, // added this line
success: function(result)
{
alert(result);}
});
}
</script>
The alert is blank there is no 3 on it when the php file has echo $bla which is $_GET['pid'] and the pid in the url is = 3.
Can someone please explain why that is the case? I dont think I understand what is happening behind the scenes of the above codes to figure out why.
Please note that I'm not trying to solve a particular problem or anything just trying to understand why $_GET is not working in this very specific case.
You're not sending any data in the AJAX request, hence there's nothing for the PHP to read and send back. To fix this include a data property in the request which contains the pid key and the required value, for example:
function someFunction(){
$.ajax({
method: 'GET',
url: "file.php",
data: {
pid: 3
},
success: function(result) {
console.log(result);
}
});
}
Note that I'm using method: 'GET' here, which is important as you're using $_GET in your PHP, so a POST request won't work. Also note that I'm using console.log() to debug the value. alert() shouldn't be used for debugging as it coerces data types.
Related
I've been struggling with this for two hours now and I've narrowed down the issue to a simple test case. I've done plenty of research and finally settled on trying to reproduce the first answer from this question: Set session var with ajax.
When I push this button (lazy html, but that's not where the issue lies):
<html>
<head>
...
<script src="jquery.js"></script>
...
<head>
<body>
....
<?php
var_dump($_SESSION);
?>
<input type="button" class="update">
....
</body>
</html>
This ajax request in jquery.js gets called:
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function() {
console.log("Successful request sent");
}
});
And finally the setSession.php file:
<?php
session_start();
$_SESSION["foo"] = $_POST["bar"];
?>
The success message is printed to the console so I know I'm hitting the right file. Why isn't the session variable getting set? I have php 5.5.2 if that matters at all. Thanks for you help!
Like I suggested on the comments, do this to fix your code:
Reload the page on your success:
success: function() {
console.log("Successful request sent");
location.reload();
}
Make sure you have session_start() in all the pages that uses sessions:
session_start(); //this must be at the top, before you print anything
Might this can help you.
In setSession.php write echo $_SESSION["foo"] = $_POST["bar"];
In your ajax script do
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function(e) {
console.log(e);
}
});
now open browser console (F12). click on your button.update. Check if is there written bar in console.
I am trying to understand the magic of the .ajax() function with jQuery. I am having a hard time getting what I want to be done. I basically want a div with content that refreshes every x time (about every 10 seconds). Mainly, this will output the latest posts that have been posted to a table in my database. Pretty much I am using this example to get an idea of how I can achieve my goal, but unfortunately I am not getting what I want.
I am trying to set my file so that when the refresh button is clicked, the div refreshes and brings up the latest posts.
On one side we have the index.php file:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>Test page</title>
</head>
<body>
<h1>Welcome to the form</h1>
<h2>We are going to try to process this with AJAX</h2>
<h3>I hope it works!</h3>
<div id="content"></div>
<button id="refresh>Refresh!</button>
<script type="text/javascript">
$('#refresh').on('click', function(){
$.ajax({
type: "POST",
url: "process.php",
data: ,
error: function(data){
$('#content').text('Update unsuccessful!').
slideDown('slow');
console.log(data);
},
success: function(data){
$('#content').text('Update completed!');
console.log(data);
//somewhere over here use the $.getJSON() function
},
complete: function(data){
setTimeout(function(){
$('#content').slideUp('slow');
}, 3000);
}
});
});
</script>
</body>
</html>
And on the other hand, we have the process.php file that queries the results from the database:
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "root";
$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sth = $db->query("SELECT * FROM posts");
$sth->setFetchMode(PDO::FETCH_ASSOC);
echo json_encode($sth);
Do you have any idea of how to accomplish this?
To structure my results, I want to use something like this inside the success part of my jQuery code:
$('#outputdiv').html(
//html code here fetching the JSON data to appear within custom divs (so I can apply css styles to them)
);
Also, do you know how can I automatize the div to bring new results using the same &.ajax() function every x time? I have read the documentation throughly and followed many examples, but I still cant get what I want!
Thanks in advance!
Cheers!
Edits:
-Fixed the echo json_encode, the "process.php", erased the data: line, and put the passing (data) into the success: error: and complete: areas and still doesnt work
first url should be string type so it would look like this
url: "process.php",
then in process.php file echo your result like this
echo json_encode($sth);
and in your error, success functions add an parameter like this
error: function(data){
//your code
},
success: function(data){
//your code
}
also your variable form_data is not needed according to your code. so remove this line
data: form_data,
Your success function must take data argument.
And i recommend you to read about $.getJSON shortcut for this case.
3 things...
url: process.php should be url: "process.php"
form_data isn't really defined anywhere
success: function(){ should be success: function (data) {
Well I think you need PDO fetch after setFetchMode. Also Its better to use send JSON Response headers in Ajax request
$data = array();
while ($row = $sth->fetch()) {
$data[] = $row;
}
header('Content-type: application/json');
echo json_encode($data);
I have some problem with passing value from javascript file to php file.
I make some calculations in JS, and after that i passing it to php.
This is a code of JS:
var price=100;// for example
$.ajax({
type: "POST",
url: "SecureRide.php",
data: { calculatedPrice: price }
});
And this is a code of PHP:
<?php
session_name("ridePrice");
session_start();
$_SESSION["calculatedPrice"]=$_POST["calculatedPrice"];
echo $_SESSION["calculatedPrice"];
?>
So what i do is a simple Ajax function that passes the value to php, very simple, but doesn't work!
When I do echo function there's nothing there.
Maybe there are another way to solve it?
Thank you very much!
Note : if you are put your ajax code in function and than call function from the "$(document).ready(function(){" then your code run perfectly
I write code in your .js file :
$(document).ready(function(){
functionName(price);
});
function functionName(price){
$.ajax({
url: 'SecureRide.php',
data:{calculatedPrice: price},
type: 'POST',
success:function(data)
{
alert(data);
},
error:function(data)
{
alert("mistake in your code");
}
})
}
And Code For PHP file for get .JS File Data
if(isset($_POST['calculatedPrice']) && !empty($_POST['calculatedPrice']))
{
$calculatedPrice1=$_POST['calculatedPrice'];
}
I have a PHP file which has code to echo some HTML. I would like to provide the PHP file to some end users which can be done like this:
<?php include 'file.php'; ?>
Unfortunately my users will for instance have index.html and this will not work. I don't want to ask my users to change there HTML file in to PHP. Another approach is to modify the .htaccess file:
<Files index.html>
AddType application/x-httpd-php .html
</Files>
I don't want to ask this of them as well. So what are my other options? Is it possible to show the echoed results in HTML file? Maybe with the help of some Javascript?
You can do this with AJAX. It might look a bit challenging, but it is frankly much simpler than many think. In fact, it's pretty easy.
Ajax goes in your javascript code, and looks like this:
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that the data from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:
$('#myDiv').html(whatIgot);
Presto! Your DIV now contains the data echoed from the PHP file.
The ajax can be triggered by a change to an control's value (as in the above example), or just at document load:
$(function() {
//alert('Document is ready');
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'Iamsending=' + this_var_val,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready
Look at this example for ideas on how it works.
Note that the above examples use jQuery, and therefore require this reference in the tags of your page:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
This will replace the body of the html page with the contents of the url called.
$('body').load( url,[data],[callback] );
If they can add javascript, an ajax request should do the work...
<script>
var req = new Request({
method: 'get',
url: 'file.php',
onRequest: function() { // loading image
},
onSuccess: function(response) {
document.getElementById("destination").innerHTML = response;
}
}).send();
</script>
They will also need a div for the code to get in:
<div id="destination"></div>
I currently have a php file executing:
test
I would rather not have to load a new page and do it onClick.
Does anyone know a simple way to do this?
I added a more complete example, including the suggested ajax. I still am having trouble getting it it to work though.
<script type="text/javascript">
$('li').click(function() {
$.ajax({ type: "GET", url: "test.php", data: { foo: 'boo' }, success: function(data){
// use this if you want to process the returned data
alert('complete, returned:' + data);
}});
});
</script>
</head>
<body>
<div id="header">
<h1>Title</h1>
</div>
<ul>
<li>Test</li>
</ul>
</body>
</html>
you could use jquery and do something like this:
$.ajax({ url: "test.php", data: { foo: 'boo' }, success: function(data){
// use this if you want to process the returned data
// alert('complete, returned:' + data);
}});
for more information, take a look at the jquery-documentation
Yes, as your tags say. You will need to use AJAX.
For example:
$.ajax({
type: "GET",
url: "test.php",
data: "foo=boo"
});
Then you just have to stick that within a click function.
$('a').click(function() {
// The previous function here...
});
EDIT: Changed the method to GET.
In your firl say e.g try.html write this code
<meta http-equiv="refresh" content="2;url=test.php?foo=boo">
it will redirect u to test.php?foo=boo in 2 seconds
OR Other way ===========================================
create one php file
<?php
header('Location: test.php?foo=boo');
exit;
?>
Hope this help