Pass Javascript variable to PHP via ajax - javascript

I am trying to pass a variable from my javascript code over to the server side PHP code. I know this must be done via an ajax call which i believe i have done correctly, however accessing the variable i pass from my ajax into my php is when i run into trouble as i am new to php. Here is my code i have thus far:
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data: "userID=" + userID,
success: function(data)
{
alert("success!");
}
});
});
});
<?php //logtime.php
$uid = isset($_POST['userID']);
//rest of code that uses $uid
?>
I'm trying to pass my javascript variable "userID" to php ($userID), however i've gone wrong somewhere along the road. Thanks for the help!

Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):
data: { userID : userID }
And in your PHP do this:
if(isset($_POST['userID']))
{
$uid = $_POST['userID'];
// Do whatever you want with the $uid
}
isset() function's purpose is to check wheter the given variable exists, not to get its value.

Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset is a function to check if something exists and has a value, not to get access to the value.
Change your PHP to be:
$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;
The above line will check to see if the post variable exists. If it does exist it will set $uid to equal the posted value. If it does not exist then it will set $uid equal to 0.
Later in your code you can check the value of $uid and react accordingly
if($uid==0) {
echo 'User ID not found';
}
This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.

To test if the POST variable has an element called 'userID' you would be better off using array_key_exists .. which actually tests for the existence of the array key not whether its value has been set .. a subtle and probably only semantic difference, but it does improve readability.
and right now your $uid is being set to a boolean value depending whether $__POST['userID'] is set or not ... If I recall from memory you might want to try ...
$uid = (array_key_exists('userID', $_POST)?$_POST['userID']:'guest';
Then you can use an identifiable 'guest' user and render your code that much more readable :)
Another point re isset() even though it is unlikely to apply in this scenario, it's worth remembering if you don't want to get caught out later ... an array element can be legitimately set to NULL ... i.e. it can exist, but be as yet unpopulated, and this could be a valid, acceptable, and testable condition. but :
a = array('one'=>1, 'two'=>null, 'three'=>3);
isset(a['one']) == true
isset(a['two']) == false
array_key_exists(a['one']) == true
array_key_exists(a['two']) == true
Bw sure you know which function you want to use for which purpose.

Alternatively, try removing "data" and making the URL "logtime.php?userID="+userId
I like Brian's answer better, this answer is just because you're trying to use URL parameter syntax in "data" and I wanted to demonstrate where you can use that syntax correctly.

$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id'); // you can add here your personal ID
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data : {
action : 'my_action',
userID : userID
},
success: function(data)
{
alert("success!");
console.log(data);
}
});
});
});
$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 'ID not found';
echo $uid;
$uid add in your functions
note: if $ is not supperted than add jQuery where $ defined

Related

Uncaught TypeError Message using Javascript variable as argument for PHP function that initiates mySQL query

I spent most of my day yesterday trying to solve this puzzle so today I've decided to reach out for some help. Before I begin, let me state that I am very aware that JavaScript is client-side and PHP is server-side and I use Ajax successfully for various other things. In this case, I can't find any S/O references that are similar to what I'm trying to accomplish. I would've thought this was very basic but I'm missing something here and could use some direction. Thank you.
In essence, I have a Javascript function that produces a JavaScript variable and then calls a PHP function that initiates a mySQL query (all on the same page). If I "hard-code" the argument in my PHP function call (e.g., sc_bdls = <?php echo Candidates::getBDLs(1000033); ?>;), the function runs perfectly and I receive the expected outcome (an array).
However, if I try and use a JavaScript variable in place of the argument, I receive a "Uncaught TypeError: Cannot read property 'id' of undefined" error. I have tried several iterations without success and I suspect I am missing something basic. Here is my code:
function tab_pos3(row){
var sc_id = row.toString();
var sc_bdls = [];
$.ajax({
type: "POST",
url: '/phpscripts/pass.php',
data: {row : row},
success:(function(data){
console.log("success");
alert(data);
})
});
sc_bdls = <?php echo Candidates::getBDLs($uid); ?>;
}
Here is the code from the pass.php file:
if(isset($_POST['row']))
{
$uid = $_POST['row'];
echo $uid;
}
Please notice that the console.log("success") and the alert(data) both show that the Ajax POST is working. Any thoughts on what might be going wrong? Thank you.
1st EDIT (comment from Swati)
I tried moving the PHP function call as suggested and then used $UID, $data, data, among others, and I still get the exact same error. Here is the edited code:
$.ajax({
type: "POST",
url: '/phpscripts/pass.php', //
data: {row : row},
success:(function(data){
console.log("success");
alert(data);
<?php $row = $_POST['row'];?>; // I tried this based on something I read.
sc_bdls = <?php echo Candidates::getBDLs(data); ?>;
})
The fact that the error doesn't change is gnawing at me. Could the argument be passed but in a format that is not being read right? Is the "TypeError" referring to data type?
Try moving the
sc_bdls = <?php echo Candidates::getBDLs($uid); ?>; to pass.php and read the returned data in ajax success function.
Please note php is executed before the browser sees it. And JS code is called client side.
This is how your function will look like
$.ajax({
type: "POST",
url: '/phpscripts/pass.php', //
data: {row : row},
success:(function(response){
console.log("success");
sc_bdls=response; // Just to show that response has the value you need.
alert(sc_bdls);
})
The pass.php will look like this
// I prefer using !empty here (unless you are expecting 0 as a valid input.
// This ensure $uid isset and is not empty.
// Also if $uid is supposed to be numeric you may want to add a validation here.
if(isset($_POST['row']))
{
$uid = $_POST['row'];
$response_array = Candidates::getBDLs($uid); //Your question says you are expecting an array
echo json_encode($response_array);
}

Django get coupon code and check the boolean value ("is available") in another column for that code

I currently have a model for coupon codes that looks like this
[code_number | code_available]
class CouponCode(models.Model):
code_number = models.CharField(max_length=256,default='')
code_available = models.BooleanField()
And I'm using Ajax to send a request to the server to see if the code is still available.
var couponCode = document.getElementById('id_coupon').value;
$.ajax({
url: '/ajax/validate_coupon_code/',
data: {
'coupon_code': couponCode
},
dataType: 'json',
success: function (data) {
if (data.is_available) {
alert("Coupon code is available.");
} else {
alert("not available")
}
}
});
Right now, my code checks and returns whether the coupon code exists.
def validate_coupon_code(request):
coupon_code = request.GET.get('coupon_code', None)
data = {
'is_available': CouponCode.objects.filter(code_number=coupon_code).exists(), # code number
'is_bool': CouponCode.objects.filter(code_number=True).exists() # boolean column
}
return JsonResponse(data)
But I am trying to get the coupon code and check the corresponding field in the code_available column to see if it is still set to True and then return that.
I feel like I'm close but can't seem to get it.
Note 1: the is_bool part is where I was trying to make this work
Note 2: I am aware that the Ajax if statement is checking the data.is_available I was using print statements to check the boolean value in the Python code.
I think this is what you want:
CouponCode.objects.get(code_number=coupon_code).code_available
Using get instead of filter is better is this case, because get returns the object and filter a queryset. I imagine that code_number will be like a Primary Key in your case. And, for what I understand, queryset is used when you don't know how many objects will be returned from the query.

Setting session properly in zend controller action on AJAX call

I have an ajax call like following:
$.post("/user/signindo",{'username':username,"password":password},function(data){
//doing something with the response
// Now I need to access the session variable
<?=echo("$_Session['id']")?>
}
and the action in the controller looks like this
public function signindo()
{
$_Session['id'] = 1; // this value is assigned dynamically when the user logs in
// example of setting session to 1
}
The weird thing is that, once the user signs in, the value is assigned with the correct id... Next time I login with the different user, the ID remains the same from the previous user... Next time when I login with the 3rd user, I get the ID of the 2nd user... If you guys understand me what I'm trying to say? What am I doing wrong here?? How to fix this ?
Try this
public function signindo()
{
$namespace = new Zend_Session_Namespace();
$namespace->id = 1;
echo $namespace->id;
exit;
}
Client side:
$.post("/user/signindo",{'username':username,"password":password},function(data){
//data will be your session id
}
Read the below link for more details about Zend session
http://framework.zend.com/manual/1.12/en/zend.session.basic_usage.html
I will go with EagleEye
You will get session value in data, but you can use $.post jquery call..
<script>
$.post("/user/signindo",{username:username,password:password},function(data){
//case1 - output
//console.log(data);//1
//case2 - output
console.log(data);//{id:1,name:joe}
console.log(data.id);//1
console.log(data.name);//joe
}
</script>
In signin I dont know how session works in zend but in corePHP it goes as shown below..
<?php
public function signindo()
{
//case 1
//session_start();
//$_SESSION['id'] = 1; //Not in small $_Session
//echo $_SESSION['id'];
//case 2
$test_array = array('id'=>1,'name'=>'joe');
echo json_encode($test_array);
exit;
}
Maybe it's due the fact that $.post is asynchronous, and the javascript function is called before the session is set, hence the old id.
When you use $.ajax it should work.
$.ajax({
url: '/user/signindo',
data: {'username':username,"password":password},
async: false,
success: function(data) {
// maybe do something with data
}
});
You could also return the id in the PHP function and and access it through the data variable.

How do i use a javascript variable in wordpress query string?

I need to find a way to use a js variable in wordpress query string. I know it involves ajax but i don't know how to go about it. Please help!
<script>
$(document).ready(function(e) {
var x=$(this).find('.resp-tabs-list li').attr('id');
//alert(x);
});
$('.resp-tabs-list').on('click',function(e){
var x = $(this).find('.resp-tab-active').attr('id');
//alert(x);
});
</script>
In the code above, i fetch 'x', which is the category id, based on which i want to fetch posts in a loop.
You are correct that it does involve ajax. You'll need to do something like the following (I haven't tested it, but it should put you on the right track):
Javascript (assuming you have jQuery loaded, and that you've used PHP to output the admin url as a javascript variable ajaxurl):
$(document).ready(function() {
bindCategoryFilter();
}
function bindCategoryFilter() {
$('.resp-tabs-list').on('click',function(e){
var x = $(this).find('.resp-tab-active').attr('id');
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
//this is the name of our Wordpress action we'll perform
'action' : 'get_ajax_posts',
//this is the important line--send 'x' to the server as category
'category' : x
},
success: function(data) {
//do whatever with the data you're getting back
//with the PHP below, it's an array of the post objects
}
});
});
This will POST data to our server, with the variable 'category' set to x in the $_POST variable. To access this, in your functions.php you would want to add something like the following:
//add our action hooks--wp_ajax_XXXXX is defined in the ajax query as 'action'
//the second argument is the name of the PHP function we're calling
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
function get_ajax_posts() {
if(isset($_POST['category'])) {
//get all the posts in the category, add more arguments as needed
$posts = get_posts(array('category' => $_POST['category']));
//data is returned to javascript by echoing it back out
//for example, to return all of the post objects (which you probably don't wnat to do)
echo json_encode($posts);
//we're done
die();
}
}
See the wordpress codex for more information about AJAX and Wordpress.

Javascript variable within a php variable

I have php function that checks if an entry exists in my database that I call with class::checkThis($my_entry);
In my script javascript is used to determined the name of the folder I am selecting, so $my_entry is supposed to look like this :
(in normal is determined by php and the part in bold is what is determined by javascript)
C:/library/user/apatik/folder1
As you guess I can't find a working way to mix up thoses languages, and I don't really have any experience in javascript yet to figure out this.
The php code that returns the first part of the path is simply $_SESSION['cwd'].'/' and the javascript variable that returns the selected folder's name is data_name and is determined by var data_name = $(this).attr('data-name');
Is there a way to get something like if (class::checkThis($_SESSION['cwd'].'/'.data_name) == true) ?
None of what I tried so far worked and I'm having troubles finding an alternative.
Thanks for the help
You'll need to make an AJAX request to accomplish this. You'll load the page as normal, except for the dynamic part. Then you can populate the dynamic part (I've illustrated it as #content here) based on the result of the AJAX call:
var data_name = $(this).attr('data-name');
...
$.ajax('http://example.com/my_php_script.php?data_name=' + data_name)
.done(function(data){
// "data" is the resulting output of the PHP script
$('#content').append(data);
});
NOTE: The solution above uses jQuery.
Then, in your my_php_script.php, you can do something like this:
if (class::checkThis($_SESSION['cwd'] . '/' . $_GET['data_name']) == true) {
...
}
Ajax jQuery is your best solution.
This one using post method with event, just for reference...
Am I exist?
Am I exist too?
$('.anchor').click(function(){
var data_name = "name=" + $(this).attr('data-name');
$.ajax({
type: "POST",
url: "is_exist.php",
data: data_name,
success: function (data) {
alert(data.response);
}
});
};
is_exist.php
if(isset($_POST['name'])){
$data['response'] = class::checkThis($_SESSION['cwd'].'/'.$_POST['name']) == true ? "exist" : "buried";
echo json_encode($data);
}

Categories

Resources