Return a view via ajax in laravel - php

I want to display a view to the user whenever user clicks on a button using ajax.
This is my code.
// BASE = localhost/project/public/
$('#button').click(function() {
$.ajax({
url: BASE + "user/settings",
type: 'GET'
})
.done(function( data ) {
console.log( data );
});
});
And my routes.php
Route::get('user/settings', 'UserController#getSettings');
And UserController.php
public function getSettings(){
return View::make('user.settings');
}
But output is this error:
{"error":{"type":"ErrorException","message":"Undefined offset: 0","file":"H:\\dev \\xampp\\htdocs\\lchat\\vendor\\laravel\\framework\\src\\Illuminate\\Support \\Collection.php","line":470}}
EDIT: error was in view. I fixed it.
Problem2: The page which is loading via ajax, itself contains another ajax post request. but it's not sending data via ajax anymore. refreshes the page to send data.
The jquery code:
$('#settings :submit').click(function(e){
e.preventDefault();
$.post(BASE + 'settings/save', {
'userName' : $('#userName').val()
}, function(data) {
return 'OK';
});
});
Problem solved: I used .on to bind event:
$(document).on('click', '#settings :submit', function(e){ ... } );
It's working...
Thank everyone.

Well, for starters, you have an error in your view. The error you're getting is in reference to an array you're trying to access that doesn't actually have the key you're trying to use ($arr[0]).
Once you fix the errors with the view itself, it should work fine. The JavaScript will get the data as HTML, and you can just insert it into wherever you want it to show up.

Use string method before view file
return (String) view('Company.allUserAjax');

Related

Laravel 5.2 return with errors - how to tell which form is submitted

I'm using Laravel 5.2. On my index page, I've got a button to add a new entry, which brings up the form in a lightbox. This form then submits via the create method.
I also have each entry listed on this page, with the ability to edit them inline, which submits via the update method.
I've setup validation via a Request. This means when someone misses something on the add, it redirects to the index method with errors. The errors only show though, when the lightbox is triggered by the user.
I know I can use $errors to see any errors, but I don't see how I can differentiate between the create and update forms for the sake of forcing the lightbox to appear on reload with create errors. Is there a way to do that?
Update:
Suggestion was made to use AJAX to bypass the reload issue, but now I'm getting a 422 return:
AJAX call:
(function(){
var submitAjaxRequest = function(e){
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(data){
console.log(data)
}
});
e.preventDefault();
}
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
Request:
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
I've also tested the ajax call and it works fine when the validation rules are met. It only fails if the validation comes back with something incorrect in the input.
You could override the response method so that you can flash the type of request.
In you Request class you could add
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
(With ajax you wouldn't need to worry about the page reload so we can just return the original response.)
In the above I'm assuming you're using POST for your create methods and PUT or PATH for your update methods. If this is not the case you could use a way that make sense to you to differentiate between the requests.
Then in your view you could do something like:
#if(session('requestMethod') == 'POST')
https://laravel.com/docs/5.2/responses#redirecting-with-flashed-session-data
If you are going to use ajax, as I mentioned in the comment above, you will need to make sure you use the error method within the ajax call:
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function (data) {
console.log('success', data)
},
error: function (data) {
console.log('error', data)
}
});
Hope this helps!

redirect not work properly in codeigniter

Halo, i'm using ajax to post form into controller codeigniter. I want to redirect after ajax post, but controller doesn't redirect.
This is my ajax
$.ajax({
type:"POST",
url:form.attr("action"),
data:form.serialize(),
success: function(){
},
error: function(){
alert("failure");
}
});
});
});
this is my controller
public function checkout_data(){
$this->account_model->checkout_simpan();
redirect('produk/payment/last_steps');
}
this is my form
<form class="form-horizontal col-md-offset-3" id="form-checkout" action="<?php echo base_url('produk/payment/checkout_data');?>">
What wrong with my code ?
You're doing it wrong.
What are you doing now:
when you send ajax-request to your server, method checkout_data is executed, and in it there's a redirect to another url. But it works on server. So, after redirecting to produk/payment/last_steps, method last_steps (or whatever is binded to this url) is executed and it's contents returned back to ajax-request.
What you need to do:
use javascript functions to redirect. Usually it's a document.location
E.g. document.location = "some/new/url".
So I suppose your checkout_data method should return some string. that contains url for redirect. For example:
public function checkout_data(){
$this->account_model->checkout_simpan();
echo 'produk/payment/last_steps';
}
And in success of ajax you can use:
success: function( data ) {
// console.log( data ) // uncomment to check what is received
document.location = data;
},
1 ) Check your path properly
2 )(important) Check Your Controller there is unwanted space in it remove all these

Form submission using ajax and page view moderation after the submission

At this moment I am using laravel. In this context I am having a form which is successfully submitted by using ajax to a controller. and that controller make it to the database. But the problem is as the ajax is doing its job the whole page remain unmoved / unchanged after the submission even the database is updated.
Now what I want
I want to give feedback to the user that your post is successfully submitted there. or what I want to do in further, I want to refresh the section in which the post is collected from the database as this post can be retrieved from there. But by using ajax only.
So there is no need to collect the whole page or refresh.
here is my form structure
`
{{ Form::open(array('route' => array('questions.store'), 'class' => 'form-horizontal' )) }}
blah blah blaaa .......
<script type="text/javascript">
$(".form-horizontal").submit(function(e){
$(this).unbind("submit")
$("#ask").attr("disabled", "disabled")
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
</script>
{{ Form::close() }}
`
As it is very much visible that the post is updated through a route & controller I want to have another dive and a success message at this script to be displayed after the success of posting. I am looking for some professional structure using what there is minimal need to have interaction with the server side and give user a better page viewing experience.
Thanks a lot for helping me in this research.
I am not sure if I understand you well, but if you want to notify the user about the result of an ajax-called db update you need to have
a route for the ajax save db call - it should point to a method that does the db update.
the db update method should return some value indicating the success/failure of update (for example OK or FAIL)
the only result of calling the method will be just plain text page with OK or FAIL as body
fetch the result by ajax and inform user accordingly (after form submit button)
check out the below code for ajax call itself (inside the form submit handler) to see what I mean
var db_ajax_handler = "URL_TO_YOUR_SITE_AND_ROUTE";
var $id = 1; //some id of post to update
var $content = "blablabla" //the cotent to update
$.ajax({
cache: false,
timeout: 10000,
type: 'POST',
tryCount : 0,
retryLimit : 3,
url: db_ajax_handler,
data: { content: $content, id: $id }, /* best to give a CSRF security token here as well */
beforeSend:function(){
},
success:function(data, textStatus, xhr){
if(data == "OK")
{
$('div.result').html('The new Question has been created');
}
else
{
$('div.result').html('Sorry, the new Question has not been created');
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
}
});
EDIT: as per comment, in step 2 (the method that is called with AJAX) replace
if($s)
{
return Redirect::route('questions.index') ->with('flash', 'The new Question has been created');
}
with
return ($s) ? Response::make("OK") : Response::make("FAIL");
EDIT 2:
To pass validation errors to the ajax-returned-results, you cannot use
return Response::make("FAIL")
->withInput()
->withErrors($s->errors());
as in your GIST. Instead you have to modify the suggested solution to work on JSON response instead of a plain text OK/FAIL. That way you can include the errors in the response and still benefit from the AJAX call (not having to refresh the page to retrieve the $errors from session). Check this post on the Laravel Forum for a working solution - you will get the idea and be able to fix your code.

PHP and JQuery Button trigger not working

Im currently new to PHP and JQuery after having using ASP.Net and C Sharp for the 2 years. I have this major problem in which i require some assistance in.
I have a HTML <input type="submit" id="btnWL" value="Add to Wishlist"> button. Basically when this button is pressed a table called 'wishlist' in the database is checked to see if the current product is already in a wishlist. If no the button will trigger a database save else it will return a JQuery alert pop up error message.
I having difficulty in passing 2 PHP variables: $_SESSION["username"] and $_GET["ProductId"] into this JQuery method:
<script type="text/javascript">
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php");
});
});
</script>
As you can see this JQuery method must pass those values to an external PHP File which checks for an already exsisting record in the 'wishist' table with those details.
<?php
$WishlistDAL = new WishlistDAL();
$result = $WishlistDAL->get_ProductInWishlistById($_GET["ProductId"]);
if (isset($_POST["isPostBack"])) {
if (isset($_SESSION["username"])) {
if (isset($_GET["btnWL"])) {
//Check if ProductId is in Cart
if (mssql_num_rows($result)>0)
{
//Return an error
//Sumhow this has to trigger an alert box in the above JQuery method
}
else
{
//Write in Wishlist Table
$WishlistDAL->insert_ProductInWishlist($_GET["ProductId"], $_SESSION["username"]);
}
}
}
else
{
//Return Error
}
}
?>
Another problem I have is then displaying an alert box using the same JQuery method for any errors that where generated in the php file.
Any Ideas how I can implement this logic? Thanks in advance.
Your "$.post()" call isn't passing any parameters, and has no callback for interpreting the results:
$.post('addToWishlist.php', { username: something, password: something }, function (response) {
});
The "something" and "something" would probably come from your input fields, so:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
});
Now the callback function would interpret the response from the server:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
if (response === "FAIL") {
alert("fail");
}
else {
// ... whatever ...
}
});
Exactly what that does depends on your server code; that "FAIL" response is something I just made up as an example of course.
jQuery accepts an callback:
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php", {'isPostBack':1}, function(res){
if (res.match(/err/i)){
alert(res);
}
});
});
});
Then, in the php, just (echo('Error adding record')) for this jquery to see there's an error string in the response and pop up the error message.
Other methods would be to use json, or http status codes and $.ajaxError(function(){ alert('error adding'); });.
from what i can tell so far is you'll only need to pass in the product id in and you can do this by appending your $.post call with the value; this will pass to your php script as a query string variable. i'm not sure which php script you posted, but if you're sending your data with jquery, it's using post and not get, so you may need to make an adjustment there and the session data should be available regardless, since it's the same session.
again this is without seeing all the code and since some of it isn't labeled, it's hard to determine. another thing, i like to use $.ajax for most actions like this, you have a lot more room to define and structure, as well as create one generic ajax function to call the methods and post data, as well as make a response callback. here's the documentation for you to look into $.ajax
i hope this helps.

Some ajax help?

I have a php script that takes some user form input and packs some files into a zip based on that input. The problem is that sometimes the server errors, so all the form data is lost. I was told I could use ajax instead so that the user never even has to change the page. I've never used ajax, and looking at http://api.jquery.com/jQuery.ajax/ without any experience in ajax is quite difficult.
The page says that you can accept returns from an ajax call. How do you set up returns in the PHP file for an ajax call? If the server errors with the ajax call, how will I know?
edit: Also, is there a way to send an ajax request with javascript and jquery as if it were a submitted form?
How do you set up returns in the PHP file
just echo it in ajax page that will return as response
Simple Tutorial
client.php
$.post('server.php',({parm:"1"}) function(data) {
$('.result').html(data);
});
server.php
<?php
echo $_POST['parm'];
?>
result will be 1
edit on OP comments
Is there a way to use ajax as if you were submitting a form
Yes, there is
You can use plugins like jQuery form
Using submit
If you using jquery validation plugin, you can use submit handler option
using sumit
$('#form').submit(function() {
//your ajax call
return false;
});
every ajax function has a function param to deal with server returns.and most of them has the param msg,that is the message from server.
server pages for example php pages you can just use echo something to return the infomation to the ajax funciton . below is an example
$.ajax({
url:yoururl,
type:post,
data:yourdata,
success:function(msg){
//here is the function dealing with infomation form server.
}
});
The easiest way to get information from PHP to JavaScript via AJAX is to encode any PHP data as JSON using json_encode().
Here's a brief example, assuming your server errors are catchable
<?php
try {
// process $_POST data
// zip files, etc
echo json_encode(array('status' => true));
} catch (Exception $e) {
$data = array(
'status' => false,
'message' => $e->getMessage()
);
echo json_encode($data);
}
Then, your jQuery code might look something like this
$('form').submit(function() {
var data = $(this).serialize();
$.ajax(this.action, {
data: data,
type: 'POST',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
if (!data.status) {
alert(data.message);
return;
}
// otherwise, everything worked ok
},
error: error(jqXHR, textStatus, errorThrown) {
// handle HTTP errors here
}
});
return false;
});

Categories