Setting PHP session variables with ajax - javascript

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.

Related

Ajax post not working codeigniter

I am using codeigniter 3.1
Ajax post not working and i am getting 403 (Forbidden) in console.
[POST http://localhost/test/post 403 (Forbidden)]
HTML
<div class="post">
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
</div>
<button id="post">Submit</button>
JAVASCRIPT
$('#post').on('click', function () {
var value1=$("#data1").val();
var value2=$("#data2").val();
$.ajax({
url: window.location.href+'/post',
type: "POST",
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
});
CONTROLLERS
public function post()
{
$data1 = $this->common->nohtml($this->input->post("data1", true));
$data2 = $this->common->nohtml($this->input->post("data2", true));
$this->data_models->update($this->data->INFO, array(
"data1" => $data1,
"data2" => $data2,
)
);
}
If you want CSRF protection on (a good idea) then you must pass the CSRF token when posting form data - via AJAX or not. Consider this approach.
The easiest way to put the token in your form is to use Codeigniter's "Form Helper" (Documented here) You can load the function your controller or use autoloading. This view code assumes you have the helper loaded.
HTML
<div class="post">
<?= form_open('controller_name/post'); //makes form opening HTML tag ?>
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
<?php
echo form_submit('submit','Submit', ['id'=>'post']); //makes standard "submit" button html
echo form_close(); // outputs </form>
?>
</div>
The form_open() function also automatically adds a hidden field containing the CSRF token to the HTML.
Javascript
$('#post').submit(function( event ) {
//the next line will capture your form's fields to a format
//perfect for posting to the server
var postingData = $( this ).serializeArray();
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
data: postingData,
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
controller
By the time $_POST gets to your controller the CSRF token has been striped away so you don't have to worry about it "polluting" your incoming data.
public function post()
{
//get all the posted data in one gulp and NO, you do not want to use xss_clean
$posted = $this->input->post();
//With the above the var $posted has this value (showing made up values)
// array("data1" => "whatever was in the field", "data2" => "whatever was in the field");
//sanitize the field data (?)
//just stick the clean data back where it came from
$posted['data1'] = $this->common->nohtml($posted["data1"]);
$posted['data2'] = $this->common->nohtml($posted["data2"]);
$this->data_models->update($this->data->INFO, $posted);
//you must respond to the ajax in some fashion
//this could be one way to indicate success
$response['status'] = 'success';
echo json_encode($response);
}
You could also send back some other status if, for instance, the model function reported a problem. You then need to react to that status in you javascript. But if you don't respond it will likely result in problems down the road.

Failing ajax function and some advice on how to debug jquery/ajax calls

I am working on a project for a crm(just to learn) and i have trouble with an ajax function.
<div class="dropdown">
<label>Name</label>
<select class="named" name ="named" id="named" onchange="userData('<?php echo $client['client_name']; ?>')">
<?php
$clients=mysqli_query($db->db,"SELECT client_name FROM clients");
foreach($clients as $client): ?>
<option value="<?= $client['client_name'];?>"><?= $client['client_name']; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Location</label>
<input type="text" class="form-control" name="locationd" id="locationd"/>
and the ajax function
function userData(name){
alert('debug');
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'adminAction.php',
data: 'action_type=clientdata&name='+name,
success:function(data){
alert('debug');
$('#locationd').val(data.client_location);
}
});
}
its a mysql generated dropdown and on change it should fill the location input with this clients location but it doesnt work.Apache returns no errors but i am kinda noob especially when it comes to debugging ajax calls(how the ** can i see what data it sends and receives ? :D).Thanks for your help in advance !!
I post the adminaction.php code too
if($_POST['action_type'] == 'clientdata'){
$tblName = 'clients';
$conditions['where'] = array('client_name' =>$_POST['named']);
$conditions['return_type'] = 'single';
$client = $db->getRows($tblName,$conditions);
echo json_encode($client);
$tblName = 'clients_contact';
for anyone interested i fixed it like that
function userData(){
userData = $("#named").serialize()+'&action_type=clientdata';
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'adminAction.php',
data: userData,
success:function(data){
$('#locationd').val(data.client_location);
}
});
}
Usually the main mistake with ajax calls is, that they don't send the expected requests or don't receive the expected results. Both of those can at least be seen with almost every decent browser by:
pressing F12,
going to the network tab and then
check the requests that are made from this point on (sometimes a reload of the page is necessary).
Also: almost every decent browser has a javascript debugger somewhere, where you can set breakpoints and step through your code, while watching all the variables of interest.
If your AJAX output is in JSON format you can use $.parseJSON(result) to decode your JSON data to Array.

Post data to current php page with ajax

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 :)

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.

why is my form not submiting using ajax

bit of a selfish question but I am really strugerling with ajax in general so I need some help. So basically Im trying to update and sql database using an 'onblur' function. heres my code:
code on index.php
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
and code on saveStatus.php
<?
require 'core.php';
require 'connect.php';
$status = $_POST['feed_id'];
$idPerson = $_SESSION['user_id'];
$query = "UPDATE person SET status = '".mysql_real_escape_string($status)."'
WHERE idPerson = '$idPerson'";
$query_run = mysql_query($query);
?>
at the moment the sql database does not update when i click of the input box. Any help would be great!!
Answer:
You have to devide scripts and html output
You forget );.You have to close $.ajax block.
You miss } closing function saveStatus().
Code:
<script>
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}); // <-- Also, you forget `);` here
} // <-- Also, you foget closing `}` here
</script>
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
Not error, but advice:
Also, note this: you used jQuery ajax function, so use jQuery in other cases too (you used pure JavaScript instead).
You getting value this way:
var status = document.getElementById("statusForm").value;
Use jQuery syntax instead:
var status = $("#statusForm").val();
Additional info
As, #Utkanos noticed in comments to this answer:
...all of which would be obvious if you look in the error console.
You have to use some debug tool, like FireBug or DevTools (Chrome, also in Chrome you can use CTRL+SHIFT+J). Not have to. You MUST do it.

Categories

Resources