I am sending arrays from View to Controller using Post Method. This is my code.
Controller: Session::put('isCheck', $isCheck);
this is how i am assigning value to isChecked array.
var isChecked = [
<?php
$isCheck = "";
if (Session::has('isCheck')) {
$isCheck = Session::get('isCheck');
}
foreach ($isCheck as $isCheck) {
$status = $isCheck;
?>
<?php echo $status; ?>,
<?php } ?>
];
View:
$("#target").click(function () {
var postTo = '<?php echo action('sample#postView'); ?>';
var data = {
isChecked: isChecked,
duplicateIsChecked: duplicateIsChecked
};
jQuery.post(postTo, data,
function (data) {
alert(data);
});
});
isChecked and DuplicateIsChecked are my 2arrays.
In controller I am writing this code:
$duplicateIsChecked = $_POST['duplicateIsChecked'];
$isCheck = $_POST['isChecked'];
But i am getting Undefined index duplicateIsChecked error. Help me
Have you checked the header of your Ajax call to make sure its sending any data? In the code you posted, you're assigning variables to the two values in data but you didn't show where you are declaring those variable values.
You can't pass a javascript array to php like that, you have to convert the array into JSON and send it.
so it should be
var data = JSON.stringify({
isChecked: isChecked,
duplicateIsChecked: duplicateIsChecked
});
To get the JSON payload in controller, you can use
$payload = Input::json()->all();
then to access the attribute, you can reference it as
$payload['duplicateIsChecked'] & $payload['isChecked']
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 extract the information with a XHR request (AJAX) to a php file (this php file gets the information throught json file with Get request too) so when I try to do console.log(Checker) on the console, it returns Undefined and if I put alert(Checker) it returns [object Object]. How can I solve it?
PHP:
<?php
headers('Content-Type', 'application/json')
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents
?>
JS:
function start() {
$.ajax({
type: 'GET',
url: 'api/domain/showall.php',
dataType: 'json',
success: function(data) {
alert(data)
displayTheData(data)
}
});
}
function displayTheData(data) {
Checker = data;
JSON.stringify(Checker)
console.log(Checker)
window.Checker = Checker;
}
JSON:
[{"name":"Google","url":"google.es","id":1}]
Here you are strigify data but not store value i any var.
function displayTheData(data) {
Checker = data;
var displayChecker = JSON.stringify(Checker) /// add displayChecker
console.log(displayChecker ) // print it
window.Checker = Checker;
}
There is not displayTheData() function so first call it and pass response params.
You need to echo the JSON Response ! Change return $jsonContents; to echo $jsonContents; it will work !!!
You must parse data into body (not returning it which has no meaning outside a function) and, optionnaly but much better, fill some headers. A very minimalistic approach could be :
<?php
headers('Content-Type', 'application/json');
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents // echo JSON string
?>
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 have 2 files(call.php and post.php) and using ajax pass value from call to post,and i want to get return value from post ,but this doesn't work. when i change post ,modify "return" to "echo",it works,but i don't know why.can anybody give me a help?
Examples would be most appreciated.
call.php
<script type="text/JavaScript">
$(document).ready(function(){
$('#submitbt').click(function(){
//var name = $('#name').val();
//var dataString = "name="+name;
var dataPass = {
'name': $("#name").val()
};
$.ajax({
type: "POST",
url: "post.php",
//data: dataString,
data: dataPass,//json
success: function (data) {
alert(data);
var re = $.parseJSON(data || "null");
console.log(re);
}
});
});
});
</script>
post.php:
<?php
$name = $_POST['name'];
return json_encode(array('name'=>$name));
?>
update:
by contrast
when i use MVC "return" will fire.
public function delete() {
$this->disableHeaderAndFooter();
$id = $_POST['id'];
$token = $_POST['token'];
if(!isset($id) || !isset($token)){
return json_encode(array('status'=>'error','error_msg'=>'Invalid params.'));
}
if(!$this->checkCSRFToken($token)){
return json_encode(array('status'=>'error','error_msg'=>'Session timeout,please refresh the page.'));
}
$theme = new Theme($id);
$theme->delete();
return json_encode(array('status'=>'success'));
}
$.post('/home/test/update',data,function(data){
var retObj = $.parseJSON(data);
//wangdongxu added 2013-08-02
console.log(retObj);
//if(retObj.status == 'success'){
if(retObj['status'] == 'success'){
window.location.href = "/home/ThemePage";
}
else{
$('#error_msg').text(retObj['error_msg']);
$('#error_msg').show();
}
});
This is the expected behaviour, Ajax will get everything outputted to the browser.
return only works if you are using the returned value with another php variable or function.
In short, php and javascript can't communicate directly, they only communicate through what php echoed or printed. When using Ajax or php with javascript you should use echo/print instead of return.
In Fact, as far as I know, return in php is not even used in the global scope very often (on the script itself) it's more likely used in functions, so this function holds a value (but not necessarily outputs it) so you can use that value within php.
function hello(){
return "hello";
}
$a = hello();
echo $a; // <--- this will finally output "hello", without this, the browser won't see "hello", that hello could only be used from another php function or asigned to a variable or similar.
It's working on the MVC framework because that has several layers, probably the delete() method is a method from the model, which returns its value to the controller, and the controller echo this value into the view.
Use dataType option in $.ajax()
dataType: "json"
In post.php try this,
<?php
$name = $_POST['name'];
echo json_encode(array('name'=>$name));// echo your json
return;// then return
?>
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";