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);
}
Related
I am working on a project using PHP Codeigniter. I want to know how can I sent a variable with JQuery to the controller. Below is my code
<script>
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id", {id: id}, function(page_response)
{
$(".modal-body").html(page_response);
});
}
</script>
Here I'm first getting the variable 'id' from function parameter. But when I run this code, it return the string 'id' instead of the actual user id from database. I want to view the user id. Below is my function from the controller..
public function Reset_User_Password()
{
$data['admin_id'] = $this->uri->segment(3);
$this->load->view('admin/user/reset_user_password', $data);
}
Send data by POST method is not append in url as GET method. So you can't get is using $this->uri->segment().
Instead use
$data['admin_id']=$this->input->post('id');
Use
$this->input->post('id');
Don't use $this->uri->segment(3); because you are posting id by post method if you want to use $this->uri->segment(3); then do a minior miodification in your function
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/"+id, function(page_response)
{
$(".modal-body").html(page_response);
});
You can take help with this code. It is working perfectly at my end
function Reset_User_Password(){
var currentpwd= document.getElementById("currentpwd").value;
var newpwd = document.getElementById("newpwd").value;
var cnfrmnewpwd = document.getElementById("cnfrmnewpwd").value;
var url = "<?php echo base_url('user/changepwd'); ?>"
$.ajax({
type:"POST",
data:{currentpwd:currentpwd,newpwd:newpwd,cnfrmnewpwd:cnfrmnewpwd},
url:url,
success:function(data){
if(data){
$('#newsleter').html(data);
}
}
});
}
try below code
you should get that id variable from GET method on the controller.
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id="+id
$(".modal-body").html(page_response);
});
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));
}
I am using a service to update a DB table.
myApp.factory('createGal', function ($http, $q)
{
return {
createGal: function ()
{
var deferred = $q.defer();
var newGalleryArray = {};
newGalleryArray.galleryName = 'New Image Gallery';
newGalleryArray.client = 245;
$http.post('/beta/images/create', {newGalleryArray: newGalleryArray}).success(function(data)
{
console.log(data);
deferred.resolve(data);
});
return deferred.promise;
}
};
});
PHP
public function create()
{
print_r($_POST);
}
The array is returning empty. Am i passing the array incorrectly?
Chrome Dev
Thanks
It's been a while since I've used PHP, but doesn't $_POST just contain request paramaters? $http.post sends data through a JSON payload, not request parameters. So, you'll need to use something like json_decode
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 am currently using jquery to get JSON data via ajax from a codeigniter backend / mySQL database, which works fine. The problem I'm having is that, along with the data that gets returned to the jquery function, I also need to run a PHP loop for some data in another table. Currently what I'm doing is waiting for an ajax success from the first function, then making another ajax call to the second function - but I know there is a way to do it with just one function, I'm just not sure how. Here are the two database queries:
function get_selected_member($member = null){
if($member != NULL){
$this->db->where('id', $member); //conditions
}
$query = $this->db->get('members'); //db name
if($query->result()){
$member_result = $query->row();
return $member_result;
}
}
AND
function get_all_groups(){
$query = $this->db->get('groups');
$result = $query->result();
return $result;
}
and then in the javascript function, what I'm doing is saying:
var post_url = "/index.php/control_form/get_selected_member/" + selected_member_id;
$('#chosen_member').empty();
$.ajax({
type: "POST",
url: post_url,
success: function(member)
{
//Add all the member data and...
var post_url2 = "/index.php/control_form/get_all_groups/";
$.ajax({
type: "POST",
url: post_url2,
success: function(group)
{
//Create a dropdown of all the groups
}
});
}
});
In PHP you can combine both in one then echo it to ajax as json variable. So in php you will need a change like following
function get_member_with_group($member = null){
$data['member'] = $this->get_selected_member($member);
$data['group'] = $this->get_all_groups();
echo json_encode($data);
}
Then in javascript something like below..
var post_url = "/index.php/control_form/get_member_with_group/" + selected_member_id;
$('#chosen_member').empty();
$.getJSON(post_url, function(response){
var member = response.member;
//do with member
var group = response.group;
// do with group
});
Hope this will help you :)