CakePHP 3 and partial View update via Ajax - How it should be implemented? - ajax

I want to render a cakephp3 template by ajax and inject the html into a loaded page (without reloading the page).
According to
CakePHP 3 and partial View update via Ajax - How it should be done?,
the idea can be
Create dedicated template (*.ctp) file for every ajax action, render
it like any other action but without the main layout and inject the
HTML (kind of variant 1 but with separated VC logic).
It also provides a partial example code:
public function ajaxRenderAuditDetails($id = null)
{
if ($id == null) {
return null;
}
if ($this->request->is("ajax")) {
$this->set("result", $this->viewBuilder()->build()->cell("audits", [$id]));
}
}
May anyone suggest a full example?

For this you have to use a Ajax call for get data from server. In term of CakePhp you will call a controller function using Ajax. This function call a ctp file which render your partial view. Success function of Ajax should updated or append the partial view. A complete example code for this process is here -
Ajax code for call controller function -
$.ajax({
dataType: 'json',
url: basepath/controllername/controllerfunction,
type: "POST",
dataType : 'html',
success: function (data) {
$(selector).html(data);
}
});
public function ajaxRenderAuditDetails($id = null){
$this->viewBuilder()->layout(false);
if ($id == null) {
return null;
}
if ($this->request->is("ajax")) {
$this->set("result", $this->viewBuilder()->build()->cell("audits", [$id]));
}
}
Put your required html or logics in ctp file.
This is not a running code. It is sample example for updating partial view in CakePhp.

Related

How to pass variables from Controller to View without refreshing the Web Page in Laravel?

Whenever there is a call to Controller inside View, I want the Controller to return some variables to the View and do not refresh the View.
Already know:
return view("webpage" , compact('variable1', 'variable2') );
What I expect to achieve:
return compact('variable1', 'variable2');
This will not return the Webpage but only some of the variables.
Edit:
Thinking it from a complete different perspective, The question maybe rephrased as such
Is there a way to manipulate REQUEST variables of a web page from the controller? This way, i would be able to get new variables from the Controller without the web page being Refreshed.
With out much to work with, here is an example:
Ajax call:
$.ajax({
url: '/your/route/',
type: 'GET',
data: {getVariable: formInputValue},
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log('Failed');
});
Controller Function:
public function getVariable(Request $request){
$resault = $request->getVariable;
return response()->json($results);
}
Update: as per comments on this answer try this and see if it works for you.
In your controller where you fetch records instead of using a ->get();
change it to paginate(5); this will return 5 records per page. and on your view at the bottom of your </table> add {{ $variable->links() }}

View returning in popup laravel 5.4

I am returning a view from controller, but instead of opening new page, the view is opening in popup which i assume is error message popup,. i am new in laravel.
Controller Code
public function postRegister () {
return view('front.member.registerpayment')->with('amountUSD', $data['btc_withcom']);
}
You can do this using AJAX request.
In your controller…
public function postRegister () {
// do something to get your data
return response()->json(
[
'data'=>$your_data
]
);
}
Then make a ajax request
First import jquery.
Then
$.ajax({
url: ‘your url’,
method: ‘POST’
data: ‘pass any data to controller’
success: function(data){
// invoke popup with data
// you can easily do this with jquery UI library
}
})
Here is the complete example to open dialog box.
Hint: append your data to html before invoking

Poplate View with new updated Model in success function of $.ajax

I am making an ajax call to controller to post data from view to controller.And in the receiving controller I am updating my model with new values.Now I want to bind this new model to view again in success call of $.ajax post.Please Suggest.
one way to do this is to return a partial view from the controller. You can replace the contents of your previous view with the new html content. Lets expand on this...
so, here is your controller action
[HttpPost]
public ActionResult SomeMethod(params...){
....
var model = some model;
...
return PartialView("ViewName",model);
}
and in the ajax, use
$.ajax({
url : #Url.Create("Action","Controller"),
type : 'POST',
data: { ... your data params ..},
success : function(result){
$("#ContainerId").html(result);
}
})
in the html you would need a div with the id = "ContainerId". The content would get swapped out by the html passed back in the success function.
The Model is only used in RAZOR when rendering the page. Once you get to the point where you are using AJAX, the model is no longer available to you.
What, exactly, are you trying to accomplish? Maybe there is another way to do it?

MVC3 redirect to action after ajax call

In an ASP.NET MVC3 Application I have a button in the view.
When the button is clicked a function is called and it jquery ajax call is made to save items to the database
function SaveMenuItems() {
var encodeditems = $.toJSON(ids);;
$.ajax({
type: 'POST',
url: '#Url.Action("SaveItems", "Store")',
data: 'items=' + encodeditems + '&storeKey=#Model.StoreID',
complete: function () {
}
}
});
}
What i want is after the items are saved to the database I want to redirect to another view. (Redirect to action)
How can I do that?
I tried to use return RedirectToAction("Stores","Store") in the controller at the end of the SaveItems function. But it is not working
I also tried to add window.location.replace("/Store/Stores"); in the complete function of the ajax call but didn't work either
Any help is greatly appreciated
Thanks a lot
You can use javascript to redirect to the new page. Set the value of window.location.href to the new url in your ajax call's success/complete event.
var saveUrl = '#Url.Action("SaveItems","Store")';
var newUrl= '#Url.Action("Stores","Store")';
$.ajax({
type: 'POST',
url: saveUrl,
// Some params omitted
success: function(res) {
window.location.href = newUrl;
},
error: function() {
alert('The worst error happened!');
}
});
Or in the done event
$.ajax({
url: someVariableWhichStoresTheValidUrl
}).done(function (r) {
window.location.href = '#Url.Action("Stores","Store")';
});
The above code is using the Url.Action helper method to build the correct relative url to the action method. If your javascript code is inside an external javascript file, you should build the url to the app root and pass that to your script/code inside external js files and use that to build the url to the action methods as explained in this post.
Passing parameters ?
If you want to pass some querystring parameters to the new url, you can use this overload of the Url.Action method which accepts routevalues as well to build the url with the querystring.
var newUrl = '#Url.Action("Stores","Store", new { productId=2, categoryId=5 })';
where 2 and 5 can be replaced with some other real values.
Since this is an html helper method, It will work in your razor view only,not in external js files. If your code is inside external js file, you need to manually build the url querystring parameters.
Generating the new url at server side
It is always a good idea to make use of the mvc helper methods to generate the correct urls to the action method. From your action method, you can return a json strucutre which has a property for the new url to be redirected.
You can use the UrlHelper class inside a controller to do this.
[HttpPost]
public ActionResult Step8(CreateUser model)
{
//to do : Save
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Stores", "Store");
return Json(new { status = "success", redirectUrl = url });
}
Now in your ajax call's success/done callback, simply check the return value and redirect as needed.
.done(function(result){
if(result.status==="success")
{
window.location.href=result.redirectUrl;
}
else
{
// show the error message to user
}
});
In action you can write this:
if(Request.IsAjaxRequest()) {
return JavaScript("document.location.replace('"+Url.Action("Action", new { ... })+"');"); // (url should be encoded...)
} else {
return RedirectToAction("Action", new { ... });
}
Try
window.location = "/Store/Stores";
Instead.

Redirecting to error page if a partial view encounters an error [duplicate]

This question already has answers here:
ASP.NET MVC Custom Error Handling Application_Error Global.asax?
(10 answers)
Closed 2 years ago.
I'm rendering a partial view inside of a view:
#{
Html.RenderAction("PartialViewAction", "SomeController");
}
Is there a way to redirect the user to an error page if the partial view action encounters an error?
EDIT: I'm looking for a server side kind of redirection. This partial view is not loaded with AJAX. It is rendered server side into a "big" view. The "big" view has no idea that the partial view errored out.
Depending on your logic, you might be able to control your application flow by using jQuery.ajax() to handle errors.
// this will render the GET request on page load
$(function() {
$.ajax({
url: '/Some/PartialViewAction',
type: 'GET',
dataType: 'json', /*edit*/
success: function(xhr_data) { /*edit*/
// the following assumes you wrap
// your partial view in div id="myDiv"
$('#myDiv').html(xhr_data.html); /*edit*/
$('#myErrorDiv').html(xhr_data.error); /*edit*/
},
error: function() {
window.location.href='/Some/Error';
// or similar page redirecting technique
}
});
});
This will handle an error in the GET, but of course if you were to return some JSON or some other indicator in your action method, you could use the same window.location.href... in the success callback function.
Edit
Also see above edits to $.ajax
Your controller could do something like this:
public ActionResult PartialViewAction() {
// handle error
string message = "Evacuate, Immediately!";
// not certain the html will render correctly,
// but you could encode/parse/whatever easily enough
return Json(new { html = "<div>some html</div>", error = message },
JsonRequestBehavior.AllowGet);
}

Resources