post in ajax with php get me undefined index - javascript

i want to send/pass data from the client to server by (ajax to php) but when i try this code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
console.log(w);
}
});
</script>
<?php
echo $_POST['data'];
?>
in my browser i got success print out which mean that the javascript code is working fine i guess , by in php i got Undefined index
p.s my file name is loo.php all the code is in the same file
edit: i have tried to separate my files like this:
my loo.php file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'test.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>
my test.php file:
<?php
echo $_POST['data'];
?>
still got undefined index
p.s. i navigate Manual to test.php file after i run loo.php file

You get this error because when loading the page the POST request has not yet been sent. So show the submitted data only if it exists, otherwise, show the JavaScript code.
<?php
if (isset($_POST['data'])) {
die($_POST['data']);
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>

Try this.
<?php
$data = json_decode(file_get_contents('php://input'), true);
echo $data['data'];
?>

Try this
Html file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data_value"></div>
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
$("#data_value").html(response);
}
});
});
PHP file (loo.php)
<?php
print_r($_POST);
?>

try to change the handler this way:
if(isset($_POST['data'])){
function return_data() {
die(json_encode($_POST['data'])));
}
return_data();
}

Answer after you edit the question:
$_POST is the array sent by the HTTP Post request. so if the request to the page named test.php or whatever is not HTTP POST Request the $_POST array will be empty. but the $_GET array may have some data if you sent them.
and navigation to a page is a get request to that page unless you used a form with method="post".
so what you are doing with ajax call is correct. but navigating to test.php manually without a form with post method is not gonna fill the $_POST array.
because when you make the Ajax call, it is done, it just makes the post-call correctly and everything is ok but when you navigate to that page it is a get request and it won't fill the $_POST array.
to do so, you don't need ajax at all. you can have this form
<form method="POST" action="test.php">
<input type="text" name="data" value="some data" />
<input type="submit" value="submit" />
</form>
so either you use ajax and handle whatever you want to handle in the ajax success method. or use form and send the request to the page and handle it there.
the answer to the question before the edit
If they are in the same file it won't work like that, because when the file loads the $_POST['data'] is not exists at all, and after you run the ajax call, it exists within that call, not in your browser window.
so you can check if $_POST['data'] exists so you are sending it from ajax call so you can return it and use it inside your ajax success function.
conclusion:
you cannot put them in the same file and expect ajax will load before the actual php.
it will first load the whole file then it will run the ajax.
the undefined index is from the server before you even see the HTML page.
A solution could be:
File with your html and ajax functions index.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
// use the response here
console.log(w);
}
});
</script>
and another with your logic loo.php
<?php
header("Content-Type: text/plain"); // if you want to return a plain text
// if you want to return json it could be header('Content-type: application/json');
echo isset($_POST['data'])? $_POST['data']: ''
?>

Related

How to pass variable from php for() to ajax when clicking a button?

when clicking (.refresh)button、how would you pass $data_name to ajax which you'll get by for() in body field of php script?
I would like to pass the variable for selecting data from database.
2Scripts:
(1) html formated .php file>
ajax written in header field,
php for() written in body field
(2) SQL select script in php, added
$dataname= $_POST['dataname'];
In for() I'm getting data from DB and showing data tables, DATA A~C.
When clicking the button for each data, I would want to get the new data from data base.
I was able to get it, just writting "A" for Ajax, but I would want to pass variable for many tables.
[enter image description here][1]
[1]: https://i.stack.imgur.com/zpJ7B.png
<head>
<script>
$(document).ready(function(){
$('.refresh').click(function(){
$.ajax({
// 通信先ファイル名
url: "select.php",
type: "POST",
data: ({"data_name": $data_name}),
success: function(data) {
//more code
},
error: function(data) {
//more code
}
});
</script>
</head>
<body>
<?php
//more code for(){  getting $data_name(A、B、C)here >
echo <<<EOD
<button class='refresh'>REFRESH DATA</button>
<table class='show'></table>
EOD;
?>
</body>
You can use a different PHP to return the JSON or the same.
So if you want to use the same script you basically want to send a JSON with the data when your PHP script gets a POST.
So you have to check:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request comes from Javascript doing POST
// Query Database and return a JSON with the field "data_name"
} else {
// Render your form like now you're doing now, the request com from the browser loading the page
}
//select.php
<?php
$data= $_POST["data_name"];
echo json_encode( $data);
?>
<script>
$(document).ready(function(){
$('.refresh').click(function(){
$.ajax({
// 通信先ファイル名
url: "select.php",
type: "POST",
data: ({"data_name": $data_name}),
success: function(data) {
// getting $data_name(A、B、C)here
},
error: function(data) {
//more code
}
});
</script>

How to handle jQuery Ajax call on the same page?

I am trying to make a get request using jQuery ajax, want to get the response on the same page. I tried this code...
<p>This is a Ajax get request.</p>
<button class='send'>click</button>
<p id='pritam'></p>
<?php
if (isset($_GET['name'])) {
echo $_GET['name'];
exit;
}
?>
<script>
$(document).ready(function() {
$(".send").click(function(){
$.ajax({
type: "GET",
data: {name: 'praveen'},
success: function(data) {
$("#pritam").html(data);
}
});
});
});
</script>
But I am getting an error, It executes all page element again when I click on the button including button tag.
You can do it like this
<?php
if (isset($_GET['name'])) {
echo $_GET['name'];
exit;
}
?>
<p>This is a Ajax get request.</p>
<button class='send'>click</button>
<p id='pritam'></p>
<script>
$(document).ready(function() {
$(".send").click(function(){
$.ajax({
type: "GET",
data: {name: 'praveen'},
success: function(data) {
$("#pritam").html(data);
}
});
});
});
</script>
You should put your PHP section on top of this php file.
EDIT:
That's because a PHP file executed from top to bottom. When the ajax request was processing, the contents above the PHP section will output first. That will cause the data response you got contains page html tags.

jQuery ajax not passing post data to php page

I try to get post data from using alert() and its worked problem is that data is not passing to php page result is always {"success":false,"result":0}
What I want is send password to php page and hash it using password_hash() and return result
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.ajax({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="spass" >
<h4>Change Your Password</h4>
<input type='password'name="passc" >
<!--<input type='password' name="cpass" id="cpass"> -->
<input type="submit">
</form>
**this my php code**
<?php
header('Content-type: text/javascript');
$json=array(
'success'=>false,
'result'=>0
);
if(isset($_POST['passc']) && !empty($_POST['passc'])) {
$pass=password_hash($_POST['passc'],PASSWORD_DEFAULT);
$json['success']=true;
$json['result']=$pass;
}
echo json_encode($json);
?>
You can test that your data has not actually been passed to a PHP page.
In the PHP code, do the following: echo $ _POST ['YOUR_VARIABLE'].
Check the INSPECT_ELEMENT / NETWORK browser to make sure you actually send data to the correct link. Your link may be relative, so you may be sending data to the wrong link.
So, try to put the entire link in the ajax url
$ .ajax ({
url: 'HTTP: //WHOLE_LINK_IN_HERE.COM/passwordhashing.php',
});
SET method in Ajax: type: "POST"
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
**i used $.post() instead of using $.ajax() and it fix my problem**
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.post({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});

Sending POST parameters between PHP files using AJAX calls

I have a PHP file test.php that has a simple link, which after being clicked, calls an AJAX function to send data as POST parameters to another file testPHP.php. The second file then receives the POST parameters from the AJAX call and then alerts the contents inside the $_POST array. The issue I am facing is that in the second file, the $_POST array is empty (I checked that using print_r($_POST)), so I think that the data hasn't passed through.
These are the 2 files:
test.php
<a id="link" role="button" href="testPHP.php">Test</a>
<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
data: {
parameter1: 'test',
parameter2: 'test2'},
success: function(msg) {
alert('wow' + msg);
}
});
alert('function end');
document.getElementById('#link').setAttribute('href','testPHP.php');
});
testPHP.php
if(isset($_GET))
{
echo "<script>alert('GET is there');</script>";
print_r($_GET);
}
if(isset($_POST))
{
echo "<script>alert('POST is there')</script>";
print_r($_POST);
}
if(isset($_POST['parameter1']))
{
echo "<script>alert('$_POST is set')</script>";
header('Location: HomePage.php');
}
else
{
echo "<script>alert('No post variable set')</script>";
}
What I have tried so far is to send a SUCCESS message if the AJAX call has been executed successfully, and it does alert me the Success message. I have also checked to see the contents of the $_POST array in the 2nd file to see if I am receiving data in a format other than a POST request (like a string that might have to be exploded to get the contents), but the $_POST array comes up empty.
This is the output I get when it redirects to the 2nd page:
Array() Array()
The $_POST and $_GET (for testing purpose) arrays come up empty.
I have also gone through the AJAX documentation, but can't get this simple POST data transfer to work. Can someone please help me with this issue so that I can understand how to properly send POST parameters and receive the data into $_POST['parameter1'] and $_POST['parameter2'] strings so I can process the data further.
Note: I have used the FORM's POST method using hidden form elements and that works fine, but I want to try this approach to better understand how AJAX works.
A slightly different version of the above which should help you solve your problem. For ease in debugging it is all one page but you can clearly see the script in operation once you click the button. Simply echoing javascript in the php code and hoping it will execute client side is not going to work - simply echo a message or a JSON object would be better.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
print_r( $_POST );
exit();
}
?>
<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<script>
$('#link').click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: location.href,
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}
});
alert('function end');
});
</script>
</body>
</html>
As 2 separate pages ( both in same directory otherwise edit page to the ajax target )
<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<br /><br />
<script>
$('#link').click(function(e) {
e.preventDefault();
$.ajax({
url: 'jquery-ajax-target.php',
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}
});
});
</script>
</body>
</html>
And the ajax target, jquery-ajax-target.php
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
$parameter1=( isset( $_POST['parameter1'] ) ) ? $_POST['parameter1'] : false;
$parameter2=( isset( $_POST['parameter2'] ) ) ? $_POST['parameter2'] : false;
$_POST['modified']=array(
'p1'=>sprintf('modified %s', strrev( $parameter1 ) ),
'p2'=>sprintf('modified %s', strrev( $parameter2 ) )
);
$json=json_encode( $_POST );
echo $json;
exit();
}
?>
Here is my version. It will return a JSON response to your ajax which will be visible in your console for easy debugging.
Your main page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="link" role="button" href="#">Test</a>
<script>
$(document).ready(function(){
$("#link").click(function(e) {
e.preventDefault();
console.log('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
dataType: 'json', //This tells your ajax that you are expecting a json formatted string as a response.
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
console.log(msg); //This will show the results as an object in your console.
}
});
console.log('Function End');
//document.getElementById('#link').setAttribute('href','testPHP.php'); //Why are you doing this. It's not needed.
});
});
</script>
Your testPHP.php page:
$results = array();
if(isset($_GET)){
$results[] = array(
'GET' => 'TRUE',
'getData' => $_GET
);
}
if(isset($_POST)){
$results[] = array(
'POST' => 'TRUE',
'postData' => $_POST
);
}
echo json_encode($results);
Here is an explanation of what is happening:
You make an initial call to your ajax by triggering some event. In your case it is the click of the link.
The click function leads to the actual ajax call which simply sends a post request to the testPHP.php.
The testPHP.php receives the post request and performs some sort of operation with the data that was provided by the ajax call.
The testPHP.php then sends back some sort of answer back to the ajax function. The data will be available in the success function.
You then get to decide how to use the data that was passed back from the testPHP.php page to the success function.
This is all done without your original page's code being refreshed.
You are not actually redirecting your user to another page.. You are just telling your page to goto another page and do some operation, which then gets reported back to the original page for you to do something with.
Hope it helps.
It does work after removing type attribute on script tag. I am using <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> before main script tag. It is working here. Also close the script tag. I hope I can help.
Also change the
document.getElementById('#link').setAttribute('href','testPHP.php');
to
document.getElementById('link').setAttribute('href','testPHP.php');
The problem with your code is that you are using javascript to change the attribute and in javascript once you used getElementById you no longer have to use # sign. try the following and it will work fine.
<?php
if(isset($_GET))
{
echo "<script>alert('GET is there');</script>";
print_r($_GET);
}
if(isset($_POST))
{
echo "<script>alert('POST is there')</script>";
print_r($_POST);
}
if(isset($_POST['parameter1']))
{
echo "<script>alert('$_POST is set')</script>";
header('Location: HomePage.php');
}
else
{
echo "<script>alert('No post variable set')</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="link" role="button" href="index2.php">Test</a>
<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
data: {
parameter1: 'test',
parameter2: 'test2'},
success: function(msg) {
alert('wow' + msg);
}
});
alert('function end');
document.getElementById('link').setAttribute('href','testPHP.php');
});
</script>
</body>
</html>
Furthermore it's a good practice to use the failed callback for the request.
error: function (xhr, status, error) {
alert(" Can't do because: " + error);
},

Ajax call to insert to database not working

I'm trying to do an Ajax call on button click to insert to a database through a PHP file. I want to use AJAX to achieve this, but it does not show the alert dialog on success nor does it insert the data to the database. Here is the code I have:
AjaxTest.html:
<button type="button" onclick="create()">Click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
function create () {
$.ajax({
url: "AjaxTestRegistration.php",
type: "POST",
data: {
'bid': 10,
'kid': 20
},
success: function (msg) {
alert("!");
}
});
}
</script>
AjaxTestRegistration.php:
<?php
include "connection.php";
include "Coupon.php";
$bid = $_GET['bid'];
$kid = $_GET['kid'];
Coupon::insertCoupon($bid, $kid);
?>
If I try to enter AjaxTestRegistration.php manually in the browser like this: ajaxtestregistration.php?kid=10&bid=5, the row gets inserted into the database.
wWhat could be the problem with this code? How to rectify that?
Your PHP handles GET requests.
$bid = $_GET['bid'];
But your ajax function tries to POST
type: "POST",
The easiest here is to get your data by $_POST in php.
I think you should try $__REQUEST method of php and also use $_POST method if you use post from ajax
$bid = $__REQUEST['bid'];
$kid = $__REQUEST['kid'];

Categories

Resources