View returning in popup laravel 5.4 - laravel

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

Related

Print fetched data with ajax in codeigniter

I am trying to make chat room with ajax. Till now I am able to store data in db without page load. And also able to fetch data and display onscreen using ajax. Here is what I did with ajax
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val(); //chat message from input field
var chatroomid = $("#chatroomid").val(); //hidden input field
$.ajax({
url: baseurl+'User_dash/chatmessage', //An function in ctroller which contains only insert query
type: 'post',
data: {chatmsg:chatmsg, chatroomid:chatroomid},
dataType: 'json',
success: function (argument) {
if(argument['status']){
$("#chatting").append(" <li id='"+getvalue+"'>"+argument['msg']+"</li>."); //Here I am printing chat message which resently submitted in database
}
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
This method with ajax is working fine. But issue I faced here is that, this display chat message only to current user. Not to other side of user whome message is being sent via chat.
To solve this issue I come up with one idea which doesn't seems to be working as I planed. Here it is how I modified my previous ajax code..
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val();
$.ajax({
url: baseurl+'User_dash/chat', //controller function which contains insert query, after that select query to fetch chat data from db and store in view
type: 'post',
data: {chatmsg:chatmsg},
dataType: 'json',
success: function (argument) {
if(argument['status']){
//Not doing anything here this time
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
In updated version of script I thought If I will call a controller function which is storing data in view (chat page) then It will run query and print data without page load.
But with this method, I am getting chat onscreen only after page load, although it is getting submit in db with ajax fine.
Here is controller code for my second method with ajax if needed
public function chat(){
if(!empty($_POST['chatmsg'])){
$chatdata = array('CHAT_ROOM'=>$_POST['chatroomid'],
'VENDOR'=>$this->session->userdata('USER_ID'),
'BUYER'=>49,
'MESSAGE'=>$_POST['chatmsg']
);
$this->db->insert('tbl_chat', $chatdata); //inserting data
}
$data['chatroom'] = $this->db->where('CHAT_ROOM', 1)->get('tbl_chat')->result_array(); //fetching data from db
$this->load->view('userDash/chat', $data);
}
How do I achieve to run insert and then select query and print data on screen without page load?
Where I am getting wrong?
I solved my issue earlier, What I did was, just added this jquery script which keep refreshing (every second) a certain div inside page in which I have put query to fetch chat from db and printing them.
setInterval(function(){
$("#chatting").load(location.href + " #chatting");
}, 1000);

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

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.

Insert Data Using Ajax

I am using Laravel 5.3. I want to insert the data using blade template.But my when i press submit button it gets refreshed every time. what to do? and please anyone tell me how to use ajax url,type,data
If you try to submit via Javascript make sure prevent form default action with e.preventDefault(). This code prevent the form submitted in a regular way. Just add this code to wrap your AJAX call:
$('#form-id').submit(function(e){
e.preventDefault();
$.ajax({...});
});
I just assume you are using jquery if you are talking about ajax. It's really simple. Your laravel routes listen to "post", "get", "patch", "delete" methods.
Everything of these can be created with a ajax request - example:
$.ajax({
method: "POST",
url: "/posts",
data: { title: "Hello World", text: "..." }
})
.done(function( post ) {
// assuming you return the post
alert(post.title + " created");
});
Now that you use ajax you will not want to return a view to the ajax call. You have different options here (create a new route, helper functions etc.) I will give the most easy example
Controller function:
public function store(Request $request) {
$post = App\Post::create($request->all());
if($request->ajax()) {
return $post;
} else {
return redirect('/posts');
}
}
now you controller will return data on ajax calls and will redirect you on default calls without ajax.
Finally you have a last thing to keep in mind. If you have web middleware applied ( done by default ) you need to handle the csrf token. The most easy way to handle this is by adding a meta tag to your html head
and then (before doing all your calls etc.) add this to configure your ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
this will add the valid csrf token which is in your head to every ajax call and will ensure you not run into token missmatch exceptions.
Things to keep in mind:
- if you stay very long on one page tokens might expire ( laravel-caffeine will help here )
- you need to handle validation for ajax calls

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.

How to avoid redirect after form submission if you have a URL in your form's action?

I have a form that looks like this:
<form name="formi" method="post" action="http://domain.name/folder/UserSignUp?f=111222&postMethod=HTML&m=0&j=MAS2" style="display:none">
...
<button type="submit" class="moreinfo-send moreinfo-button" tabindex="1006">Subscribe</button>
In the script file I have this code segment where I submit the datas, while in a modal box I say thank you for the subscribers after they passed the validation.
function () {
$.ajax({
url: 'data/moreinfo.php',
data: $('#moreinfo-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#moreinfo-container .moreinfo-loading').fadeOut(200, function () {
$('form[name=formi]').submit();
$('#moreinfo-container .moreinfo-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
Unfortunately, after I submit the datas, I'm navigated to the domain given in the form's action. I tried to insert return false; in the code (first into the form tag, then into the js code) but then the datas were not inserted into the database. What do I need to do if I just want to post the data and stay on my site and give my own feedback.
I edited Eric Martin's SimpleModal Contact Form, so if more code would be necessary to solve my problem, you can check the original here: http://www.ericmmartin.com/projects/simplemodal-demos/ (Contact Form)
Usually returning false is enough to prevent form submission, so double check your code. It should be something like this
$('form[name="formi"]').submit(function() {
$.ajax(...); // do your ajax call here
return false; // this prevent form submission
});
Update
Here is the full answer to your comment
I tried this, but it didn't work. I need to submit the data in the succes part, no?
Maybe, it depends from your logic and your exact needs. Normally to do what you asking for I use the jQuery Form Plugin which handle this kind of behavior pretty well.
From your comment I see that you're not submitting the form itself with the $.ajax call, but you retrieve some kind of data from that call, isn't it? Then you have two choices here:
With plain jQuery (no form plugin)
$('form[name="formi"]').submit(function() {
$.ajax(...); // your existing ajax call
// this will post the form using ajax
$.post($(this).attr('action'), { /* pass here form data */ }, function(data) {
// here you have server response from form submission in data
})
// this prevent form submission
return false;
});
With form plugin it's the same, but you don't have to handle form data retrieval (the commented part above) and return false, because the plugin handle this for you. The code would be
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm(function() {
// this call back is executed when the form is submitted with success
$.ajax(...); // your existing ajax call
});
});
That's it. Keep in mind that with the above code your existing ajax call will be executed after the form submission. So if this is a problem for your needs, you should change the code above and use the alternative ajaxForm call which accepts an options object. So the above code could be rewritten as
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm({
beforeSubmit: function() { $.ajax(...); /* your existing ajax call */},
success: function(data) { /* handle form success here if you need that */ }
});
});

Resources