I'm using a session variable in PHP to manage the current language in a multi-language site. To achieve what I want I'm using a flag icon that when clicked (jQuery) it tells lang_json.php to switch the session variable to the new language.
I'm not getting errors on the jQuery side:
var sendData = 'en';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "lang_json.php",
data: ({newLang: sendData}),
dataType: "json",
success: function (msg) {
alert('Success');
},
error: function (err){
alert('Error');
}
});
But the PHP file is not setting the session variable:
lang_json.php:
<?php
// Session variables
session_name('aklogin'); // Starting the session
session_start();
if( isset($_POST['newLang']) ){
$_SESSION['current_lan'] = $_POST['newLang'];
}else{
$_SESSION['current_lan'] = "Not Posting";
}
?>
The session variable is returning "Not Posting".
You claim you are sending the server JSON, but:
You aren't
The PHP isn't set up to receive JSON
Remove contentType: "application/json; charset=utf-8",, then jQuery will set the correct content-type and PHP will populate $_POST.
I kept playing with the jQuery side and this is what worked:
var sendData = 'en';
$.ajax({
type: 'POST',
url: 'app/pro/pro_lang_session_json.php',
data: {'newLang': sendData},
success: function (msg) {
alert(sendData);
},
error: function (err){
alert('Error');
}
});
The session variable sets to 'en' with this code.
Thank you for your help! #DelightedDOD
Related
I am trying to pass a js variable via ajax to the php side. My js code is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var sAgentId = 'hi'
$.ajax({
url: "api-test.php",
method: "POST",
data : { id:sAgentId}
}).done(function(){
console.log('done')
})
and in the php file, I am trying to get the variable via post:
$sAgentId = $_POST['id'];
But finally in api i get the notification that says
Notice: Undefined index: id in C:\xampp\htdocs\webdev-php-exam-prep\exercise\api-test.php on line 2
Can anyone tell me what I am doing wrong?
Try adding this to your AJAX method:
dataType: "json"
Try also console logging the response back to check $_POST['id'] is being set.
.done(function(data) {
console.log("Data: ", data);
});
and in your PHP just return $_POST['id']
var sAgentId = 'hi'
$.ajax({
url:'api-test.php',
type: "POST",
data: {id: sAgentId },
cache: !0,
dataType: 'json',
success: function(data) {
console.log(data);
}
});
try replace method by type:
type: "POST",
I pass the variable javascript method by ajax post method to the php file in this way:
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: 'php/file.php',
type: 'post',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
name: name,
time: time
},
success: function(response){
console.log(response);
}
});
});
Request Payload in my Browser returns: name=Adrian&time=00%3A01%3A59. What should I write in the file file.php to send variables using sql query to my mysql database?
You can make good use of php explode() method here:
$string = name=Adrian&time=00%3A01%3A59
$parameters = explode("&", name=Adrian&time=00%3A01%3A59)
This will give you an array $parameters:
($parameters[0] == name=Adrian,
$parameters[1] == time=00%3A01%3A59)
Now you can get the name and time from $parameters:
$name = explode("=", $parameters[0])[1];
$time = explode("=", $parameters[1])[1];
For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.
How can I send data through ajax to a specific method in a another PHP class? In the url value I have pointed to the class file, but where can I assign the method name to use?
$.ajax({
type:'POST',
url:'ResortController.php',
data: vidData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(vidData);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
Pass the data in data:vidData and specify your function name after call of controller.
url = BASE_PATH + 'ResortController/FUNCTION_NAME';
vidData = {id: 123, vidName: "testVideo"};
$.ajax({
type:'POST',
url:url,
data: vidData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
Using $_POST in your function you will get your ajax data in $_POST['vidData'].
Also you need to call data instead of vidData variable in success of ajax console.log(data).
You need to have a server-side mechanism in place to handle how to direct your requests. Presumably the url you are sending a request to just has the class declaration...you need some sort of dispatcher or else php doesn't know what to do:
jQuery:
$.ajax({
type:'POST',
url:'/dispatcher.php',
data: {
"data":vidData,
"class":"ResortController",
"method":"rMethod"
},
cache:false,
success:function(data){
console.log("success");
console.log(vidData);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
/dispatcher.php
<?php
// This is dangerous if you have no controls in place to allow/restrict
// a program to run a command
// Anyone could send a cURL request and run an automated class/method through
// this mechanism unless you have some way to restrict that
if(!empty($_POST['class']) && !empty($_POST['method'])) {
// Here you want to have some way to check that a request is valid and not
// made from some outside source to run arbitrary commands
// I will pretend you have an admin identifier function....
if(is_admin()) {
call_user_func_array(array($_POST['class'],$_POST['method']),array('data'=>$_POST['data']));
}
}
I have a function that includes an AJAX to send a JSON object retrieved from localStorage. For some reason, in my PHP script, it never shows anything in the $_POST variable, despite me being pretty sure the AJAX call goes through successfully. My code is as follows:
The javascript:
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
dataType: 'json',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
The php script:
if(isset($_POST['answers'])){
$obj = json_decode($_POST['answers']);
print_r ($obj);
}
Any help as to why this isn't working would be greatly appreciated. Thank you.
I've tried all of the options given so far, and nothing seems to be working. I'm at a total loss.
For those asking, the finalResult variable is structured as:
[{"answer":0,"elapsed_time":1378,"stimulus_id":"8","task_id":1},{"answer":1,"elapsed_time":157,"stimulus_id":"2","task_id":1},{"answer":1,"elapsed_time":169,"stimulus_id":"1","task_id":1}, etc....
dataType: 'json' requires that what you output in PHP (data accepted in success section) must be valid json.
So valid json will be in PHP:
if(isset($_POST['answers'])){
echo $_POST['answers'];
}
No need to decode it, it is json string already. No var_dump, no print_r
I would remove the dataType property in your Ajax request and modify the structure of your data :
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: 'answers='&finalResults,
success: function(data){
console.log(data);
console.log('Success');
}
})
And in a second time I would test what I receive on PHP side :
if(isset($_POST['answers'])){
var_dump(json_encode($_POST['answers']));
}
Remove dataType: 'json', if you sending with JSON.stringify
JS.
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
PHP CODE:
if (!empty($_REQUEST['answers'])) {
$answers = json_decode(stripslashes($request['answers']));
var_dump($answers);
}