How to handle jQuery Ajax call on the same page? - javascript

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.

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>

Ajax not able to post javascript variable to php

I want to post values of a JavaScript variable to a PHP page, and then use those values there.
I get back a new HTML page, which I did not want to happen. Also, it is showing the error message produced by:
echo"some error";
What am I missing? I don't understand why this happens?
Here is my html file try.html
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php" target="_blank">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
dataType: 'script' // I am not sure about what I write here script,json,html?
});
});
</script>
</body>
</html>
And this is my PHP file try.php
<?php
if(isset($_POST['text']))
{
$text = $_POST['text'];
echo $text;
}
else {
echo"some error";
}
?>
In try.php if you echo something which in turn will comeback to try.html.
If you just want to post the data to try.php and echo there the just use form and submit. You dont need ajax in that.
Ajax is to send the data/receive back without reloading the existing page. The response will be seen in the current page itself.
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
var json_params = {
text: val1
};
var json_data = JSON.stringify(json_params);
$.ajax({
type: 'POST',
url: 'try.php',
data: json_data,
dataType: "html",
success: function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
In the try.php page you can place this code
<?php
if (isset($_POST)){
$data = json_decode(file_get_contents('php://input'));
print_r($data);
}
else{
echo "not set";
}
?>
Firstly, remove script from data-type.
This is how you can pass the data to php file:
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
});
dataType - The type of data that you're expecting back from the
server. Here you don't want anything in return then it's fine. If you
are expecting anything like json or something, you can specify it.
If You want anything in response, you can handle in this manner
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
success: function (data) {
//Your success handler code
},
});
success - A callback function to be executed when Ajax request
succeeds.
Firstly remove href from link. By this it is directly redirecting to try.php
<a id="button" href="javascript:void(0);" target="_blank">send data</a>

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

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 to include php file on click

Is that possible to output some php code, in JS, than includes a php template when clicked on a buton? I am trying the following way like below without success. How can i do it?
$("#show").one('click', function () {
$("#showTemplate").html("<?php require_once 'php-template.php'; ?>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "showTemplate"> </div>
<button id="show"></button>
Use ajax instead and since you want to output some php code then you'll have to set the header from your php template to text/plain.
$.ajax ({
url: 'php-template.php',
type: 'get',
dataType: 'text',
success: function (data){
$('#showTemplate').html (data);
});
})
And in your php template, you'll need to set the header,
header ('Content-Type: text/plain');

Categories

Resources