Reputation: 2520
I , im working with Ajax and Codeigniter to call function client-server
the php
public function mainViewClean() {
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
return "Ready";
}
//route $route['cleantags'] = 'user/mainViewClean';
And ajax:
<script type="text/javascript">
$(document).ready(function(){
$("#btn_recargar").button().click(function(){
//window.location.href = "<?= base_url('home')?>";
$.ajax({
type:'POST',
url:'<?php echo base_url("cleantags"); ?>',
data:{'id':100},
success:function(data){
//window.location.href = "<?= base_url('home')?>";
alert(data);
}
});
});
});
</script>
The function excuse good , but javascript don't show any data , what im doing wrong?
Upvotes: 1
Views: 1514
Reputation: 149
I'm fairly new as I only have been using AJAX , but I think your code has a few syntactical errors.
I advise you need to look at more examples of ajax calls to fix these little errors.
You said your JS is working but not showing data?
Upvotes: 0
Reputation: 9060
Change return
into :
echo "Ready";
If you're sending an array, at server side you need to json_encode
, example :
// encode array into json string format
echo json_encode( array( 'name' => 'Osman' ) );
And in Js, you have 2 options, the 1st solution is :
success : function ( data ) {
// data now is coming in this form { "name" : "osman" }
// as the string data is coming from server-side
// you must parse it back into Javascript object
var newData = JSON.parse( data );
}
And the 2nd option is, add dataType
properties inside ajax properties like following :
$.ajax({
...
dataType : 'json', // with this, no need to write JSON.parse()
...
});
Upvotes: 1
Reputation: 16997
Well, the ajax call reads the response from the server, and that response must be rendered as some type of readable data, such as application/json
or text/html
.
In order to write that data, you need to echo
it from the server with PHP.
The return
statement doesn't write data, it simply returns at the server level.
If you want to communicate between PHP
functions, you have to use return
. But if you want to output some data, you have to use echo
Client side
$.ajax({
url:'<?php echo base_url("cleantags"); ?>',
dataType: 'application/json',
success:function(response)
{
alert(response.foo);
}
})
Server Side
public function mainViewClean()
{
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
echo json_encode( array("foo"=>"Ready"));
}
Upvotes: 2