I am using cakephp2 and working with ajax , well i have successfully get the response of ajax request form controller action but i am not getting the response from view to success method.
Here is my code.
Code For ajax Request:
var data = new Array(maincatagory,subcatagory,experience,degree,city,area);
ajaxfunction(data);
function ajaxfunction(d){
var jsonString = JSON.stringify(d);
$.ajax({
type: "POST",
url: "/FindTutor/posts/searchresults",
data: {data : jsonString},
cache: false,
success: function(data){
alert(data);
}
}).fail(function(){
alert('request fail');
});
}
Now here first I get array and pass to data after jasonStringfy.
Now In posts/searchresults action:
public function searchresults(){
if( $this->request->is('ajax') ) {
$data = json_decode(stripslashes($_POST['data']));
$this->request->onlyAllow('ajax');
$this->set(compact('data')); // Pass $data to the view
$this->set('_serialize', 'data');
$this->layout = 'ajax';
die();
}
}
And Now in searchresults view I am doing this:
<?php foreach($data as $d){
echo $d;
} ?>
But I am not getting the data back or responce from view.
Another Thing is If i echo data in controller action I get the responce successflly,Like this,
public function searchresults(){
if( $this->request->is('ajax') ) {
$data = json_decode(stripslashes($_POST['data']));
$this->request->onlyAllow('ajax');
<?php
foreach($data as $d){
echo $d;
}
?>
$this->layout = 'ajax';
die();
}
}
Help me I'm really stuck. Thanks in advance.
Related
I am trying to get a response from my controller into my view files but I'm always just getting no response. I know the controller is getting the right data and the data is in the controller because I used echo to check but then that creates the error unable to emit headers. But when I'm using $this->set I just get no response. I've followed many other questions and added the request handler and tried various things but cannot get this to work.
This is my view file blah.ctp.
<?php use Cake\Routing\Router; ?>
<?= $this->Form->create(Null, ['type' => 'POST']) ?>
<?php
echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);
?>
<?= $this->Form->end() ?>
<script>
document.getElementById('customers').addEventListener('change',function(){
var id = this.value;
var csrfToken = $('[name=_csrfToken]').val();
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
headers: {
Accept: "application/json"
},
data: {'id' : id},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
success: function(data){
alert(data);
}
});
});
</script>
This is my fill fucntion in CustomersController
public function fill(){
$layout = 'ajax';
$this->autoRender = false;
if ($this->request->is('post')) {
$id = $this->request->data['id'];
$data = $this->Customers->get($id);
$this->set(compact('data'));
$this->set('_serialize', ['data']);
}
}
The no response and preview
public function fill(){
$layout = 'ajax';
$this->autoRender = false;
if ($this->request->is('ajax')) {
$id = $this->request->data['id'];
$data = $this->Customers->get($id);
$this->response->body($data);
}
}
as i am new to codeigniter and ajax please can any one do favor for me.I am sending array from my controller to ajax function but how can i access that array element.I am posting here my code.
Thanks in advance.
public function index()
{
$Modules = $this->General_model->AllMoudules();
$data['result'] = $this->printTree($Modules);
$output = array(
'html'=>$this->load->view("Add_user",$data),
'data' => $data
);
echo json_encode($output);
}
and ajax function
$("#user").on("click",function(){
var url=static_url+'/User';
$.ajax({
type:"POST",
url:url,
success:function(output)
{
$(output).each( function (index, o) {
alert (o.data);
});
}
});
});
controller:
public function index()
{
$Modules = $this->General_model->AllMoudules();
$data['result'] = $this->printTree($Modules);
$output = array(
'html'=>$this->load->view("Add_user",$data,true),
'data' => $data
);
echo json_encode($output);
}
**Javascript:**
$("#user").on("click",function(){
var url=static_url+'/User';
$.ajax({
type:"POST",
url:url,
success:function(output)
{
console.log(output.data);
console.log(output.html);
});
}
});
Try this.
To load view in the string you have add third parameter to load view as below:
$output = array(
'html'=>$this->load->view("Add_user", $data, true),
'data' => $data
);
To access your ajax response try the below code
success:function(output)
{
console.log(output.html);
}
Just get the length of array using array.length.
Then for loop it
You should use ajax datatype as json like this
$.ajax({
type:"POST",
url:url,
dataType: 'json',
success: function (data) {
alert(data.key);
}
});
How can I get the serialized data in the Controller?
For example i have this data...
var str = $('#edit-form-data').serialize(); //string
I pass it inro the function like this...
editDosage(urlEdit,str);
My function is like this...
function editDosage(url,res)
{
console.log(url);
$.ajax({
url: url,
method: 'POST',
data: res,
success:function(data){},
error: function(data){}
});
}
How do I get the input value of the serialized data in the Controller in Laravel?
For example, I have included in the edit-form-data the name of the 'store_id' and I want to access it in the controller. Can I do something like?
$store_id = Input::get('store_id');
dd($store_id);
you may also use,
$(document).ready(function() {
$('#edit-form-data').ajaxForm();
});
checkthis out: http://malsup.com/jquery/form/
Or check this one:
$(document).ready( function(){
$(document).on('click','#submitButton', function(){
var _this = this;
var request = $.ajax({
url: url,
type: "POST",
data: jQuery("#form").serialize(),
dataType: "json"
});
request.done(function( msg ) {
});
request.fail(function( jqXHR, textStatus ){
});
});
});
And in php
try {
// input code
if($_REQUEST){
echo json_encode("success");
} else {
echo json_encode("checkinput");
}
}catch (Exception $e){
echo $e->getMessage();
echo json_encode("error");
}
You can use a few different ways to get the input.
From the Request
If your function has a Request parameter, it you can get the input from it.
public function methodA(Request $request) {
$data = $request->all();
}
You can view the documentation on Requests here.
Input Facade
Similar to requests you can use the Input Facade to get the inputted data.
public function methodB() {
$data = Input::all();
}
You can view the API docs for the Input Facade here.
Jquery code
$.post('/ajax', {'_token': $token,data: $this.serialize()}, function(resp) {
/*optional stuff to do after success */
});
controller function##
public function CreateBill()
{
parse_str($_POST['data'], $data);
return $data;
}
I'm doing an ajax call to my controller, but the alert in my success isn't displaying and I'm not getting errors in console. I don't know how to proceed now.
Controller - rate
function graph($userid, $courseid){
$i_am_admin = $this->logged_in->logged_as_admin();
if($this->session->userdata('id') == $userid || $i_am_admin ){
$this->load->model('rate_model');
$graph_data = array();
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['rate'] = $query;
}
$data['graph_json'] = json_encode($query);
$data['content'] = 'rate_graph_view';
$this->load->view('templates/template', $data);
return json_encode($query);
}
}
Script.js
$('.profileimg').click(function(){
$.ajax({
url: url, // url = http://localhost/herexamen/project/rate/graph/6/4
type:'POST',
dataType: 'json',
success: function(output_string){
alert(output_string);
alert("yes");
} // End of success function of ajax form
}); // End of ajax call
});
You aren't checking if the ajax call failed
The appended code isn't the solution, by any means, but can shed light on your problems. Notice I added the error section to the ajax request.
What is the result of this call?
$('.profileimg').click(function(){
$.ajax({
url: url,
type:'POST',
dataType: 'json',
success: function(output_string){
alert(output_string);
alert("yes");
},
error: function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
}
}); // End of ajax call
});
While making ajax calls you are supposed to echo the content or response to send and you are using return try this
echo json_encode($query);
Why view is loaded when you are making json and only
function graph($userid, $courseid){
$i_am_admin = $this->logged_in->logged_as_admin();
if($this->session->userdata('id') == $userid || $i_am_admin ){
$this->load->model('rate_model');
$graph_data = array();
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['rate'] = $query;
}
$data['graph_json'] = json_encode($query);
$data['content'] = 'rate_graph_view';
$data['viewloaded']= $this->load->view('templates/template', $data,true);
echo json_encode($data);
die();
}
}
There is a third optional parameter lets you change the behavior of
the function so that it returns data as a string rather than sending
it to your browser. This can be useful if you want to process the data
in some way. If you set the parameter to true (boolean) it will return
data. The default behavior is false, which sends it to your browser.
Remember to assign it to a variable if you want the data returned
CI Views
How to create jQuery + ajax form without refresh?
This is my controller and views:
http://pastebin.com/GL5xVXFZ
In "clear" PHP I create something like this:
$(document).ready(function(){
$("form#submit").submit(function() {
var note = $('#note').attr('value');
$.ajax({
type: "POST",
url: "add.php",
data: "note="+ note,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
in add.php file is INSERT to Database.
There are more complicated ways of doing this for example detecting an ajax request in your action and then if detected print out a javascript response. The way you would do this is
JAVASCRIPT
function postForm(note){
$.ajax({
url : '/controller/action',
type : 'POST',
data : 'note='+note,
success : function(jsn){
var json = $.parseJSON(jsn);
if(json.status == 200)
alert('Completed Successfully');
else
alert('Not Completed Successfully');
},
error : function(xhr){
//Debugging
console.log(xhr);
}
});
}
PHP
<?php
Class Controller_ControllerName extends Controller_Template{
public $template = 'template';
public function action_index(){}
public function action_form(){
$this->auto_render = false; // <-EDITED
$array = array();
//PROCESSING FORM CODE HERE
if($success){
$array['status'] = 200;
}else{
$array['status'] = 500;
}
print json_encode($array);
}
}
?>
this is an example i have done without testing but this surely should be enough for you to work on