Pass JS var to PHP var - javascript

I need to have a "global" variable because I need to use it in different page and I want to modify it too: I think that I need to use $_SESSION
I need to change this variable, when the user click on dropdown or list.
I have this:
SOLUTION 1
PageA:
$('#list.test li').on('click',function(){
choice=$(this).attr('id');
$.ajax({
url: "PageB.php",
data: {word : choice},
dataType: "html",
success: function (data) {
$('#content_table').html(data);
}
});
});
PageB
session_start();
$_SESSION['b']=$_GET['word'];
echo $_SESSION['b']; // It works
PageC for verify the result
session_start();
echo $_SESSION['b']; // Error !!
In my PageC, I have an error ( Notice: Undefined index: b )
Is it possible to update session variable with ajax ?
SOLUTION 2
PageA: I want to passe the id JS var to PHP var
$('#list.test li').on('click',function(){
choice=$(this).attr('id');
<?php $_SESSION['b'] ?> = choice; //<--- it is possible ?
$.ajax({
url: "PageB.php",
data: {word : choice},
dataType: "html",
success: function (data) {
$('#content_table').html(data);
}
});
});
This solution doesn't work because AJAX and PHP are note in the same side (client/server).
Thank you

You can push data to cookies via JavaScript, smth like document.cookie = "key=value";
And receive it on back-end like $_COOKIE["key"];.

$_SESSION['b']=$_GET['projet']; should be $_SESSION['b']=$_GET['word'];

Related

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Passing Php variable it Ajax

Hi I'm trying to pass a php variable from produto.php to another file descProduto.php it ajax but without success. Please someone can tell me what I'm doing wrong? The ajax is working but I can't get the value on descProduto.php
This is where I click produto.php
<img class="btn-details" src="plus.png" data-idproduto="'.$idproduto.'"/>
My ajax ( diferent file ajax.js)
$(function(){
$(".btn-details").on('click', function(){
var idproduto = $(this).data('idproduto');
$.ajax({
type: "POST",
url: "descProduto.php",
async: false,
dataType: "html",
data: {'idproduto': idproduto},
success: function(result){
console.log("success");
},
error: function(){
console.log("error");
}
});
return false;
});
});
Where I get the variable descProduto.php
if(isset($_POST['idproduto'])){
$idproduto = $_POST['idproduto'];
echo $idproduto;
}
Thanks
Why using AJAX ? .You can't use for this matter.just use session
In page1.php
<?php
session_start();
$_SESSION['var'] = 'foo'
In Page2.php
echo $_SESSION['var']; //foo
First of all check whether your $idproduto actually prints on produto.php (Developer Tools/ FireBug/ View Source).
Then console.log(idproduto) before sending the ajax post to see whether it sets correctly.

Javascript passing variable issue not returning

Hi All I have the following code to pass a JS variable using AJAX as seen below:
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
data: { 'id': id },
success: function(msg){
window.alert(msg);
}
});
}
if I put an alert box in I can see the object id is successfully getting grabbed. however if in php I want to simply return the variable - I am getting a null has anyone got any ideas:
heres my PHP function (I am using Codeigniter):
public function passid(){
$courseId = $this->input->post('id');
echo $courseId;
}
EDIT: the success alert box appears - but appears blank and that is my issue I am hoping to see the ID
1. Can you make sure id equals something by doing this:
function buttonCallback(obj){
var id = $(obj).attr('id');
alert( id ); // What does it alert?
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
2. Your javascript looks good... Can you try this instead to see if it works:
JS
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
PHP
public function passid(){
$courseId = $this->input->post('id');
$response = array( "id" => $courseId );
header('Content-Type: application/json');
echo json_encode( $response );
}
3. If this does not work, can you try and rename from id to something like poopoo, just to make sure id is not taken and being weird?
4. Can you check what the network response is of your ajax request - Go to developer toolbar and goto network section, make sure you hit the record/play button. then send your request off. When you see your request come up in the network list, check the "details" of it and goto response.

How to send a JQuery Variable to another PHP page via dblclick()?

So guys, I made a listbox and if I dblclick to an item the value of it gets saved into "val", but I can't send it to the next PHP File. I also alerted "val" - the value is really saved in it. I also get the function succes displayed in the browser console. what to do?
thanks
My Function:
$(document).ready(function () {
$("option").dblclick(function () {
var lb = document.getElementById("liste");
var val = lb[lb.selectedIndex].value;
$.ajax({
type: 'POST',
url: 'about.php',
dataType: 'HTML',
data: {
aufid: val
},
success: function (data) {}
});
});
});
PHP Code in about.php:
$id = $_POST['aufid'];
Can you try to see what variables are in the $_POST superglobal?
print_r($_POST);
try to set the url your full adrees
url: 'http://myadress.com/about.php',
java script is running on your local computer so it might send the request to you own pc where no about.php exist

Categories

Resources