Write to Session with Post - CakePHP - ajax

I am trying to post an array of check box ids to an action in my controller. Here is the script from my index.ctp:
<script type="text/javascript">
$('.editSel_dialog').click(function()
{
var selected = [];
alert('Edit Selected Has Been Clicked');
$("#[id*=LocalClocks]").each(function()
{
if(false != $(this).is(':checked'))
{
selected.push($(this).attr('id').replace('LocalClocks', ''));
}
});
alert(selected);
/*$.ajax(
{
type: 'POST',
url: "/LocalClocks/editSelected/",
data: selected,
traditional: true,
//contentType: "application/json",
dataType: "text",
success: function(data){ alert(data); alert('Edit Success');}
});*/
$.post('/LocalClocks/editSelected', { "Session" : selected }, function(data){
alert(data);
});
});
</script>
I have both an ajax request and a post request. I was using the ajax until I saw that the post can actually modify a php variable. The code in the braces { "Session" : selected } should modify the Session variable with the array selected.
I tried using debug on $this->data, and $this->request->data, and $_POST, but they all are empty.
I need help getting the selected array written to a variable or something. I was thinking of trying to write to $this->Session but I am not sure how I would go about doing that.
Thanks in advance

With Cake, to get posted values in $this->request->data, their names have to be prefixed with data:
Javascript:
$.post('/LocalClocks/editSelected', { "data[Session][selected]" : selected }, function(data){
alert(data);
});
Controller:
function editSelected()
{
if($this->request->is('post'))
{
if(isset($this->request->data['Session']['selected']))
{
$this->Session->write('selected', $this->request->data['Session']['selected']);
}
}
}

Maybe I'm wrong, but I think you cannot do that directly from the client side using ajax. Can you share the source your statement regarding you can modify the php variable? I googled for that with no luck, and it will be weird to me being able to modify the PHP session.. it would be really insecure, saying you could use Session Fixation/Injection or other malicious techniques
Edited
For assigning the value on a existing variable you need
Make the ajax call
$.post('/LocalClocks/editSelected', { "selected" : selected }, function(data){
alert(data);
});
and on your controller you'll have a function like this
function editSelected($selected){
$_SESSION["selected"] = $selected;
}
and voila

Related

Use ajax to filtering data table in codeigniter

i'm using codeigniter to build my project. I want to make filter use select box with ajax, but i confused. when user choose values from select box, then i want the table just show data that contain select box values. Can anyone help me please...
<script>
function show_result()
{
if($('#selectbox').val()!='')
{
$.ajax({
type: "POST",
url:'<?php echo base_url()?>controller/controller_function',
data:'selectvalue='+$('#selectbox').val(),
cache: false,
beforeSend : function ()
{
$("#idAjaxLoader").css("display",'');
},
success: function (data) {
$("#idAjaxLoader").css("display",'none');
$('#table-div').html(data);
},
error: function(data){
//return false;
}
});
}
}
</script>
write query in controller's controller_function and then load view with table by your expected result

Using form data to dynamically construct url using ajax

I have the following ajax code that takes in 3 variables and passes them to a php file, and this is all fine and dandy. I want to do a redirect using the value stored in one of these variables. I figured I could just do window.location.href = within the success in the ajax call, but for some reason, it doesn't seem to respond to the click, and simply does nothing.
Here is the ajax function, hope y'all can help!
$("#findItem").click(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.ajax({
type: 'get',
url: 'http://plato.cs.virginia.edu/~aam3xd/cabbage/closestBuildingWeb.php',
data: {
foodItemId: $('#foodItem').val(),
sentLongitude: position.coords.longitude,
sentLatitude: position.coords.latitude
},
success: function(data){
//$('#answer').html(data);
//the following line doesn't seem to be executing....
window.location.href = foodItemId+"/"+sentLatitude+"/"+sentLongitude;
}
});
});
I think you should use your url into that window.location
window.location.href = "www.example.com/"+foodItemId+"/"+sentLatitude+"/"+sentLongitude;

joomla token is not getting recognized by controllers method

I'm trying to set up a token on ajax post but is not getting recognized by the controllers method. The javascrip looks as it follows
jQuery(document).ready(function() {
jQuery('#source').change(function() {
jQuery('#fileupload').addClass('fileupload-processing');
var data = jQuery('#source option:selected').val();
jQuery.post('index.php', {
'option': 'com_tieraerzte',
'task': 'parser.importColumns',
'tmpl': 'component',
'token':'<?php echo JUtility::getToken()?>',
'app': data,
'dataType': 'html',
}, function(result) {
jQuery('td.add_column').html(result);
jQuery('button#parse.btn').show();
//edit the result here
return;
});
});
the token is getting generated and posted
in the controller I check the existance of toke but throws me Invalid Token
controller check toke
JRequest::checkToken('request') or jexit( 'Invalid Token' );
You're almost there, it's just a little mixed up. The Joomla! Form Token is generated and submitted as a input name with a value of 1. So, the token looks like this in your form:
<input type="hidden" name="1LKJFO39UKSDJF1LO8UFANL34R" value="1" />
With that in mind, when submitting via AJAX, you need to set the parameter name to your token name, with a value of 1. I accomplish something similar by just using the jQuery('selector').serialize() method:
Joomla.autoSave = function () {
jQuery.ajax({
url: "index.php?option=com_gazebos&task=product.apply&tmpl=component",
type: "POST",
data: jQuery("#product-form").serialize(),
success: function (data) {
console.log("autosaved");
}
});
};
Doing this pulls in all the form data (including the form token from the hidden input) and formats it as a query string, then sends it with the request. However, it seems to me that you might not want to do that and you are really only wanting to submit a single bit of data, not the whole form. So, let's rework your code a little bit to get the desired effect:
/**
* First, let's alias $ to jQuery inside this block,
* then setup a var to hold our select list dom object.
*/
jQuery(document).ready(function ($) {
var sourceSelect = $('#source');
sourceSelect.change(function () {
$('#fileupload').addClass('fileupload-processing');
/**
* Use the token as a parameter name and 1 as the value,
* and move the dataType param to after the success method.
*/
$.post('index.php',
{
'option': 'com_tieraerzte',
'task': 'parser.importColumns',
'tmpl': 'component',
'app': sourceSelect.val(),
'<?php echo JSession::getFormToken()?>': 1
},
function(result) {
$('td.add_column').html(result);
$('button#parse.btn').show();
//edit the result here
return;
},
'html'
);
});
});
Finally, this code is assuming you have this js code either in your view.html.php or in your views/parser/tmpl/default.php. If you have it in a separate .js file, then your php code won't execute and give you the token.
In your ajax call method use url as :
$.ajax({
url: '/index.php?option=com_itemreview&task=item.userReviewVote&<?php echo JSession::getFormToken(); ?>=1',
type: 'post',
data: {'data': submitvalue},
dataType: 'json',
success: function(response) {
}
});
for more information see here:
http://joomlabuzz.com/blog/27-preventing-cross-site-request-forgery-in-joomla
https://docs.joomla.org/How_to_add_CSRF_anti-spoofing_to_forms

Relevant data form_dropdown codeigniter

I am trying to post value using javascript in form_dropdown('') but it is not posting data on form.
Jquery library is loaded. On alert it display record of dep_selected
JQUERY On view page
function get_subdepartment() {
var dep_selected = $('select[name=txtDept]').val();
$.ajax({
data: {
dep_selected: dep_selected,
},
type: 'POST',
url: 'addVacancy/getSubDept',
success: function(data){ //alert(dep_selected);
console.log(data);
$('.subdepartment').html(data);
}
})
}
Controller Page:
function getSubDept(){
if($this->input->post('txtDept')){
echo "getSubDept > Dept: ".$this->input->post('txtDept');
}
else{
echo "getSubDept > No Return";
}
}
It display "getSubDept > No Return" Please help.
Well it's obvious, that in your controller you are requesting a post value by the key txtDept, but you don't have that when you send data with AJAX. What you have now is:
var dep_selected = $('select[name=txtLocation]').val();
and
data: {
dep_selected: dep_selected,
},
So you should simply change the first line in your controller method to
if($this->input->post('dep_selected')) {
I suggest you to do some reading about POSTing values with AJAX and how to work with JSON.

Getting wordpress to play nice with AJAX

How do I use WP functions from AJAX calls. I've looked at the documentation for creating plugins that use ajax, but I couldn't figure out how to apply that to regular pages and posts.
Is there an easy way to just load everything without using their API? I have my way I like to do ajax and would rather not use their stuff.
This is a fluff version of my code:
Javascript (jQuery):
$('.action.next_posts').click(function() {
var last_date = $(this).attr('title');
//alert();
$.ajax({
url: WP_DIR+'functions.php?action=get_next_posts',
type: 'POST',
data: {date : last_date},
success: function(response) {
alert(response);
},
error: function(error) {
alert("error");
}
});
});
Functions.php (PHP):
// AJAX controller
if(isset($_GET['action'])) {
require_once('../../../wp-config.php');
require_once('../../../wp-includes/classes.php');
require_once('../../../wp-includes/functions.php');
wp();
echo 'ok';
echo bloginfo('name'); // NOT WORKING. TRIED adding actions..
return;
}
The following solution should work. You are going to go ahead and post directly to the WordPress installation and intercept the request before WordPress does all the querying that it would normally do. There are some caveats to this method, one of which being that some caching methods will interfere with it, but it should work fairly well for your purposes.
Besides, you said you didn't want to use the specified WordPress API, so this should be right up your alley.
JavaScript:
jQuery(document).ready(function($) {
$('.action.next_posts').click(function(event) {
event.preventDefault();
var last_date = $(this).attr('title');
$.ajax({
url: '/',
type: 'post',
data: {date : last_date, action: 'get_next_posts'},
success: function(response) {
alert(response);
},
error: function(error) {
alert("error");
}
});
});
});
functions.php
add_action('parse_request','my_request_parser');
function my_request_parser($wp) {
if( 'get_next_posts' == $_POST['action'] ) {
echo 'ok';
bloginfo('name');
exit();
}
}

Resources