How to check ajax's response from laravel's controller is empty? - javascript

I work on laravel project with ajax. Below is my controller.
public function Student(Request $request){
$student = Student::where('school_uuid',$request->school_uuid)
->where('cardid',$request->cardid)
->first();
return response()->json($student);
}
And this is my ajax.
$.ajax({
url:"{{ route('api.student') }}",
method:"POST",
data:{
cardid:cardid,
school_uuid:"{{$shareuser->school_uuid}}",
},
success:function(response){
if (typeof response.name !== 'undefined'){
console.log(response.name);
}else{
console.log("no data");
}
}
});
I can check the empty response by using typeof response.name !== 'undefined' and it work fine. But I'm not sure that is the best way or not. Any advice or guidance on this would be greatly appreciated, Thanks

You should send the correct response code if the student isn't found, and then handle that in the javascript.
For example:
public function Student(Request $request){
$student = Student::where('school_uuid',$request->school_uuid)
->where('cardid',$request->cardid)
->firstOrFail(); // This will cause a 404 if the student does not exist
return response()->json($student);
}
And then in your JS:
$.ajax({
url:"{{ route('api.student') }}",
method:"POST",
data:{
cardid:cardid,
school_uuid:"{{$shareuser->school_uuid}}",
},
success:function(response){
console.log(response.name);
},
error: function(xhr) {
if (xhr.status === 404) {
// Handle 404 error
}
// Handle any other error
}
});

Related

ajax can't going into success method

here is controller:
#ResponseBody
#PostMapping("/signup")
public String signUp(HttpServletRequest request) {
try {
log.info("-------signup page");
String username = request.getParameter(Constant.PARAMETER_USERNAME);
if (userDetailService.findByUsername(username)!=null) {
log.error("----------username is exist!!");
return Constant.MESS_EXIST_USER;
}
log.info("----------username is not exist!!");
User user = new User();
user.setUsername(username);
user.setPassword(passwordEncoder.encode(request.getParameter(Constant.PARAMETER_PASSWORD)));
user.setEmail(request.getParameter(Constant.PARAMETER_EMAIL));
user.setPhonenumber(request.getParameter(Constant.PARAMETER_PHONE)) ;
user.setAddress(request.getParameter(Constant.PARAMETER_ADDRESS));
user.setFullname(request.getParameter(Constant.PARAMETER_FULLNAME));
String status = userService.save(user);
log.info(status );
return status;// return "success" or "fail"
}
}catch (Exception e) {
log.error("sign up has been error: ",e);
return Constant.MESS_FAIL; // "fail"
}
}
and js:
var data = $('form#form1').serialize();
$.ajax({
url: '/signup',
data: data,
type: "POST",
datatype : "text",
success: function(data){
console.log(data);
if(data == "success"){
alert("signup success!");
window.location.href = "/index";
}else if(data=="existUser"){
alert("username is exist!");
window.location.href = "/index";
}
else if(data=="fail"){
alert("signup fail!");
window.location.href = "/index";
}
}
});
}
log of save(user) is success but ajax not alert("signup success!"), it show error page. When I debug in js and java, ajax worked and show alert("signup success!"). I try search in google but it can't run. Anyone help me :(
EDIT
I try use datatype = 'text' and not dublicate save(user). When I run it then seem it not going into success function but when i debug in js then my program is running normally :(

How can I display alert only once in javascript?

My case like this :
if(window.location.pathname == '/shop/payment/checkout' || window.location.pathname == '/shop/detail' || window.location.pathname == '/shop') {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}
If the url accessed meets the condition of if then it will delete session by ajax and redirect to the url /shop
My problem is if redirect to url /shop, it will check again and display alert message again. So on and on
I want if the alert message appears and reload to the url /shop, it does not check anymore and displays the alert message
How can I do it?
EDIT:
After the answer given, I wrapped my code like this:
if (localStorage.getItem("cartCache") !== null) {
...
}
else {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}
}
It does not work as intended.
Before removing, you could first check if the local storage data is still there. Put this before the alert:
if (localStorage.getItem("cartCache") === null) return;
... assuming this code is within a function. But you get the idea. Or you can combine it with the if you already have (a bit improved):
if(['/shop/payment/checkout', '/shop/detail', '/shop'].includes(window.location.pathname)
&& localStorage.getItem("cartCache") !== null) {
// ...etc.

Delete a file with ajax request

I'm trying to delete a file with ajax request:
javascript:
function deleteFile(file_path)
{
var r = confirm("Sure?")
if(r == true)
{
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
method: 'GET',
success: function (response) {
alert('Deleted!');
},
error: function () {
alert('Not Deleted!');
}
});
}
}
delete_file.php :
unlink($_GET['file']);
It returns true on succes,but the file is not deleted.
Check the response in AJAX, Best is use JSON DATA to check the response:
// Default AJAX request type is GET so no need to define
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
dataType: 'json',
success: function (response) {
if( response.status === true ) {
alert('File Deleted!');
}
else alert('Something Went Wrong!');
}
});
Do It like this in PHP:
// First Check if file exists
$response = array('status'=>false);
if( file_exists('FILE_PATH/FILENAME') ) {
unlink('FILE_PATH/FILENAME');
$response['status'] = true;
}
// Send JSON Data to AJAX Request
echo json_encode($response);
Make sure you are giving the complete path with filename to unlink() function
Try this you need to check file, give permission, then delete it
$filename = 'full absolute file path';
if(file_exists($filename)) {
#chmod($filename, 0777);
#unlink($filename);
return true;
}
As there can be two issues either the file path is not correct or the file is not having permission.
With the above code both will be checked.

No response status in ajax call not sure why

I have the following ajax call which is made to my spring mvc app..
alert("ready");
$.ajax({
type: "GET",
url: document.location.toString()+ "/dashboard",
success: function(response) {
alert(response);
alert(response.status);
$("#frameBody").contents().find("html").html(response);
// we have the response
if(response.status == "SUCCESS") {
alert(response);
// do nothing..
// check for no content... if there is content... replace iframe
// $("#frameBody").attr('src', jsonObj.url);
// $(""#frameBody").contents().find("html").html(response);
}
else {
// do nothing yet
}
},
error: function(e){
$("#errors").attr("style", "display:inline")
$('#errors').html(e.responseText);
window.setTimeout("fadeErrorsDiv();", 5000);
}
});
my mvc controller:
#RequestMapping(value = "/dashboard", method = RequestMethod.GET)
#ResponseStatus(value=HttpStatus.OK)
public String dashboard(Model model, HttpServletRequest req) {
int i = 0;
return "login";
}
My question is that i cant see why this is not producing the response status that i expect?... it gives me undefined when i check for response.status in javascript?.. any idea why
See JQuery .get docs. It would seem your "response" object inside your success callback will actually be "login". Therefore you're infact trying to do "login".status.

Fetch http status code in jquery

Below is an existing jquery code in our code base.
$("#download_").click( function() {
$("#error").html('');
$.ajax({
type : "GET",
cache : false,
async : false,
url : "/download",
success : function(data) {
var json_obj = $.parseJSON(data);
if(json_obj !== undefined && json_obj != null){
if(json_obj.download=="success"){
location=json_obj.url;
}
}
},
error : function(data) {
// TODO
$("#error").html(failed);
}
});
});
Here, In case of error (marked as TODO), I want to check if the http status is 404, then I need to redirect user to different url.
Can any one tell me how do I get the http status in this error: function(data) method?
Thanks!
Did you even look at the docs?
$.ajax({
...
statusCode: {
404: function() {
alert('page not found');
}
}
});
try: statusCode
from documentation:
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
http://api.jquery.com/jQuery.ajax/
EDIT:
Now that I think about it, do you only want to redirect if it's a 404? What about other error codes?

Categories

Resources