Post data to current php page with ajax - javascript

i want to post data to current page with ajax.But i couldnt do that.
I have doctor panel and i wanna get patient's data from 'hastalar' table in my db by using patient's national id:'tc'.Session is using by doctor so i guess i cant use $_SESSION for patient at same time.And i wanna use only one php page.So i cant see my patient's datas in current page.Pls help me guys.
dokyon.php
textbox
<a href="#" id="ara" class="ara" ><br/>SEARCH PATIENT</a>
<input type ="text" id="tc" name="tc" />
JQUERY
<script type="text/javascript" >
$(function() {
$(".ara").click(function(){
var tc = $('#tc').val();
$.ajax({
url:'dokyon.php'//current page
type: 'POST',
data:{tc:tc},
success: function(){
alert(data);
}
});
});
});
</script>
php codes
<?php
$tc=$_POST['tc'];
echo $tc;
$query = mysqli_query($connection,"select * from hastalar where tc_no=$tc");
while($hasta = mysqli_fetch_array($query)){
echo $hasta['name'];}
?>

For your ajax code, you need to add dataType parameter and add the parameter of success: function(data), so like this:
$.ajax({
url:'dokyon.php'//current page
type: 'POST',
data:{tc:tc},
dataType:"html",
success: function(data){
alert(data);
}
});
For additional: always do debuging for sending data with inspect element of browser.
Hopefully it will be success for you :)

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>

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

Setting PHP session variables with ajax

Want to change value of SESSION variable "fullname" without refreshing the page.
My implementation using ajax:
Page 1 html:
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<button onclick="setSession()"> GO </button>
Page 1 script:
<script>
function setSession(){
var fullname = $("#fullname").val();
var dataString = 'fullname=' + fullname;
$.ajax({
type: "POST",
url: "Page2.php",
data: dataString,
cache: false,
success: function( data ) {
if(data === 'True'){
alert("<?php echo $_SESSION['fullname'];?>");
}
}
});
}
</script>
And in Page 2:
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'True';
exit();
It doesn't change the value of the session variable.
Both pages have session_start().
Your code should already be changing the value in the PHP session. You just don't have your client-side script set up properly to show that.
Return some kind of indicator in your PHP script:
<?php
// Page2.php
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'set session fullname to ' . $_POST['fullname'];
Then in your AJAX success function, show that response:
...
success: function( response ) {
alert(response);
}
...
When you use alert("<?php echo $_SESSION['fullname'];?>"); in your success function, PHP will fill in the $_SESSION['fullname'] value in that alert box once when the page loads, and it will never change until the page is reloaded, even if you do successfully update the session value via AJAX.
First, have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?
Second, you're starting a session in a remote page. That session data will not be available in the current page until you reload the current page. In addition you have some wonky quoting in your alert, it should be:
alert("<?php echo $_SESSION['fullname'];?>");
Page 1 HTML
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<button onclick="setSession()"> GO </button>
Page 1 Script
<script>
function setSession(){
$.ajax({
type: "POST",
url: "Page2.php",
data: { fullname: $("#fullname").val() },
dataType: "json",
cache: false,
success: function( data ) {
alert(data.fullname);
}
});
}
</script>
Page 2 PHP Script
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo json_encode(array('fullname' => $_SESSION['fullname']));
It's generally a bad idea to mix server-side and client-side scripts together so try to separate your PHP and Javascript logic. They both execute at different times/stages of a page request life-cycle.
You are setting the variable in JS using PHP Inline coding. You could however echo the session variable in page2 if no post has been set. If you then request page two without any post you can use the response body in JS to get the current set session variable and put it in a JS variable.
Var name;
$.get(‘page2.php’, function(data){ name = data; } );
I’m using the iOS app so above code is not complete but an indication for what can be done.

AJAX to PHP without page refresh

I'm having some trouble getting my form to submit data to my PHP file.
Without the AJAX script that I have, the form takes the user through to 'xxx.php' and submits the data on the database, however when I include this script, it prevents the page from refreshing, displays the success message, and fades in 'myDiv' but then no data appears in the database.
Any pointers in the right direction would be very much appreciated. Pulling my hair out over this one.
HTML
<form action='xxx.php' id='myForm' method='post'>
<p>Your content</p>
<input type='text' name='content' id='content'/>
<input type='submit' id='subbutton' name='subbutton' value='Submit' />
</form>
<div id='message'></div>
JavaScript
<script>
$(document).ready(function(){
$("#subbutton").click(function(e){
e.preventDefault();
var content = $("#content").attr('value');
$.ajax({
type: "POST",
url: "xxx.php",
data: "content="+content,
success: function(html){
$(".myDiv").fadeTo(500, 1);
},
beforeSend:function(){
$("#message").html("<span style='color:green ! important'>Sending request.</br></br>");
}
});
});
});
</script>
A couple of small changes should get you up and running. First, get the value of the input with .val():
var content = $("#content").val();
You mention that you're checking to see if the submit button isset() but you never send its value to the PHP function. To do that you also need to get its value:
var submit = $('#subbutton').val();
Then, in your AJAX function specify the data correctly:
$.ajax({
type: "POST",
url: "xxx.php",
data: {content:content, subbutton: submit}
...
quotes are not needed on the data attribute names.
On the PHP side you then check for the submit button like this -
if('submit' == $_POST['subbutton']) {
// remainder of your code here
Content will be available in $_POST['content'].
Change the data atribute to
data:{
content:$("#content").val()
}
Also add the atribute error to the ajax with
error:function(e){
console.log(e);
}
And try returning a var dump to $_POST in your php file.
And the most important add to the ajax the dataType atribute according to what You send :
dataType: "text" //text if You try with the var dump o json , whatever.
Another solution would be like :
$.ajax({
type: "POST",
url: "xxxwebpage..ifyouknowhatimean",
data: $("#idForm").serialize(), // serializes the form's elements.
dataType:"text" or "json" // According to what you return in php
success: function(data)
{
console.log(data); // show response from the php script.
}
});
Set the data type like this in your Ajax request: data: { content: content }
I think it isnt a correct JSON format.

Update database with html link click using ajax php mysql

I've read through a number of similar questions and tried my hand at putting it to work on my website, but it is not working (when you click the link there is no response on the console and the database is not updated).
Here's what I want to do: I want users to rate a comment +1 by clicking an icon next to the comment. I want that to update my mysql comment_table column called rating with rating+1. When I do it without AJAX (ie, just set the form action to a php page?id=10) it works fine. I can't get the AJAX to update the database though.
My main page with the comment:
<span class="glyphicon glyphicon-chevron-up"></span>
The javascript below that link:
<script type="text/javascript">
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
rating: rating,
id: <?php echo $thisperspective_row['id']; ?>,
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
</script>
and my rating.php file is
<?php
require_once('connectiontodatabase.php');
/* simple comment up and down voting script */
$mode = $_GET['mode'];
$rating = $_GET['rating'];
$id = $_GET['id'];
if ($mode=="vote")
{
// The name of the
$cookie = "nameofmycookie".$id;
if(isset($_COOKIE[$cookie]))
{
echo '<div class="alert alert-warning"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Sorry You have already rated this comment within the last 14 days.</div>';
}
else
{
$expiry = 1209600 + time(); // 14 day expiry
setcookie ($cookie, "voted", $expiry);
mysql_query ("UPDATE comment_table SET rating = rating+$rating WHERE id=$id", $connection);
}
}
?>
The php runs fine and all the variables are listed properly when I view the source. However, when I click the link, there is no response at all and the console does not output the response. What am I doing wrong? Thanks in advance!
Firstly you should change the way you are detecting the click event. Check out this fiddle. Then secondly you need to pass all the variables through in one JSON string using the data option. Your code should look something like this:
<span class="glyphicon glyphicon-chevron-up clickable"
data-rating="1"
data-id="<?php echo $thisperspective_row['id']; ?>"></span>
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
mode: "vote",
rating: $(this).data('rating'),
id: $(this).data('id')
};
$.ajax({
type: 'GET',
url: 'rating.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
First off all, check that you are loading jQuery, then use this code
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
data: { rating: rating, id: id },
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
is working for me.
note that I removed ` inside Ajax, since you are already sending the params in the function, also to send params you have to use data:, you can see more examples here Ajax jQuery

Categories

Resources