to print a session using ajax codeigniter - php

In my page
$(document).ready(function(){
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>total',
data:'id=1',
beforeSend:function(){
$('.searc_res').show();
},
success:function(html){
$('.searc_res').remove();
$('.searc_res').append(html);
}
});
});
This is just to return in the div the value of a session
Session is: $this->session->userdata('searchItems_Total')
How to do this in the total.php file?
Do I need to create something in the model?

Just print it?
public function total()
{
header('Content-type: application/json');
/.../
echo json_encode($this->session->userdata('searchItems_Total'));
}
In your client side call (to view the returned data's structure):
$.ajax({
...
success: function(resp){
console.log(resp);
});

You can just return $this->session->userdata('item'); in your php function or you can just echo the values in your html since you are trying send an ajax request in document ready state which is not necessary.

Related

How to pass JS object to PHP function

$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'<?php echo site_url($this->config->item('admin_folder').'/catalog/get_all_option');?>',
type:'POST',
data:{category_id:1},
dataType: 'json',
success:function(data){
$('#attribute_form').html('<?php add_attribute_form("'+data+'");?>');
}
});
}
});
on callback function success return the data and pass it to add_attribute_form(data) php function but nothing response.
what is the correct way to pass js object to php function
What you will need to do here is, use Ajax to send data to a separate php page passing it some information, then, based on that information, the php page should return data to the Ajax callback function which will add the returned data to the original page.
Here's a simple example (and a working demo here):
In index.html do this:
<script>
$(document).ready(function(){
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'somepage.php',
type:'POST',
data:{category_id:1},
dataType: 'json', // this setting means you expect the server to return json formatted data
// this is important because if the data you get back is not valid json,
// the success callback below will not be called,
// the error callback will be called instead
success:function(response){
$('#attribute_form').html(response.html);
// if not using json, this would just be $('#attribute_form').html(response);
},
error:function(xhr, status, error){
// handel error
}
});
}
});
});
</script>
<input type="checkbox" class="select_category"> Check this box
<div id="attribute_form"></div>
Then in somepage.php do the following:
<?php
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : null;
if($category_id == '1'){
echo json_encode(array('html'=>'<h1>This text came from the php page</h1>'));
exit;
// if you are not using dataType:json in your ajax, you can just do:
// echo '<h1>This text came from the php page</h1>';
// exit;
}
?>

How to use ajax to pass a variable to a php file using POST method?

I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});

CodeIgniter, Ajax call does not get into Controller

After looking at a solution on ci-ajax-csrf-problem I added the following line into the script and it works fine.
var post_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
inserted into
$.ajax({
url: '<?php echo base_url()."ajax/test";?>',
type:'POST',
dataType: 'json',
data: post_data,
Thank you for the help everyone :)
I am new to Ajax/Jquery and was following a guide on Ajax for CodeIgniter from jorge torres to implement a simple ajax call on my website and ran into problems.
I created a Controller Ajax and this is the code snippet.
class Ajax extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function test() {
$output_string = 'This is a test';
echo json_encode($output_string);
}
public function test2(){
$this->load->view('test.php');
}
}
And this is the view for that controller, its identical to the one from the tutorial except I added loaded the url helper $this->load->helper('url'); on the first line
Here is the snippet for the script code.
The #getdata is a button type and #result_table is a div
$('#getdata').click(function(){
$.ajax({
url: '<?php echo base_url().'ajax/test';?>',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
I can successfully access localhost.com/codeigniter/ajax/test2 but when I clicked the button, nothing happen.
I tried looking at the page source info and the url is correct
$.ajax({
url: 'http://localhost/codeigniter/ajax/test',
type:'POST'
....
Accessing localhost/codeigniter/ajax/test directly is also possible and it display the output message.
I am using CodeIgniter 2.1.3 and my localhost is running on XAMPP 1.7.3
Thank you in advance :)
After looking at a solution on ci-ajax-csrf-problem I added the following line into the script and it works fine.
var post_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
inserted into
$.ajax({
url: '<?php echo base_url()."ajax/test";?>',
type:'POST',
dataType: 'json',
data: post_data,
Thank you for the help everyone :)
Did your .click() event handler works as expected?
$('#getdata').click(function(){
alert('clicked');
........
if no, try to wrapped the jquery code in $(document).ready(function() { ... }); as #Sudhir suggested:
$(document).ready( function() {
$('#getdata').click(function(){
alert('clicked');
........
});
if yes, in case you don't know it yet, there's a tool called firebug to check your AJAX request.
I thinks there's no problem with your AJAX url.
So far, this is my answer. Hope this helps too.
Do you have output compression enabled(gzip) in your config.php? If you compress your output it will fail when you use echo and return the 500 server errors.
I think there is an issue with your ajax call . Should be like this I think :
$(document).ready (function () {
$('#getdata').click(function(){
$.ajax({
url: '<?php echo base_url()."ajax/test";?>',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
If the firebug console says that The action you require is not allowed, then it may be a CSRF token issue, turn it off in the codeigniter config.
Add this in config file.
$config['csrf_protection'] = FALSE;
Hope this helps :)
Have you tried
$(document).ready (function () {
$('#getdata').click(function(){
$.ajax({
url: '/ajax/test',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
as apposed to <?php base_url; ?>
Have you entered your site url into the CI config?

return php variable to jquery ajax

I have an ajax function in jquery calling a php file to perform some operation on my database, but the result may vary. I want to output a different message whether it succeeded or not
i have this :
echo '<button id="remove_dir" onclick="removed('.$dir_id.')">remove directory</button>';
<script type="text/javascript">
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
if(rmd==0)
alert("deleted");
else
alert("not empty");
window.location.reload(true);
}
});
}
</script>
and this
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if(isset($_POST['dir_id'])){
$rmd=remove_dir($_POST['dir_id'],$bdd);
}
?>
my question is, how to return $rmd so in the $.ajax, i can alert the correct message ?
thank you for your answers
PHP
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if (isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
?>
JS
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did}
}).done(function(rmd) {
if (rmd===0) {
alert("deleted");
}else{
alert("not empty");
window.location.reload(true);
}
});
}
i advice to use json or :
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
You need your php file to send something back, then you need the ajax call on the original page to behave based on the response.
php:
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo "{'rmd':$rmd}";
}
which will output one of two things: {"rmd": 0} or {"rmd": 1}
We can simulate this return on jsBin
Then use jquery to get the value and do something based on the response in our callback:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://jsbin.com/iwokag/3",
success: function(data){
alert('rmd = ' + data.rmd)
}
});
View the code, then watch it run.
Only I didn't send any data here, my example page always returns the same response.
Just try echoing $rmd in your ajax file, and then watching the console (try console.log(rmd) in your ajax response block)
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
console.log(rmd);
}
});
You can then act accordingly based on the response
Try echo the $rmd out in the php code, as an return to the ajax.
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
//if $rmd = 1 alert('directory not empty');
//if $rmd = 0 alert('directory deleted');
echo $rmd;
}
Your "rmd" in success: function(rmd) should receive the callabck.

Jquery: Only fill in data from .load if there is content?

Im using the jquery .load function to query a php file that will output some data. Now sometimes the script will return nothing. In this case, can I have the load function not put any data into my specified div? (right now it clears out the div and just puts a blank white area.
Thanks!
try using $.get;
$.get('<url>',{param1:true},function(result){
if(result) {
$('selector').html(result);
}
else {
//code to handle if no results
}
});
Use $.get
http://api.jquery.com/jQuery.get/
in addition to #jerjer's post, you can also use this:
var paramData= 'param=' + param1 + '&user=<?echo $user;?>';
$.ajax({
type: "GET",
data:paramData,
url: "myUrl.php",
dataType: "json", // this line is optional
success: function(result) {
// do you code here
alert(result); // this can be an any value returned from myUrl.php
},
statusCode: {
404: function() {
alert('page not found');
}
}
});

Categories