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.
Related
I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.
I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):
$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";
//this is the file that contains the above query variable
require('custom/Connection.php');
$owner_arr = array();
//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}
This generates a list of name records pulled from the database in a Alias(first name) Last Name format.
Here's where I'm having trouble
Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.
I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:
$.ajax({
type: 'POST',
data: 'listRefresh();',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function() {
alert("this succeeded?");
}
});
The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?
Your ajax call is wrong. The 'data' value is what you send to the server.
Try this:
$.ajax({
type: 'POST',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function(data) {
listRefresh(data);
alert("this succeeded?");
}
});
The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.
In alternative, you could just reload the page putting location.reload(); into success function
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.
While reading other similar questions I've learned that to send a javascript value to PHP variable I need to use AJAX. That's what I've done so far:
function onCursorChanged(e, data) {
$.post('familytree.php', {id: data.context.id});
<?php
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
else {
$id = $individualid;
}
?>
}
The problem is that when I check if id is posted it always goes to else statement (id is always equal to individualid). However, when I change my code to this:
function onCursorChanged(e, data) {
$.post('familytree.php', {id: data.context.id,
success: function (msg){
alert('success') },
error: function (err){
alert(err.responseText)}
});
<?php
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
else {
$id = $individualid;
}
?>
}
EDIT: the code above is mixed incorrectly because of a lot of experimenting I've been doing. The original code:
<script type="text/javascript">
function onCursorChanged(e, data) {
$.post('familytree.php', {id: data.context.id});
}
</script>
<?php
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
else {
$id = $individualid;
}
$this->displayLeafEditForm ($_SESSION['username'], $id, $this->getParents($id));
Thanks to all the answers I realised that id is not set that's why I can't get the value in php. But I don'y understand why because data.context.id is the id of the item clicked and set after each click.
I get the message that says 'success'. Any idea why can't I get my variable posted?
The big problem here is that you mixing PHP and JavaScript incorrectly. You are expecting $_POST['id'] to be set in the JavaScript before it goes to the client. But by the time the JavaScript reaches the client, the PHP processing is already complete.
This means that when the $.post() happens, the server has already decided whether if (isset($_POST['id'])) is true. The server sends the output (the JavaScript) on to the client, and then no more PHP processing will happen.
Also, you are passing id, success, and error as data, which is almost certainly not what you want. You want this:
$.post('familytree.php',
{id: data.context.id},
success: function (msg){
alert('success')
},
error: function (err){
alert(err.responseText)
}
);
The AJAX success function cares whether the asynchronous call occurred without error. The fact that you even reached if (isset(...)) (and didn't set any error code eg. with header(...)) means that the AJAX call succeeded.
If isset is returning false, you need to look closer at the information that your AJAX call is actually sending to the PHP. Try putting in print_r($_POST) to see what post values you're actually getting.
I have a form set up that, when submitted, uses an ajax call to retrieve data via a PHP file that in turn scrapes data from a given URL based on the input field value.
Everything is working perfectly, but what I'd like to do now is implement a couple of additional features.
1) After the initial form submission, I'd like it to auto-update the query at set intervals (Chosen by the end user). I'd like to append the new results above the old results if possible.
2) When new results are returned, I'd like a notification in the title of the page to inform the user (Think Facebook and their notification alert).
Current jQuery/Ajax code:
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'jobSearch.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.val('Searching....'); // change submit button text
},
success: function(data) {
$('#container').css('height','auto');
alert.html(data).fadeIn(); // fade in response data
submit.val('Search!'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
I'm not too sure how I'd go about this, could anyone give me an insight? I'm not after somebody to complete it for me, just give me a bit of guidance on what methodology I should use.
EDIT - jobSearch.php
<?php
error_reporting(E_ALL);
include_once("simple_html_dom.php");
$sq = $_POST['sq'];
$sq = str_replace(' ','-',$sq);
if(!empty($sq)){
//use curl to get html content
$url = 'http://www.peopleperhour.com/freelance-'.$sq.'-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}else{
$url = 'http://www.peopleperhour.com/freelance-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}
$html = file_get_html($url);
$jobs = $html->find('div.job-list header aside',0);
echo $jobs . "<br/>";
foreach ($html->find('div.item-list div.item') as $div) {
echo $div . '<br />';
};
?>
Question 1:
You can wrap your current ajax code in a setInterval() which will allow you to continue to poll the jobSearch.php results. Something like:
function refreshPosts(interval) {
return setInterval(pollData, interval);
}
function pollData() {
/* Place current AJAX code here */
}
var timer = refreshPosts(3000);
This has the added benefit of being able to call timer.clearInterval() to stop auto-updating.
Appending the data instead of replacing the data is trickier. The best way, honestly, requires rewriting your screen scraper to return JSON objects rather than pure HTML. If you were to return an object like:
{
"posts": [
// Filled with strings of HTML
]
}
You now have an array that can be sorted, filtered, and indexed. This gives you the power to compare one post to another to see if it is old or fresh.
Question 2:
If you rewrote like I suggested above, than this is as easy as keeping count of the number of fresh posts and rewriting the title HTML
$('title').html(postCount + ' new job postings!');
Hope that helps!
If i understand correctly. . .
For updating, u can try to do something like this:
var refresh_rate = 2500
function refresh_data() {
// - - - do some things here - - -
setTimeout (refresh_data(),refresh_rate); // mb not really correct
}
You can read more about it here
Hope, i helped you
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