I want to show error, or to know why this code run in error:function()
Result is always run to error:function. I want to run success:function(data) and reload this page.
But console don't show anything about error.
https://imgur.com/ZubjYTc
https://imgur.com/mSfHnSR
====== Ajax ======
function ex_go(r_idx)
{
if(confirm("Are you sure?") == true)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'POST',
dataType: 'JSON',
url: "{{ route('change-centerYn') }}",
data:{r_idx:r_idx},
success:function(data){
alert(data.success);
location.reload();
},
error:function(xhr, data){
console.log(xhr);
},
}else{
return false;
}
}
====== Controller ======
public function ex_ok(Request $request)
{
if(request()->ajax())
{
$r_idx = 'Hello';
var_dump('<pre>', $r_idx);
return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
}
}
Since you aren't using Try & Catch or error handling your controller will return 200 HTTP header status code, which means ajax will always think that process is correct and noting went wrong, try using error handling in your controller function and raise an exception if something went wrong during your code process. you can read at this link
you can see a sample code modification to your existing code below:
public function ex_ok(Request $request)
{
try
{
if(request()->ajax())
{
$r_idx = 'Hello';
var_dump('<pre>', $r_idx);
return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
}
}
catch(\Exception $e)
{
\Log::error($e); // create a log for error occurrence at storage/log/laravel.log file
return response()->json($e->getData(), $e->getStatusCode());
}
}
It's suddenly working! Unbelievable!
Thank you very much! You saved my morning!
Use try catch
========= AJAX ===========
function ex_go(r_idx)
{
if(confirm("해당 결제건을 지원센터로 보내시겠습니까?") == true)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(r_idx);
$.ajax({
type:'POST',
dataType: 'JSON',
url: "{{ route('change-centerYn') }}",
data:{r_idx:r_idx},
success:function(data){
alert(data.success);
location.reload();
},
error:function(xhr, data){
console.log(xhr);
}
});
}else{
return false;
}
}
========= Laravel Controller =======
public function ex_ok(Request $request)
{
try
{
if(request()->ajax())
{
$r_idx = $request->r_idx;
$lecture = DB::table('class_order')
->select('*')
->where('r_idx', '=', $r_idx)
->first();
if ($lecture->r_oid != '') {
$insert_data = [
'r_oid' => $lecture->r_oid,
'r_user_id' => $lecture->r_user_id,
'r_name' => $lecture->r_name,
'r_tel' => $lecture->r_tel,
'r_hp' => $lecture->r_hp,
'r_email' => $lecture->r_email,
'r_zip' => $lecture->r_zip,
'r_addr1' => $lecture->r_addr1,
'r_addr2' => $lecture->r_addr2,
'r_class' => $lecture->r_class,
'r_enddate' => $lecture->r_enddate,
'app_endday' => $lecture->app_endday,
'whole_study' => $lecture->whole_study,
];
DB::table('ex_class_order')->insert($insert_data);
ClassOrder::where('r_idx', '=', $r_idx)->update(['centerYn' => 'y']);
$info_txt = "처리되었습니다.";
}
else
{
$info_txt = "처리실패";
}
return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
}
}
catch(\Exception $e)
{
\Log::error($e); // create a log for error occurrence at storage/log/laravel.log file
return response()->json($e->getData(), $e->getStatusCode());
}
}
Related
I'm using ajax to implement infinite scroll pagination in laravel but I cannot access the url while I can with the enter the url in the adress bar or via the default pagination page list.
I get GET http://localhost:8888/gest/items?page=2 500 (Internal Server Error)
Scripts
<script type="text/javascript">
var page = 1;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
page++;
loadMoreData(page);
}
});
function loadMoreData(page){
$.ajax(
{
url: '?page=' + page,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
if(data.html == " "){
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$(".row-items").append(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
And the controller
public function index(Request $request, $submenu = null){
$items = Item::paginate(5);
if ($request->ajax()) {
$view = view('data',compact('items'))->render();
return response()->json(['html'=>$view]);
}
return view('layouts.gest', compact('items'), ['submenu' => $submenu]);
}
EDIT
I also tested to add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The error was that laravel couldn't find the view data
I've currently got this:
$.ajax({
url: '/some/url',
dataType: 'json',
type: 'POST',
data: formData,
success: function(data) {
if (window.confirm('Thank you for your message. Can I erase the form?')) {
document.querySelector('.form-input').val('');
}
},
error: function(xhr, status, err) {
console.error(status, err.toString());
alert('There was some problem with sending your message.');
}
});
Instead of it going to a URL, how can I change it to send directly to a specific email address? I am using this contact form with a React app I've created.
So react component, class based.
class Foo extends Component {
popupQuestion() {
// implement method
}
sendEmail() = () => {
axios.post('/some/url', {
subject: 'mail',
to: 'someone#example.com',
body: 'something',
name: 'name'
})
.then(function (response) {
popupQuestion();
})
.catch(function (error) {
console.log(error);
return 'Error occurred. Please refresh page and try again.';
});
}
render() {
return(
<form onSubmit={this.sendEmail}>
// ...
</form>
);
}
}
And php method that will be executed on some/url
public function sendEmailAction(): bool
{
$request = // get request;
$subject = $request->get('subject');
$to = $request->get('to');
$body = $request->get('body');
$name = $request->get('name');
$transport = (new Swift_SmtpTransport('smtp.example.org', 25))
->setUsername('your username')
->setPassword('your password');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message($subject))
->setFrom(['mymail#exmaple.com' => 'me'])
->setTo([$to => $name])
->setBody($body);
$sent = $mailer->send($message);
return $sent ? true : false;
}
I am trying to do the following from my HTML:
var vm = new Vue({
el: '#loginContent',
data: {
main_message: 'Login',
isLoggedIn: false,
loginError: '',
loginButton:'Login'
},
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
});
Basically user presses the login button, onLogin method is called that sends a post to my API. The post is working fine and I do get the response back in the .then() promise.
But, trying to do things like this.isLoggedIn = true; does not update my DOM with what I am expecting the HTML to do when the user logs in.
Could be that I am in some sort of background thread (sorry, mobile developer here) when I get the response in the promise and it can't find the "vm" instance?
Thanks
It is probably happening because your this is not pointing to correct scope, scope of this changes inside an $.ajax call, so you just have to do something like following:
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
var that = this
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
that.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
that.isLoggedIn = true;
} else {
that.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
I would propose another method use ES6 Arrow Functions like '=>'. It is simple and do not need extra variable.Like following:
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then((response) => {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
You might want to take a look at axios. I used $.ajax and got it working, but found axios and prefer axios over the ajax library.
public function index($id)
{
$project = Project::findOrFail($id);
if(Request::ajax())
{
$html = View::make('Milestones.indexpartial', $project)->render();
return Response::json(array('html' => $html));
}
return View::make('milestones.index')->with('project', $project)
->with('title','Milestones');
}
$(".ajaxul a").click(function()
{
var url = $(this).attr('href');
$.ajax(
{
url: url,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajaxloading').show();
}
})
.done(function(data)
{
$('#ajaxloading').hide();
$(".refresh").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
Please help me make this work.
I'm new to AJAX and laravel.
my problem was this line here:
$html = View::make('Milestones.indexpartial', $project)->render();
it gives an error. then i changed it to
$html = View::make('Milestones.indexpartial',array('project' => $project))->render();
the request is a success but the html is empty.
Please help me. Thank you.
i have an ajax which I don't know if it is correct. I want to get the value from the controller and pass it to ajax.
ajax:
$.ajax({
type: "GET",
url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),
success: function(response) {
if (response != "Error")
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});
event.preventDefault();
and in the controller:
public function swoosh_delete_child()
{
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response = $this->emp->delete_children($id);
}
model
public function delete_chilren($id){
.......//codes here.. etc. etc.
if success //
return "success";
else
return "Error";
}
i just want to pass/get the value of $reponse and pass it to the ajax and check if the value is error or not..
Just echo in the controller:
$response = $this->emp->delete_children($id);
And alert the response:
alert(response); //output: success / Error
in your controller:
you should have something like this
public function swoosh_delete_child(){
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response['status'] = $this->emp->delete_children($id);
echo json_encode($response);
}
then in your ajax, to access the response
$.ajax({
type: 'POST',
url: url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),,
dataType: 'json',
success: function(response){
if (response.status)
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});