I have a folder (suppose it's name is "test") outside of controller folder which contains a file name "error404.php" and my controller name is "test_controller.php" which has a method name "tst()". error404.php is a view page in where i want to access data from test_controller.php via ajax.
<script>
$(document).ready(function(e) {
$('#search_items_err').keyup(function(e) {
if($('#search_items_err').val().trim()==''){$('#sugglist').html(''); return false;}
search_key=$(this).val().trim();
var data = {
search_key: search_key
};
alert(search_key);
$.ajax({
data: data,
type: "post",
url: "test_controller/tst",
success: function(response) {
var options = JSON.parse(response);
alert(options);
}
});
});
});
</script>
My tst function is:
public function tst(){
$search_key = $_POST['search_key'];
echo "success";
}
But my ajax doesn't work. I suspect that it may contain some problems in the (url: "test_controller/tst",). So how can i solve it? What is the syntax of accessing test_controller's method from error404.php page?How do i access base url?
Take a look at this ajax concept
in your ajax function :
url : baseURL+'test_controller/search', //Make sure this url is working properly
data : {'search_key' : search_key},
in you test_controller/search
public function search()
{
//generate data and load your view
$data = "Generated Data array";
$this->load->view('test_folder/search', $data); //Load your view from application/view/ not from outside the controller
}
Related
I have trying to load a page using simple get request
<script>
$(document).ready(function(){
$("li").click(function(e){
e.preventDefault();
var href = $("a",this).attr('href');
$.ajax({
async: true,
type: "GET",
url: href,
success: function (response) {
$('#main-content').html(response);
}
})
});
});
</script>
In response I am getting content with full layout. But Here I am trying to get only content without layout. In controller I have written code like below
public function index()
{
if ($request->ajax())
{
$this->layout = null; //but same result
}
$tags = Tag::orderBy('id', 'desc')->paginate(10);
return view('admin.tags.index')->with('tags',$tags);
}
But I am getting same result with layout, how can I make layout false ? Or can change layout in controller ?
you can use the renderSections
return view('admin.tags.index')->renderSections()['content'];
https://laravel-tricks.com/tricks/render-view-without-layout
Well, you are still returning a view. Why not do:
return response()->json(["data"=>"some data"]);
after your Ajax check? This will return a JSON response to your frontend.
I am using ajax in yii2.
How to fill fields without submit form. Without submitting the validation is working, but how to add field value.
In below code $this->name is my field name.
if($this->statusOk){
$this->name = "gana";
}else{
return $this->addError('branch_code', ' code can’t be found');
}
you can set your value in save function(in model) or before saving your model(in controller) ,and use custom validation just for validation.
Try this,custom ajax
$(document).ready(function () {
$("body").on("blur", "#id", function () {
var data = $("#nameField").val();
$.ajax({
url : "validURL",
type : "post",
data : {"sortcode":data},
success: function (response)
{
var json_obj = $.parseJSON(response);
if(json_obj.errorMessage) {
// do something
}else {
// do something
}
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
I'm trying to send a Backbone collection to Laravel with an Ajax Request.
I don't need to save it or update the database I just need to process the data with the Omnypay php Api. Unfortunately the Laravel Controller variable $input=Input::all() contain an empty string.
var url = 'index.php/pay';
var items = this.collection.toJSON;
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: items,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
This is the Laravel Route:
Route::post('pay','PaypalController#doPay');
And finally the Laravel Controller:
class PaypalController extends BaseController {
public function doPay() {
$input=Input::all();
}
}
Your route doesn't match, it's
Route::post('pay','PaypalController#doPay');
So the url should be
var url = 'pay';
instead of
var url = 'index.php/pay';
BTW, not sure if anything else (backnone) is wrong.
Update : toJSON is a method, so it should be (you missed ())
var items = this.collection.toJSON();
The hack solution I found to transfer a backbone collection to Laravel was to convert the collection to JSON and then wrapping it in a plain object, suitable for the jQuery Ajax POST. Here is the Code:
var url = 'index.php/pay';
var items = this.collection.toJSON();
var plainObject= {'obj': items};
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: plainObject,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
Now the $input variable of my "doPay" controller function contain an array of Backbone models.
I have an MVC application that I'm using various JsonResult endpoints to populate the javascript ViewModel.
I have been using several jQuery Ajax requests to populate the model, but I'd like as much of the inital model to be passed to the view on the server.
The ViewModel has 3-5 pieces (depending on where the user is in the application):
Basic page links, these don't change very often and could be the exact same throughout the entire user's session
User notifications.
User data.
(optional) Viewable data
(optional) misc data
I'm currently using this code to load the first three pieces:
$(document).ready(function () {
ko.applyBindings(viewModel);
#Html.Raw(ViewBag.Script)
// Piece 1. Almost always the same thing
postJSON('#Url.Action("HomeViewModelJson", "Home")', function (data) {
if (data == null)
return;
for (var i in data.Tabs) {
viewModel.tabs.push({ name: data.Tabs[i] });
}
for (var i in data.Buttons) {
viewModel.metroButtons.push({ name: data.MetroButtons[i] });
}
for (var i in data.Ribbons) {
viewModel.ribbons.push(data.Ribbons[i]);
}
ApplyButtonThemes();
});
});
// Piece 2. Changes constantly. OK as is
postJSON('#Url.Action("GetNotifications", "NotificationAsync")', function (nots) {
viewModel.notifications.removeAll();
ko.utils.arrayForEach(nots, function (item) {
item.readNotification = function () {
hub.markNotificationAsRead(this.Id);
return true;
};
viewModel.notifications.push(item);
});
});
// Piece 3. Changes but should also be loaded at startup
postJSON('#Url.Action("GetUser", "UserAsync")', function (user) {
viewModel.user(koifyObject(user));
});
postJSON = function(url, data, callback) {
if($.isFunction(data)) {
callback = data;
data = {};
}
$.ajax({
'type': 'POST',
'url': url,
'contentType': 'application/json',
'data': ko.toJSON(data),
'dataType': 'json',
'success': callback
});
};
I tried doing something like this, but I'm finding that by using the #Html.Action("HomeViewModelJson", "Home") is causing the HTTP headers to get changed and the whole page is sent as if it were JSON
(function (data) {
if (data == null)
return;
for (var i in data.Tabs) {
viewModel.tabs.push({ name: data.Tabs[i] });
}
for (var i in data.MetroButtons) {
viewModel.metroButtons.push({ name: data.MetroButtons[i] });
}
for (var i in data.Ribbons) {
viewModel.ribbons.push(data.Ribbons[i]);
}
ApplyMetroButtonThemes();
})('#Html.Action("HomeViewModelJson", "Home")');
What I'd like to do is use the existing JsonResult endpoints to get Json data into my ViewModel on the server side, before the page is sent to the user.
Are there any options that will allow me to do that w/o rewriting my controllers?
When rendering the main view you are using a view model, right? In this view model simply populate the properties that you don't want to be fetched with AJAX before returning the view:
public ActionResult Index()
{
MyViewModel model = ...
model.Prop1 = ...
model.Prop2 = ...
return View(model);
}
for example if you have the following action that is used for the AJAX requests:
public JsonResult GetProp1()
{
Property1ViewModel model = ...
return Json(model, JsonRequestBehavior.AllowGet);
}
you could use it from the main action to populate individual properties:
model.Prop1 = (Property1ViewModel)GetProp1().Data;
model.Prop2 = (Property2ViewModel)GetProp2().Data;
and then inside the corresponding view you could use the Json.Encode method to serialize the entire model into a JSON string:
#model MyViewModel
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
// You could use model.Prop1 and model.Prop2 here
</script>
or you could also serialize individual properties if you don't need all of them:
#model MyViewModel
<script type="text/javascript">
var prop1 = #Html.Raw(Json.Encode(Model.Prop1));
</script>