I'm trying to pass a simple variable from my jQuery to my php and then echo it on my HTML. It doesn't seem to work though.
I can't get my variable $result to show up on my page. Any thoughts? The Ajax POST seems to be working fine. The problem seems to be communication between php and HTML.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='front.js'></script>
</head>
<body>
<?php echo $result; ?>
</body>
</html>
front.js:
$(document).ready(function() {
$.post('/back.php', {name: "Bob"}, function(data) {
});
});
back.php:
<?php $result = $_POST['name']; ?>
Try this
index.html:
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='front.js'></script>
</head>
<body>
</body>
</html>
front.js:
$(document).ready(function() {
$.post('/back.php', {name: "Bob"}, function(result) {
$('body').html(result);
});
});
back.php:
<?php echo $_POST['name']; ?>
Change this
<body>
<div id="show-data"></div>
</body>
And
$(document).ready(function() {
$.post('/back.php', {name: "Bob"}, function(data) {
$('#show-data').html(data);
});
});
And
<?php echo $result = $_POST['name']; ?>
Change Your PHP Code :
<?php echo $_POST['name']; ?>
And Also Your HTML Code :
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
</body>
<script>
$(document).ready(function() {
$.post('/back.php', {name: "Bob"}, function(data) {
$('body').append(data)});
});
</script>
</html>
$result in back.php and $result in index.html aren't related. Setting it in back.php has no effect on index.html. If you echo something in back.php however, that output will be passed to the empty callback function you have in your $.post() call. You can handle the data there and use javascript to insert it into your page.
Just add the following line to your code: $('body').html(data);
Like your question we have three different files one is index.html
1) index.html
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='front.js'></script>
</head>
<body>
<?php echo $result; ?>
</body>
</html>
2) front.js
$(document).load(function(){
$.ajax({
url: '/back.php',
type: 'POST',
data: 'name=Bob',
async: false,
success: function(data) {
$('body').html(data);
},
cache: false
});
});
3) back.php
<?php echo $result = $_POST['name']; ?>
Now use this, your files will work out. Please let me know if you have any queries.
Puh, lot of mistakes. First, your index.html contains PHP - Code which won't be executed because this is not a PHP - Skript (ending with php).
Second you are saving the value of your request to back.php in a variable, which won't be existing after the request is finished. You can either:
rename index.html to index.php, exchange your statement to
<?php echo $_POST['name']; ?>
and change your request to
$.get('/index.php', {name: "Bob"}, function(data) {
});
which would cause a continously reloading of the site,
or store your result in a $_SESSION (see PHP Session Handling), and retrieve that in your index.php (you got to rename the file).
Related
This question already has answers here:
What is the order of inline onclick vs addeventlistener and why?
(3 answers)
Closed 2 years ago.
I have two PHP pages. On one of the pages, I want to post data to the other page when a button is pressed. However, when I try to access the post array from the other page, it appears empty. Would appreciate if someone could show me where I'm going wrong. (Also I'm not allowed to use a html form to post)
Page called test2.php:
<?php
if(isset($_POST['testing1'])){
die(json_encode($_POST));
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="testbtn" onclick="location.href='test1.php'">Test Button</button>
<script>
$(document).ready(function(){
$('#testbtn').click(function() {
$.ajax({
method: 'POST',
url: 'test1.php',
data: {
testing1: 'string1',
testing2: '111'
},
success: function(data){
alert(data);
output = JSON.parse(data);
}
});
});
});
</script>
</body>
</html>
Page called test1.php:
<?php
$testvar = json_encode($_POST);
echo $testvar;
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>
the reason the it's failing is because you have so much html on test1.php
alert(data) is having an issue because there is so much content.
JSON.parse(data) is failing because it's not just json it's also html
test1.php should just simply parse post to json and echo it
<?php
echo json_encode($_POST);
?>
When you press the button 2 things are happening in same time :
The ajax call that sends data to the page test1.php
The page redirection beacause of the onClick attribute on the button.
The ajax request calls the page test1.php which is not the same instance as the page you call when you use the onClick attribute. So I think you could try placing "location.href = 'test1.php'" in the success function and store $_POST in a session variable. That way the data will reach the test1.php page before your redirect.
success: function(data){
alert(data);
output = JSON.parse(data);
location.href = 'test1.php';
}
Maybe like this:
Page called test2.php:
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="testbtn" onclick="location.href='test1.php'">Test Button</button>
<script>
$(document).ready(function(){
$('#testbtn').click(function() {
$.ajax({
method: 'POST',
url: 'test1.php',
data: "yourData="+"{
testing1: 'string1',
testing2: '111'
}",
dataType:"json",
success: function(data){
alert(data);
output = JSON.parse(data);
}
});
});
});
</script>
</body>
</html>
Page called test1.php:
<?php
if(isset($_POST["yourData"]){
$testvar = json_decode($_POST["yourData"]);
echo $testvar->testing1."<br/>";
echo $testvar->testing2;
}else{
echo"is not set";
}
if(!empty($_POST["yourData"]){echo $_POST["yourData"];}else{echo"is empty";}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>
NB:
dataType:"json" used if you want to get a json answer;
if you use dataType:"json" that mean you have to change the method json_decode() in my code to json_encode();
isset() check if name of associative array is exist;
! means not;
empty() check that if the value of that name in associative array is empty (like ' ');
!empty() check that if the value of that name in associative array is not empty (not like ' ').
I would like to get the value sent from php via AJAX in php. But i can not get value. Where is my mistake?
It is my functions.js
$(document).ready(function(){
$(".yeni_problem").click(function(){
var uid = 1;
$.ajax({
url: 'admin.php',
type: "post",
data: {'uid': uid},
success: function(data){
// $("#cvb").text(data);
},
statusCode: {
404: function(){
alert("admin.php not found");
}
}
});
});
});
and it is my php page that, i control sending value in here. The Codes is large but i write small form. Which that when i run the small codes on other folders as other site it does't work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HELPDESK</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/css.css">
<link rel="stylesheet" href="css/default.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/icon.css">
</head>
<body>
<button class="yeni_problem">Yeni Problem</button>
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "<hr>Value not found<br/>";
}
var_dump($_POST);
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="js.js"></script>
<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript" src="bootstrap.min.js"></script>
<?php
echo "</body>
</html>";
?>
When i click to ".yeni_problem" class i can not get value.
1st- check you include Jquery
2nd- Be sure admin.php page in the same directory with file you called functions.js in if not check its path
3rd- you pass uid not data so in php use
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "Value not found";
}
?>
4th: and if you dynamically generate the element with class="yeni_problem" .. so use
$('body').on('click',".yeni_problem", function(){
instead of
$(".yeni_problem").click(function(){
5th: if yeni_problem is a submit button or anchor so you need to use e.preventDefault(); to prevent page from reloading
$(".yeni_problem").click(function(e){
e.preventDefault();
// rest of code here
6th: if yeni_problem is a form use .submit()
$(".yeni_problem").submit(function(e){
e.preventDefault();
// rest of code here
Pay attention to your code: in the JS snippet, the parameter passed to the server is "uid", which means your server will be getting a $_POST array with a position labeled "UID".
<?php
if(isset($_POST["uid"])){
echo "Value:".$_POST["uid"];
}else{
echo "Value not found";
}
?>
You should also check what is in the $_POST variable, insert var_dump($_POST) and comment out the rest of the code.
I thought this would be simple enough, but I can't get it to work.
I have two files. main.html and data.php
The two files are in the same folder on a server.
I want to get a string from the PHP file and use it in jQuery. In the example below, I want the browser to create a pop-up, with the text "xxxx". I get no pop-up.
data.php
<?php
$var = "xxxx";
echo json_encode($var);
?>
main.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts/jquery-1.11.1.js"></script>
<script>
$(document).ready(function() {
var testString = <?php $var = json_decode(file_get_contents('data.php'), true); echo $var; ?>;
alert(testString);
});
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
Any takers?
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function() {
$.ajax({
url:"data.php",
success:function(result){
alert(result);
}
});
});
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
The first problem with this is that on many servers .html is not parsed for PHP
The second problem is that the file_get_contents will actually display the full contents of your .php file (including the <?php) which is likely not what you're looking for.
Instead I would use an AJAX request such as http://api.jquery.com/jquery.get/
For this you will need to include jQuery in your <head>
You should get the php data before html initiates, like below
<?php
$var = json_decode(file_get_contents('data.php'), true);
?>
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function() {
var testString = <?php echo $var; ?>;
alert(testString);
});
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
I have index.html like this
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var auto_refresh = setInterval(
function ()
{
//alert("abc");
$('#mydiv').load('xyz.php').fadeIn("slow");
}, 1000);
});
</script>
</head>
<body>
<div id="mydiv"> </div>
</body>
</html>
In same folder there is xyz.php file whose code is this:
<?php
echo "My first PHP script!";
?>
When I uncomment //alert("abc"); and comment $('#mydiv').load('xyz.php').fadeIn("slow");
alert message comes every second but vice versa is not working when I am calling php file and commenting alert message. Why?
It´s working for me, but you only can see the content one time, because .load function is replacing the old content, change
$('#mydiv').load('xyz.php').fadeIn("slow");
with this
$('#mydiv').append($('<div >').load('xyz.php'));
I renamed index.html to index.php and called that by localhost/firstproject/index.php. That worked
I'm new to backboneJS so i have a problem sync the data from PHP server with backbone that i dont even get the json data from the php server to backbone model!Help me
Here is my php code
$data = array('1'=>array('id'=> 1, 'description'=>'Pick up milk', 'status'=> 'incomplete' ));
echo json_encode($data);
and the backbone js code
<html>
<head>
<script src="jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="underscore-min.js" type="text/javascript"></script>
<script src="backbone.js" type="text/javascript"></script>
</head>
<script type="text/javascript">
var TodoItem = Backbone.Model.extend({});
var todoItem = new TodoItem();
todoItem.url = '/backboneJS/todo.php';
console.log(todoItem.fetch());
</script>
<body>
</body>
</html>
I cant get the json data from the php to the backbone.What wrong with my code ?
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js" type="text/javascript"></script>
</head>
<body>
</body>
<script type="text/javascript">
var TodoModel = Backbone.Model.extend({
urlRoot: '/backboneJS/todo.php',
initialize: function(){
// Place init message or else
}
});
var todoItem = new TodoModel();
todoItem.fetch({
success: function(todoResult){
console.log(todoResult);
console.log(todoItem.get(1));
}
});
</script>
</html>
Sticking to design pattern also, if you call your todoItem outside of nested function its likely to be executed before the actual fetch() is performed. Tested locally.