CodeIgniter, Ajax call does not get into Controller - php

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?

Related

Ajax attributes post

where do you think I'm making a mistake in the process below? I didn't use Ajax very well I don't know I tried searching but I wasn't successful.
Html
<td>Kontrol Et
</td>
<td><div id="loading">Kontrol Edilmedi</div></td>
Ajax
$('.kontrolet').click(function () {
// add loading image to div
$('#loading').html('<img width="50" src="<?php echo base_url("assets/front/images/yukleniyor.gif"); ?>">');
// run ajax request
$.ajax({
type: "POST",
dataType: "html",
kullanici : $(this).attr('kullanici'),
url: "<?php echo base_url("kullanici-kontrol"); ?>",
success: function (d) {
setTimeout(function () {
$('#loading').html(d);
}, 2000);
}
});
});
Controller
public function kullanicikontrol()
{
echo $_POST['kullanici'];
}
I would recommend you to check your code. From what I see it's not valid code. The attribute "kullanici" is not valid for HTML. And the Ajax variable name should be "data" instead of "kullanici".
Try instead:
data-kullanici="testuser"
And for your Ajax call use:
data : $(this).data('kullanici'),
Hope this helps.

to print a session using ajax codeigniter

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.

Send data through ajax to controller in yii

First of all thanks all for your help, it's very useful. Im starting with yii and Im a bit lost yet.
I have create a jquery script where I validate a form and then I send it to my controller to work with it and save in the db.
But Im doing it wrong I think I cant connect with my controller. Here is the code:
Jquery script(after all the validate stuff, the variables are fine):
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->request->baseUrl; ?>/proceso/guardarproceso",
data:
{
post_nombre: nombre,
post_empresa: empresa,
post_fechaI: fechaI,
post_fechaF: fechaF,
post_descripcion: descripcion
},
success: function(result)
{
alert(result);
}
});
And my controller ProcesoController:
public function actionGuardarProceso(){
$nombre = $_POST['post_nombre'];
$empresa = $_POST['post_empresa'];
$fechaI = $_POST['post_fechaI'];
$fechaF = $_POST['post_fechaF'];
$descripcion = $_POST['post_descripcion'];
echo $nombre;
}
Im not working with the db yet, I only want to see if I have done it well and the alert(result) shows me the content of $nombre, but instead of that the alert shows me all the html code of the view(yes all xD)
I have done it too:
public function accessRules()
{
return array(
array(
'allow',
'actions'=>array('index','guardarproceso'),
'users'=>array('*'),
),
);
}
But nothing...
Anyone cuold help me or give me some idea? Thank you all again
1st error: url: "<?php echo Yii::app()->request->baseUrl; ?>/proceso/guardarproceso",
replace guardarproceso with guardarProceso
2nd error:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
dataType is missing; it should be json
read here http://api.jquery.com/jquery.post/
also, in the controller action actionGuardarProceso, use:
echo json_encode(array('key'=>$nombre));
exit
If a ajax or jquery result prints the html of the page its usually a error in the url.
check your network jumps to see if it goes to the controller action you want.
also baseurl is slower than createUrl. try Yii::app()->createUrl and edit that until it goes to the correct destination.. But the base of my theory is that your url is incorrect.
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->request->baseUrl; ?>/proceso/guardarproceso",
data:
{
post_nombre: nombre,
post_empresa: empresa,
post_fechaI: fechaI,
post_fechaF: fechaF,
post_descripcion: descripcion
},
success: function(result) {
alert(result);
},
error:function(jqXHR, textStatus, errorThrown){
alert('error::'+errorThrown);
}
});
first try this you will get post data or not
public function actionGuardarProceso(){
echo "<pre>";
print_r($_POST);
exit;
}
if not getting any data , try with your model
public function actionGuardarProceso(){
$model = new modelname;
echo $_POST['modelname']['post_nombre'];
exit;
}
else try with the following
public function actionGuardarProceso(){
echo Yii::app()->request->getPost("post_nombre");
exit;
}
i hope you will get now from the above any methods

JQuery not anticipating on return value

I'm currently trying to use the return value of a PHP script to do a refresh action with jQuery. My PHP script is doing what it should do, return the value "reload" when a certain requirement is met; jQuery then however displays "reload" briefly and doesn't act on the refresh action that I've required it to do.
$.ajax({
url: '/bidstatus.php',
data: {
sale_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
dataType: 'json',
type: 'get',
success: function(output) {
if (output == "reload") {
location.reload();
}
}
});
The PHP that returns the value, when a requirement has been met, looks like this:
echo json_encode("reload");
Also, to make it even more confusing, it sometimes does what it has to do, but it's not consistent at all.
So, am I missing something?
Since I saw this was still open and I managed to fix it myself, I'll post the code so it can/may help others with similar problems.
This was the code that fixed it.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function()
{
$.post('/bidstatus.php',
{
auction_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
function(data)
{
if(data == "reload"){
location.reload();
}
else{
$('#shop-balance').html(data);
}
}
);
}, 1000);
});
Well, try this:
function do_ajax(callback)
{
$.ajax({
url: '/bidstatus.php',
data: {
sale_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
dataType: 'json',
type: 'get',
success: function(data){
callback(data);
},
});
}
Just check it again and if you use any global scope variable then pass it through function's parameters.
And call it like this::
do_ajax(function(data) {
if (data == "reload") {
location.reload();
}
}
);
What I have done is to set a callback for your .success state, rather than direct code execution. Since Javascript executes the code asynchronously, it just passes the .success before the AJAX is finished, and thus, the data will not be "output" and it is "null" probably. You shoul add a callback there and execute it through a callback to allow the Javascript Interpreter to accomplish the task.

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);
}
});
});

Categories