Sending POST parameters between PHP files using AJAX calls - javascript

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);
},

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.

post in ajax with php get me undefined index

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']: ''
?>

How can we apply both JavaScript and PHP to a button?

When I click a button:
I need the JavaScript to perform some function.
Also run PHP code as well.
How can we achieve this?
PHP is only run by the server and responds to requests like clicking on a link/button (GET) or submitting a form (POST).
HTML & JavaScript is only run in someone's browser.
<html>
<?php
function PhpFunction() {
echo 'A php function';
}
if (isset($_GET['JsFunction'])) {
PhpFunction();
}
?>
Hello there!
<a href='index.php?JsFunction=true'>Run PHP Function On Click Of This Link</a>
</html>
Alternatively ,
You can create a ajax request to run a php code in your server..
Ajax can help you to send an asynchronous request to the server that php (or other) can catch, in this way you can implement and play with some callback functions
$.ajax({
url : "yourScript.php", // the resource where youre request will go throw
type : "POST", // HTTP verb
data : { action: 'myActionToGetHits', param2 : myVar2 },
dataType: "json",
success : function (response) {
//in your case, you should return from the php method some fomated data that you //need throw the data var object in param
data = toJson(response) // optional
//heres your code
},
error : //some code,
complete : //...
});
in your php script, you'll receive the request posted throw the superglobal vars like POST (for this example)
<?php
$action = (string)$_POST['action']; //this is unsecure, its just for the example
if("myActionToGetHits" == $action) {
//here you have to call your php function and so on..
$data = hitsMonth();
echo $data;
exit;
}
here is html
<a href="#" onclick="javascript:functionName(arg1, arg2);">
This is a basic example to do it, there are lots of ways to do.
Have javascript do the submit:
function button1() {
// js code here
var formelt = document.getElementById("form1");
formelt.submit(); // this will submit the form to server
}
Example =>
<button class="btn-test">Btn Test</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
jQuery('.btn-test').click(function() {
js_do_something();
php_do_something();
});
function js_do_something() {
console.log('something done from js');
}
function php_do_something() {
console.log('something done from php');
jQuery.ajax({
type: "POST",
url: 'you_php_file.php',
data: {param: 'btn-test-click'},
success: function () {
console.log('success');
}
});
}
</script>
There you have how to execute a php function with on Onclick.
Execute PHP function with onClick
You can execute a Javascript function assuming you´re using jQuery like this:
jQuery('#id-button').on('click', function(){
// your function body
});

Ajax call request in CodeIgniter with CSRF enabled

I am using an ajax call to save value of a radio button through hidden field in database using ajax call, used an alert to see if its working, and it is.
The URL I mentioned in the ajax call is redirecting it to a controller but I used an alert to see if its working, but its not working. Can't locate what's the issue.
Here is the code of ajax call in view:
<script type="text/javascript">
$('#save').click(function(){
var hint=$('#hidfield').val();
alert('Oops, your response is '+hint);
$.ajax({
url: '<?php echo base_url();?>welcome/save_answer',
type: "post",
dataType: "html",
data:{hint:$hint, <?php echo $this->security->get_csrf_token_name();?>: "<?php echo $this->security->get_csrf_hash();?>"},
success: function(data) {
}
});
});
</script>
Here is the controller:
function save_answer()
{
alert('You Can Do It !!');
$data = array(
'hint'=>$this->input->post('hint')
);
$this->base_model->save_answer($data);
}
Here is the model:
function save_answer($data)
{
$this->db->insert('questions',$data);
}
Please suggest some way out.
You cannot used javascript "alert()" inside controller.
instead of "alert('You Can Do It !!');" use "die('You Can Do It !!');" to debug, and check in to your console.

Categories

Resources