I am relatively new to cake and I am struggling with a custom filter that im making in order to display products based on which checkboxes have been ticked. The checkboxes get populated based on which attributes the user creates in the backend, i then collect all the values of the selected boxes into an array with javascript and post it to the controller, but for some reason I cannot access the controller variable named '$find_tags' in my view, it throughs undefined variable.
Here is my javascript and ajax which collects and posts correctly (when i firebug it 'data' in my controller has array values which im posting) so thats fine
$("#clickme").click(function(event){
event.preventDefault();
var searchIDs = $("#checkboxes input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var contentType = "application/x-www-form-urlencoded";
var data = 'data[ID]='+searchIDs;
$.post("",data,function(data){
console.log(data);
});
});
Here is my controller code which im assuming is where the fault lies
if ($this->request->is('post') ) {
$data = $this->request->data['ID'];
$find_tags = array();
$selected_tags = $data;
foreach($selected_tags as $tag)
{
array_push($find_tags,$this->Product->findByTag($tag));
$this->set('find_tags', _($find_tags));
}
}
And here is my view code where i get Undefined variable: find_tags
foreach($find_tags as $all_tag)
{
echo $all_tag['Product']['name'];
echo '</br>';
}
Any help or suggestions would really be appreciated been struggling with this for a while now
If searchIDs is array of ids you just need to make the json of array and then send to your controller
$("#clickme").click(function(event){
event.preventDefault();
var searchIDs = $("#checkboxes input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var contentType = "application/x-www-form-urlencoded";
var data = 'ids='+JSON.stringify(searchIDs);
$.post("controller url",data,function(data){
console.log(data);
});
});
On php side you are getting wrong variable
if ($this->request->is('post') ) {
$data = $this->request->data['ids'];
$find_tags = array();
$selected_tags = $data;
foreach($selected_tags as $tag)
{
array_push($find_tags,$this->Product->findByTag($tag));
}
$this->set('find_tags', _($find_tags));
}
Related
Trying to pass the array data using ajax to the PHP function. but getting null value. I am using post method to pass the data.
$(document).on('change','#accordion',function(){
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
var params = new window.URLSearchParams(window.location.search);
var search = params.get('search');
$.ajax({
url:"index.php?route=product/search/filtered_data",
method:"POST",
data:{filter:filter},
success:function(data){
console.log("Hitesh"+data);
}
});
});
PHP Code
public function filtered_data(){
$filter = isset($_POST["filter"]);
echo json_encode($filter);
}
I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";
I'm posting data from a knockout.js page to a controller in cakephp and it says the data was successfully posted, however, my controller doesn't seem to be responding and I don't get an alert back...not even a null response. I even checked the network tab in chrome and it shows the correct data being POSTED
Here's the data being posted from my knockout viewmodel file
var JSON_order = JSON.stringify({"orderInfo":[{"itemNumber":"1","quantity":"1","price":1.00,"productName":"test"}]});
$.post("/orders/submit_order", JSON_order,
function(data){
alert(data.check); //alert doesn't appear
}, "json");
Here's my controller
function submit_order(){
$this->layout = false;
$this->autoRender = false;
if ($this->request->is('post')) {
$order = $this->request->data;
$order = json_decode($order, true);
$finalize_order = new submit;
$finalize_order->display_submitted_order_success($order);
}
}
Here's the code for display_submitted_order_success (I also tried this on a php file outside of CakePHP but it didn't work either)
function display_submitted_order_success($order = null){
$this->layout = false;
$this->autoRender = false;
//I'm just trying to display the order as-is so that I know it's even being posted to begin with
echo json_encode(array("check" => "success","order_num" => $order)); //the values passed the price check, display the result
}
You have to assign the value of JSON_order to a var:
var JSON_order = JSON.stringify({"orderInfo":[{"itemNumber":"1","quantity":"1","price":1.00,"productName":"test"}]});
$.post("/orders/submit_order", {order:JSON_order},
function(data){
alert(data.check); //alert doesn't appear
}, "json");
So that your controller would receive it like this:
$data['order'] = '{"orderInfo":[{"itemNumber":"1","quantity":"1","price":1,"productName":"test"}]}'
I have a table that has sortable rows. The table is generated from a mysql database that has a field called "displayorder" that oders the table. When the user drags and drops rows, I want to use AJAX to submit those changes to the database whenever a user drops a row.
Currently, I can see the console.log() output from the success part of the AJAX call, and when i output the data there (order) it looks great, like this:
["order_1=1", "order_2=2", "order_4=3", "order_3=4"]
But according to Firebug, all that's getting passed in the $_POST is "undeclared".
How do I access that order variable from my indexpage_order.php file?
I have this jquery code:
<script>
$(document).ready(function() {
var fixHelper = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index)
{
$(this).width($originals.eq(index).width())
});
return $helper;
};
var sortable = $("#sort tbody").sortable({
helper: fixHelper,
stop: function(event, ui) {
//create an array with the new order
order = $(this).find('input').map(function(index, obj) {
var input = $(obj);
input.val(index + 1);
return input.attr('id') + '=' + (index + 1);
});
$.ajax({
type: 'POST',
url: 'indexpage_order.php',
data: order,
error: function() {
console.log("Theres an error with AJAX");
},
success: function(order) {
console.log("Saved.");
console.log(order);
}
});
return false;
}
});
});
</script>
indexpage_order.php contains:
if(isset($_POST) ) {
while ( list($key, $value) = each($_POST) ) {
$id = trim($key,'order_'); //trim off order_
$sqlCommand =
"UPDATE indexpage
SET displayorder = '".$value."'
WHERE id = '".$id."'";
$query = mysqli_query($myConnection,$sqlCommand) or die (mysqli_error($myConnection));
$row = mysqli_fetch_array($query);
}
}
You can simply rewrite the js code that are generating the data for POST.
order = {}
$(this).find('input').map(function(index, obj)
{
return order[this.id] = index;
}
)
Rest should work in PHP.
Try $_REQUEST instead of $_POST on the PHP file for POST method with ajax.
convert the js array order to json object as ajax data needs to be in json using JSON.stringify. hence, it needs to be data:JSON.stringify(order), in the ajax function.
Or, use json_encode like this data: <?php echo json_encode(order); ?>, in the ajax function
order is an array. Convert the order to query string like this in your ajax script,
data: order.join('&'),
It looks like your sending your order in a JavaScript array
And when it arrives at your PHP, its unreadable.
If its an object look into the json_decode function.
If its an array, serialize the data before it goes, then unserialize on the php side.
PHP is unable to understand JavaScript array or objects unless they are encoded/serialized correctly.
I have a CodeIgniter MVC application.
I have a model called city that has a method:
<?php
class Cities_model extends Model{
function Cities_model(){
parent::Model();
}
function get_cities($id = null){
$this->db->select('id, city_name');
if($id != NULL){
$this->db->where('country_id', $id);
}
$query = $this->db->get('cities');
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->id] = $city->city_name;
}
return $cities;
}else{
return FALSE;
}
}
...
Controller:
function Post(){
$this->load->helper('form');
$this->load->model('cities_model');
$this->load->model('country_model');
$this->load->model('field_model');
$data['cities'] = $this->cities_model->get_cities();//optional $id parameter
$data['countries'] = $this->country_model->get_countries();
$data['fields'] = $this->field_model->get_fields(); //subject field
$this->load->view('post_view',$data);
}
This method is used to fill the contents of a dropdown list. I have a similar model for countries, which also has a dropdown.
You can see that the get_cities method is set up to accept a country_id. This would be used to filter the results if a country was selected.
My question is I need help calling this method using Ajax (preferably jQuery). I'm new to ajax and have never done anything like this before.
Any help most appreciated!
Billy
UPDATE
I've added jquery library and have created method in my controller:
function get_cities($country){
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(array($this->cities_model->get_cities($country))));
}
here is my javascript on my view:
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>home/get_cities/"+country_id,
data: ({country : country_id}),
success: function(cities){
$.each(cities,function(i,city)
{
var opt = $('<option />');
opt.val(city.value);
opt.text(city.text);
$('#cities').append(opt);
});
}
});
});
});
This is the json reply:
[{"2":"Accra"}]
So it is successfully retriving the correct data. the only problem is it's adding blank values/text to the drop down. and each time I change the city the data is being added on, so I guess i'd have to clear the dropdown first?
extending Alpesh's answer:
you should have a controller's function which return cities filtered by country:
/controller/get_cities/<country>
i'm assuming that your controller's function will return a json object, you can obtain it by doing:
function get_cities($country)
{
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(array($this->cities_model->get_cities($country))));
}
then on the view you'll have 2 select boxes:
one filled up with the contries
one empty and to be filled up with the cities retrived via ajax
now, you have to write something like Alpesh did in order to retrive the cities of the selected country; URL will be
url: '/controller/get_cities/'+country_id
while the success function would be something like
success: function(cities)
{
$('#cities').empty();
$.each(cities,function(i,city)
{
var opt = $('<option />');
opt.val(city.value);
opt.text(city.text);
$('#cities').append(opt);
});
}
UPDATE
in your ajax success function you are dealing with a json objects, infact you are doing this:
opt.val(city.value);
opt.text(city.text);
where city is a json object and value and text are its properties.
when you generate the json via php you have to respect what you use in jquery so your model should return an array like this:
array
(
array("value"=>"2","text"=>"Accra"),
array("value"=>"3","text"=>"Kumasi"),
....
);
the json_encode that array and it should work. Maybe you don't need to wrap the model call into an array but i'm not sure depens on how you return the array
echo(json_encode(array($this->cities_model->get_cities($country))));
or
echo(json_encode($this->cities_model->get_cities($country)));
You can do it this way by jquery -
lets say you have 'country' as an id for the select for country -
then on change of country you can bring it's specific cities as follows -
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "the url you want to call",
data: ({id : country_id}),
success: function(cities){
//populate the options of your cities dropdown here.
}
});
});
});
you can refer detailed documentation here -
JQuery
Ajax API
Ajax