ajax post to controller and display into custom element file - ajax

i need to fetch data from database from controller file and display into element file and ajax value showing in inspect element and also when i alert in ajax it is showing that value is going to controller.
but problem is that how can i echo or print ajax value in controller to fetch data from database and display it into element file?
how can i render custom element file in controller function?
ajax script
<script>
$('#categories .accordion .tablist .tablistitem').on('click', function () {
event.preventDefault();
$(".accordion li").removeClass("active");
var $li = $(this);
$liid = $li.attr('id');
$slug = $li.data('slug');
$li.addClass("active");
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#categories_info').show();
$.ajax({
type: 'POST',
url: '/reviews/getsubcategories',
data: {"selectid":$liid },
dataType:"text",
success: function(data, textStatus, xhr) {
alert(data);
},
error: function(xhr, textStatus, error) {
alert(textStatus);
}
});
});
</script>
controller function
function getsubcategories()
{
echo $selectid= $_POST['selectid'];
return $selectid;
}
element file
$SubCategoryObj = cri('Reviews');
$selectid = $SubCategoryObj->getMainCategories();
echo $selectid;

What you have done so far is mostly right, however in the past I have just created the view as normal in the View/Reviews folder.
In the controller set your data:
/app/Controller/ReviewsController.php
public function getsubcategories()
{
$this->layout = 'ajax';
$data = /**code to get data**/
$this->set('data', $data);
}
/app/View/Reviews/getsubcategories.ctp
<?php echo json_encode($data); ?>
another option is to create the same view above but put it in file app/View/Ajax/json.ctp
And then inside the controller the last thing you call in the getsubcategories action is.
$this->render('Ajax/json');
In my experience elements are used inside views and not as replacements of views

Related

Laravel ajax return whole HTML page instead data

I'm having this trouble with the ajax request. This code works on other pages, only on this not working.
I want to call ajax (from different controller - CalendarController) on "show" page from controller ClientController - (http://.../client/35) maybe is that wrong
Client.js
$(document).ready(function() {
$('#events-list').on('click', '.event-popup', function () {
var getEventId = $(this).data('id'); //this line is okay, return dynamic id as i want
$.ajax({
type: "GET",
url: "getEvent/" + getEventId,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json',
})
.done(function (data) {
console.log(data); //if i remove dataType: 'json' whole page will print in log instead data
})
.fail(function(data,jqXHR, textStatus, errorThrown) {
toastr.error("error");
console.log(data,jqXHR, textStatus, errorThrown);
})
});
});
Error message from ajax
parsererror" SyntaxError: Unexpected token < in JSON at position
...
responseText: "<!DOCTYPE html><html lang="sr"><head>... - WHOLE PAGE
web.php
Route::get('/getEvent/{id}', 'CalendarController#getEventData');
CalendarController
public function getEventData($id)
{
$event = Event::findOrFail($id);
return Response::json($event);
}
I added how to Controller looks but does not return data, this ajax call does not come to the controller
I think the problem is somewhere in the URL or because I want to add data with another controller to the show page, but I can't figure
Thanks in advance
EDIT
Ajax request is redirected for some reason
Instead of findOrFail() (it returns HTML if the object doesn't exist), use find() method. Then you can check if the object exists or not and return json as per the condition.
Example:
public function getEventData($id)
{
$event = Event::find($id);
if(!$event) {
return response()->json([
'success' => false,
'message' => 'Not Found'
], 404);
}
return response()->json($event);
}

Redirect to another view using AJAX call in Codeigniter

My table contains many rows from database. After clicking edit button in a row, I want to redirect it to another page. I am able get the data, but it cannot redirect to the other page.
I'm using bootstrap template, so there are different file to load on view. I do not know how to load view that consist of more than one files.
Ajax
$('#example2').on('click','#edit',function(){
var id_per = $(this).closest('tr').attr('id');
alert("ini"+id_per);
$.ajax({
url:"<?php echo base_url('c_dokter/ubahdt_perawatan/');?>" + id_per,
type:"POST",
data:{
id_perawatan : id_per,
id_pasien : id_pasien
},
dataType:'JSON',
success:function(data) {
},
error:function() {
alert('error ... ');
}
});
Controller
public function ubahdt_perawatan($id_perawatan){
$data['pasien']=$this->m_pasien->spes_Perawatan($id_perawatan);
if ($this->input->is_ajax_request()) {
echo json_encode($data);
exit;
}
$data['pasien']=$this->m_pasien->DataPerPasien($id_pasien)->result();
$data['sidebar']='member/dokter/sidebar_psn';
$data['content']='member/dokter/edit_perawatan';
$this->load->view('member/dokter/main',$data);
}
Edited answer:
public function ubahdt_perawatan($id_perawatan){
$data['pasien']=$this->m_pasien->spes_Perawatan($id_perawatan);
if ($this->input->is_ajax_request())
{
echo json_encode($data);
}
}
public function test()
{
$id_pasien=$this->uri->segment(2);
$data['pasien']=$this->m_pasien->DataPerPasien($id_pasien)->result();
$this->load->view('member/dokter/sidebar_psn');
$this->load->view('member/dokter/edit_perawatan');
$this->load->view('member/dokter/main',$data);
}
set path to test() in routes.php..
$route['test/(:any)']='controller/test';
then in ajax success function
success:function(data){
window.location.href="<?php echo site_url('test/'.data);";
},
try it.

How do I request views from a layout using AJAX?

In my MVC application I don't want the layout page to reload everytime a view is selected. It would be great if the views could be loaded using ajax to keep things nice and fast and allow me to persist certain interface states that are wiped out when you move around.
My initial approach was to add some ajax to the _Layout.cshtml and then whent he view was requested pass that request to the controller method which will grab that page. All I ended up doing however was returning the WHOLE view again.
Here is the code I have so far, am I on the right tracks here or is this totally wrong?
Layout Ajax Script
<script>
$(function () {
var content = document.getElementById('content');
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
console.log("Data Attrib : " + page);
$.ajax({
type: 'GET',
url: '#Url.Content("~/Home/")' + page,
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
</script>
As I say, this sort of works, but it's not perfect as it returns the whole page into the content area including layout, ideally I just want the core view data.
you can create a Single Page Application that have 1 layout and in home controller and index action method create menu or user setting or another things
and now you can load other action with Ajax call with data-content html that does not have layout file and append that in container
when user click another menu clean older content and add new or you can create tab strip or window
Layout.cshtml
<script>
$(function () {
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
$.ajax({
type: 'POST',
url: '/Home/Pages',
data: { pageValue: page },
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
Controller
public class HomeController : Controller
{
[HttpPost]
public string Pages(string pageValue)
{
string result = //Whatever
return result;
}
}
Controller
public ActionResult SomeAction(String someparams)
{
//Make the model
SomeModel someModel = new SomeModel();
someModel.someparams = someparams;
return PartialView("SomePartialView", someModel);
}
In View
$.ajax({
url: "/Home/SomeAction",
type: "POST",
dataType : "html",
data: json,
contentType: 'application/json; charset=utf-8',
success: function(data){
$('#SomeDivID').html(data);
}
});

zf2 and ajax I can't get the parametrs

I can not get the data passing from the controller ajax me there any solution?
button click action
$(".bajaAlumno").click(function () {
var urlform = "<?php echo $this->url(null, array('controller'=>'Academius','action' =>'bajaAlumnos' ) ); ?>";
var dato= $(this).attr('id');
var myData = {textData:dato};
$.ajax({
type:"POST",
url:"/Academius/bajaAlumnos",
data:{data:myData},
success: function(data){
//The callback function, that is going to be executed
//after the server response. data is the data returned
//from the server.
// Show the returned text
//$("#answer").text(data.text);
//$("#answer").text(data.text);
alert('enviado');
}
});
});
and controller
public function bajaAlumnosAction()
{
die(var_dump($this->params()->fromPost()));
}
one answer?

how can i get file data on ajax page in magento?

I have made a custom module in magento. I am using ajax in it(prototype.js).i can find the post variable on ajax page. But I am unable to find the file array on ajax page.
I am using following code for this.Please let me know where i am wrong?
//Ajax code on phtml page
new Ajax.Request(
reloadurl,
{
method: 'post',
parameters: $('use-credit-Form').serialize(),
onComplete: function(data)
{
alert(data.responseText);
}
});
//Php code on ajaxpage
public function ajaxAction()
{
$fileData = $_FILES;
echo '<pre>';
print_r($fileData);die;
}
It always print blank. but when I added this line
"VarienForm.prototype.submit.bind(usecreditForm)();"
I can get the value of file array. but draw back now page starts refreshing.
Please give me some suggestion.
Try this:
Event.observe('use-credit-Form', 'submit', function (event) {
$('use-credit-Form').request({
onFailure: function () {
alert('fail.');
},
onSuccess: function (data) {
alert(data.responseText);
}
});
Event.stop(event); // stop the form from submitting
});
Credit: submit a form via Ajax using prototype and update a result div

Resources