This is driving me crazy. I'm trying to post a variable to a PHP script using AJAX but while I can verify that $_POST is set, the varibale remains undefined.
I've used almost identical code elsewhere and it works fine - I just cant see what the problem is here.
Here is a very stripped down version of the code -
The JS
$(function(){
$('#load_more_comments').click(function(){
var newLimit = 40;
$.ajax({
url: "scripts/load_comments.php",
data: { limit: newLimit },
type: "post",
success: function(result){
// execute script
},
error: function(data, status, errorString)
{
alert('error');
}
});
return false;
});
});
The PHP
if (isset($_POST)) {
echo "POST is set";
if (isset($_POST['limit'])) {
$newLimit = $_POST['limit'];
echo $newLimit;
}
}
UPDATE
var_dump($_POST) returns array(0) { } so I know that AJAX is definitely is not posting any values
Using slightly modified version of the above I am unable to reproduce your error - it appears to work fine.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
if( isset( $_POST['limit'] ) ){
echo $_POST['limit'];
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
$(function(){
$('#load_more_comments').click(function(){
var newLimit = 40;
$.ajax({
url: location.href, //"scripts/load_comments.php",
data: { limit: newLimit },
type: "post",
success: function(result){
alert( result )
},
error: function(data, status, errorString){
alert('error');
}
});
return false;
});
});
</script>
</head>
<body>
<!-- content -->
<div id='load_more_comments'>Load more...</div>
</body>
</html>
Try :
if (count($_POST)) {
Instead of
if (isset($_POST)) {
Related
instead of getting the object as the responce data I'm getting the entire html page (the page I'm posting to) therefore I cannot retrieve the object in the php script
//this is an example of the object not the actual abject
var data={lat:"1.098", lng:"31", city:"durban"};
$.ajax({
type: "POST",
url: "/webapp/index.php/",
data: data,
async:true,
cache: false,
success: function(data)
{
alert(data.status);
console.log(data);
},
error: function (xhr, status, error) {
alert(status);
alert(xhr.responseText);
}
});
Since the server will consume <?php /*some PHP scripts */ but than return the following <!DOCTYPE html><html> etc... as response - you need to exit
index.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Handle POST requests here
echo "HELLO WORLD!";
exit; // <<< You need to exit here!
}
?>
<!DOCTYPE html>
<html lang="en">
<head><!-- head stuff --></head>
<body>
SOME FORM
<script>
// Some AJAX to "self" (index.php)
// success response: "HELLO WORLD!"
</script>
</body>
</html>
Or even shorter:
exit("HELLO WORLD!");
I tried all the stackoverflow posts about this, I spend two days and still no success 😔, I am trying to pass a JavaScript variable to a PHP variable, I tried this for example and still not succeed, it does not print noting on the screen, here is a full code:
here cc.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//treehouse code
var $my_variable = "something";
$.ajax({
url: 'cc.php',
data: {x: $my_variable},
type: 'POST'
});
});
</script>
</body>
</html>
and here cc.php:
<?php
if(isset($_POST['x'])){
echo $_POST['x'];
}
?>
What should I do?
You don't do anything with the result of the AJAX call. Add a callback function:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//treehouse code
var $my_variable = "something";
$.ajax({
url: 'cc.php',
data: {x: $my_variable},
type: 'POST'
}).done(function (result) {
alert(result); // <--- do something with the result
});
});
</script>
</body>
</html>
And your PHP code remains unchanged:
<?php
if(isset($_POST['x'])){
echo $_POST['x'];
}
?>
What you do in that callback function is up to you. You can alert() the value, log it to the console, write it somewhere on the page, etc.
If you want to print it on the screen you should use success: function(data)$('#result').html(data)} here is code example:
$(document).ready(function() {
$('#sub').click(function() {
var $my_variable = "something";
$.ajax({
url: 'cc.php',
type: 'POST',
data: { x: $my_variable },
success: function(data) {
$('#result').html(data)
}
});
});
});
You can try $.post too
$.post( "cc.php", { x: $my_variable} );
I have this PHP file:
JSONtest.php
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
I want to alert this variable's value using Ajax and JSON, and for that I've written this script:
learningJSON.php
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
data: data,
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
But when I click the button, I get this error message:
learningJSON.php:14 Uncaught ReferenceError: data is not defined
What wrong I'm doing? How can I fix this?
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Nope, it doesn't. Whats the point in converting a simple number to JSON? It stays the number 5
Now the real problem. Yes your data variable is not defined anywhere in your JavaScript code. If you have no data to send, remove that parameter.
However if you still want to pass some data, define it accordingly then. For example
data: { fname: "John", lname: "Doe" }
Now let's say on your next exercise you want to post form data you can use this nice function named serialize(). This will take all the postable fields from your form and send them along with this request.
data : $("#formID").serialize()
Data variable is not defined, you can delete that
Php file
<?php
$a = $_REQUEST['number'];
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Javascript file
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
//data: {'number' : 10}, //this is when you need send parameters to the call, uncomment to send it parameters
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
I think this one should be perfect for you.
We need 3 files
index.php
login.js
login.php
That mean when user submit [index.php] script js file [login.js] running ajax process script [json] in login.js by collect all data from form input [index.php] and send and run script login.php ... This is powerful script of ajax & json
check code below
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="login.js" type="text/javascript" charset="utf-8"> </script>
</head>
<body>
<form method="post" id="login" name="login">
Email: <input type="email" id="log-mail" name="log-mail" > <br />
Password: <input type="password" id="log-pass" name="log-pass" > <br />
<button type="submit" >Log in</button>
</form>
</body>
</html>
login.js
$(document).ready(function(){
// #login = login is the name of our login form
$('#login').submit(function(e) {
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
window.location=msg.txt;
}
}
});
e.preventDefault();
});
});
login.php
<?php
if(isset($_POST['log-mail']) && $_POST['log-mail'] != '' && isset($_POST['log-pass']) && $_POST['log-pass'] != '' ) {
$_data_ = 'index.php?user_data='.$_POST['log-mail'];
echo msg_result(1,$_data_);
}else{
$msg_att = "index.php?login_attempt=1";
echo msg_result(0,$msg_att);
}
function msg_result($status,$txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
you can see on your url if you
complete all field => ...index.php?user_data=user_data#gmail.com
uncomplete => ...index.php?login_attempt=1
Hope this solve your issue
I'm trying to write a short ajax code to echo the word 'hello' to the screen, but so far I'm not having any luck. If anyone know what I'm doing wrong, please correct me, and let me know. Thank you.
test6.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax() {
$.ajax({
type: "POST",
url: 'testing.php',
data:{action:'call_this'},
error: function(xhr,status,error){alert(error);},
success:function(html) {
alert(html);
}
});
}
</script>
echo hello
testing.php
<?php
if($_POST['action'] == 'call_this') {
echo "hello";
}
?>
I made some little changes to your code, like adding quotes for 'action', and creating a button because <A HREF has some issues with click event (buttons don't have those issues), here it is, now it works to me, let me know if it works to you too :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : {'action':'call_this'},
url : 'testing.php',
success: function ( data ) {
document.getElementById( "my_div" ).innerHTML = data;
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
echo hello
<br/><br/>
<button onclick="myAjax()">echo hello</button>
<br/><br/>
<div id="my_div"></div>
</body>
</html>
You have two problems. First, you have a syntax error. You need a comma after error:
function myAjax() {
$.ajax({
type: "POST",
url: 'testing.php',
data:{action:'call_this'},
error: function(xhr,status,error){alert(error);} /* this comma --> */ ,
success:function(html) {
alert(html);
}
});
}
Second, since you are using an anchor (<a>) tag, when you click on the tag it follows the link. You have to prevent that from happening. You can:
Not use an <a> tag
Put a href to something like # or javascript:void(0)
Make the function it calls return false
Use event.preventDefault
See it on JSFiddle
Edit:
On a side note, you may prefer to just use JavaScript to bind the event handler. This way you get a further separation of JS and HTML, which is typically preferred. Something like this should work:
$("#sendAjax").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/echo/html/',
data:{html:'call_this'},
error: function(xhr,status,error){alert(error);},
success:function(html) {
console.log(html);
$("#result").text(html);
}
});
});
Then in your HTML you don't need the onclick handler:
echo hello
See it on JSFiddle
ajaxcheck.js
var val = "hai";
$.ajax(
{
type: 'POST',
url: 'ajaxphp.php',
data: { "abc" : val },
success :function(data)
{
alert('success');
}
}
)
.done(function(data) {
alert("success :"+data.slice(0, 100));
}
)
.fail(function() {
alert("error");
}
);
ajax.html
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="ajaxcheck.js"></script>
<title>ajax request testing</title>
</head>
<body>
</body>
</html>
ajaxphp.php
<?php
$v_var = $_POST["abc"];
print_r($_POST);
if(isset($_POST["abc"]))
{
echo $v_var;
}
else
{
echo "Data not received";
}
?>
When I run the ajax.html file ,I get success alert. But when I run ajaxphp.php file it shows notice like:
undefined index abc
Why is that the data is not received in $v_var ? where i am mistaking ?please help.
Actually the ajaxphp.php file is used to receive the data from the
post method and i will give response .
In First case by using ajax post method it will call to ajaxphp.php file.
In Second case your using direct file call without any post data(that's way it shows error)
Try this
var val = "hai"
$.post( "ajaxphp.php", {'abc':val}function( data ) {
alert( "Data Loaded: " + data );
});
jQuery expects an object as data, remove the double-quotes:
data: { abc : val }