Ajax call not returning a response, just reloads page - ajax

I have a Symfony 3 CRM and I use ajax calls to action the removal of items throughout the system. It uses a single call and then uses a switch statement to determine what it is the user is attempting to delete and handles it accordingly.
However, for some strange reason one particular type of item doesn't seem to work, it just reloads the page.
Here is the trigger button (I am implementing bootstrap confirmation):
<a href="" data-type="unit" id="{{ unit.id }}"
data-toggle="confirmation-singleton"
data-btn-ok-class="btn btn-xs btn-success"
data-btn-cancel-class="btn btn-xs btn-danger"
class="btn btn-xs btn-danger remove-item">
<i class="fa fa-remove no-override"> </i>
</a>
My ajax call for removal of items:
$('.remove-item').confirmation({
rootSelector: '[data-toggle=confirmation-singleton]',
container: 'body',
onConfirm: function() {
var type = $(this).attr('data-type');
var id = $(this).attr('id');
var data = type + '|' + id;
$.ajax( '/app_dev.php/ajax-call/remove-item/' + data )
.done( function(response) {
if(response != 'success') {
if(response == 'units_exist') {
alert("You cannot delete this item as there are units already linked to it.");
} else if(response == 'no_property') {
alert("Sorry! Property could not be found.");
} else if(response == 'bookings_exist') {
alert("Sorry! This unit has bookings. Please delete the bookings first.");
}
}
});
return false;
},
onCancel: function() {
return false;
}
});
And on the PHP side, for this particular example:
$data = $request->get('data');
$parts = explode("|",$data);
$type = $parts[0];
$id = $parts[1];
// using switch on $type
case 'unit':
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('AppBundle:Unit');
$booking_repo = $em->getRepository('AppBundle:Booking');
$bookings = $booking_repo->findBy(array('unitId' => $id)); // check to see if any bookings exist
if(!empty($bookings)) {
return new Response('bookings_exist');
} else {
$item = $repo->findOneBy(array('id' => $id));
if(!empty($item)) {
$em->remove($item);
$em->flush();
}
}
break;
In this example, it SHOULD return 'bookings_exist' and if I directly go to the URL in the browser, it does display this message - however, all it does it reload the page instead of throwing the alert as stipulated in the ajax call. I know this call works as it does successfully delete other items in the CRM, it just seems to be when it cannot delete it due to a condition such as this.
I may be missing something really obvious here, so any help is appreciated.

For jQuery Ajax, use success and error handlers
Other handlers in jQuery's Ajax object are unreliable at best, and vary in their behavior and support between versions and browsers.
Prevent Default is generally a good idea with ajax handled events
Should jQuery fail, and NOT return false, the element will do it's default behavior, which in your case is which reloads the page.
onConfirm: function(e) {
e.preventDefault();
var type = $(this).attr('data-type');
var id = $(this).attr('id');
var data = type + '|' + id;
$.ajax( '/app_dev.php/ajax-call/remove-item/' + data )
.success( function(response) {
if (response.errorMessage) {
alert(response.errorMessage);
}
})
.error( function(xhr, status, error) {
console.log(status + '\n' + error);
})
;
return false;
}
PHP Side, build a JSONResponse
if(!empty($bookings)) {
return new JsonResponse([
'errorMessage' => 'Sorry! Property could not be found.'
);
}

instead of just adding .done() you should also use
.fail(function( jqXHR, textStatus, errorThrown ) {});
to catch any errors.

If the bookings is not empty then the function will return the new response 'booking_exist' and stop ... it will not proceed to next statments .
So if you need to delete the item use this code instead :
if(empty($bookings)) {
return new Response('bookings_not_exist');
} else {
$item = $repo->findOneBy(array('id' => $id));
if(!empty($item)) {
$em->remove($item);
$em->flush();
}

Related

I am not sure if my Vue code is efficient

I am a beginner in Vue and I am wondering if I can get an insight from experienced developers here about my Vue codes. I just want to ask for help to know if my Vue approach is efficient and proper. (Project is running on Laravel)
The Case:
Let us say I have 2 tables in DB
(1) stores
(2) ad_accounts
Then we have 2 web pages to present these tables' data and execute CRUD functions with it
(1) store.blade.php
(2) adaccount.blade.php
Each page is running a Vue component
(1) Stores.vue
(2) AdAccounts.vue
I am using Vuex for store management.
Within store.js, I would have set of actions for CRUD for each vue component.
Now I realized that I have series of actions that actually does the same thing. For example, I have an action to add stores, and another action to add Ad accounts. Their only difference is that they are calling a different Laravel route.
So it seemed to me that my code was unnecessarily long and a bit expensive. To resolve, I decided to write my actions in a form of template. So this is what I did:
In store.js, I created an action for each CRUD function to be used as template
In Stores.vue and AdAccounts.vue, if I need to execute a CRUD function, I would use a method to call the corresponding action from store.js and provide the Laravel route as part of the action's payload
I have states and corresponding getters for returning these states in Stores.vue and AdAccounts.vue
Each action has a dedicated mutation that alters the approriate state
states and getters are mapped in each Vue component in order to access and use them
Is this approach efficient and proper? I have sample methods and actions below for reference.
Stores.vue
<template>
<div>
<form #submit.prevent="addData('stores/add')">
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</template>
<script>
export default {
methods: {
addData: function(url) {
this.payload.url = url
if(
this.payload.requestData.store_name == "" &&
this.payload.requestData.store_token == ""
) {
this.payload.isErr = true;
this.payload.errMsg = "ERROR: Could not continue due to some invalid or missing data. \nPlease check your entries and try again or contact your administrator.";
this.$store.dispatch('addData', this.payload)
}
else {
this.payload.isErr = false;
this.$store.dispatch('addData', this.payload)
this.readDataAll('stores/all', 'store');
}
this.cleanOnModalDismiss(this.$refs.addModal, this.refreshRequestData)
}
}
}
</script>
AdAccounts.vue
<template>
<div>
<form #submit.prevent="addData('ad_accounts/add')">
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</template>
<script>
export default {
methods: {
addData: function(url) {
this.payload.url = url
if(
this.payload.requestData.ad_id == "" &&
this.payload.requestData.ad_name == ""
) {
this.payload.isErr = true;
this.payload.errMsg = "ERROR: Could not continue due to some invalid or missing data. \nPlease check your entries and try again or contact your administrator.";
this.$store.dispatch('addData', this.payload)
}
else {
this.payload.isErr = false;
this.$store.dispatch('addData', this.payload)
this.readDataAll('ad_accounts/all', 'adaccounts');
}
this.cleanOnModalDismiss(this.$refs.addModal, this.refreshRequestData)
}
}
}
</script>
store.js
export default new Vuex.Store({
actions: {
addData (commit, payload) { // insert a record to DB
try {
if(payload.isErr == true) {
commit('SHOW_ERRORS', {messageType: "alert-danger", errorMessage: payload.errMsg});
} else {
axios.post(payload.url, payload.requestData)
.then(response=>{
if(response.status == 200) {
var err_msg = "";
if(response.data.success !== null) {
response.data.messageType = "alert-info"
response.data.actionMessage = response.data.success
commit('ADD_DATA', response.data);
} else {
response.data.messageType = "alert-danger"
for(var i=0; i<response.data.error.length; i++) {
err_msg += response.data.error[i] + "\n"
}
response.data.actionMessage = err_msg
commit('ADD_DATA', response.data);
}
}
else {
commit('SHOW_ERRORS', {messageType: "alert-danger", errorMessage: "ERROR: Connection status set to '" + response.headers.connection + "' due to error " + response.status + " " + response.statusText + ". \nPlease contact your administrator."});
}
})
}
} catch (error) {
commit('SHOW_ERRORS', {messageType: "alert-danger", errorMessage: error})
}
}
}
}

Can I use fetch api in jquery-datatables?

I understand that you can use ajax to populate the datatable. But can you use fetch?
Because I have this normal table, filled dynamically using fetch api.
$(document).ready(function(){
fillTable();
})
//fetch api (AJAX) to fill table
fillTable = () => {
fetch('http://localhost:3000/home.json')
.then(response => response.json())
.then(data => {
let html = '';
for (i = 0; i < data.length; i++){
html += '<tr>'+
'<td class="tdUsername pv3 w-35 pr3 bb b--black-20">'+ data[i].username + '</td>'+
'<td class="tdPassword pv3 w-35 pr3 bb b--black-20">'+ data[i].password + '</td>'+
'<td class="pv3 w-30 pr3 bb b--black-20">'+
'<div class="btn-group" role="group" aria-label="Basic example">'+
'<a class="editButton f6 grow no-underline ba bw1 ph3 pv2 mb2 dib black pointer" data-toggle="modal">EDIT</a>'+
'<a class="deleteButton f6 grow no-underline ba bw1 ph3 pv2 mb2 dib black pointer" data-toggle="modal">DELETE</a>'+
'</div>'+
'</td>'+
'</tr>'
}
$('#tblBody').html(html);
})
.catch(err => console.log("ERROR!: ", err))
}
So I am wondering if I can use fetch-api instead of using this to fill the datatable.
//syntax copied from the website
$('#myTable').DataTable( {
ajax: '/api/myData'
} );
It is possible to use 'ajax' option as a function, see https://datatables.net/reference/option/ajax#function
As a function, making the Ajax call is left up to yourself allowing complete control of the Ajax request. Indeed, if desired, a method other than Ajax could be used to obtain the required data, such as Web storage or a Firebase database.
When the data has been obtained from the data source, the second parameter (callback here) should be called with a single parameter passed in - the data to use to draw the table.
Example:
$('#example').dataTable( {
"ajax": function (data, callback, settings) {
callback(
JSON.parse( localStorage.getItem('dataTablesData') )
);
}
});
I was looking for this answer myself as I am trying to stay away from jquery as much as possible, but was unable to find an answer anywhere. I ultimately figured it out on my own and the implementation is not very different than using DataTable's suggested jquery ajax call.
var myTable = $('#myTable').DataTable({
ajax: async function (data, callback, settings) {
let response = await fetch("/api/v1/some/end/point", {headers: {Authorization: 'Bearer ' + sessionStorage.getItem("token")}});
if (response.ok) {
let msg = await response.json();
sessionStorage.setItem('token', msg.token);
console.table(msg.data);
delete msg['token'];
callback(msg);
} else {
console.log(response);
}
},
...... followed by the usual DataTable options
if someone is looking for an answer.
Yes, you can use fetch to populate datatable, here is an example.
fetchEndPointData(dc)
.then(aggregatedData => {
$('#table1').dataTable().api().rows.add(aggregatedData);
}).catch(error => {
// When fetch ends with a bad HTTP status, e.g. 404
console.log(error.message);
});
invoked method
async function fetchEndPointData(dc) {
const response = await fetch('/someEndPoint=' + dc);
const movies = await response.json();
return movies;
}
Note : the fetchEndPointData is returning a promise.
reference : https://dmitripavlutin.com/javascript-fetch-async-await/

submit form if don't have error

i am using ajax for send active form by this function
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() { $.ajax({url: '".$url."',type: 'POST',success : function(res){ $('#".$dviId."').html(res);}});});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}
And want to show error if any happened else send form
There is a plugin in jquery to do client side validation if you are using javascript and want to do initial validation of the form.
http://jqueryvalidation.org/
Also you can use "required" attribute in your text tags to do some intial checks. More can be found here:
http://www.w3schools.com/tags/att_input_required.asp
Hope this helps a bit.
You can also set enableAjaxValidation to true in your form.
There is an example in the docs about that (see the controller part).
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
if(isset($this->params['confirm'])) {
$confirm = "if(confirm('".$this->params['confirm']."')){";
$endConfirm = "}";
}
else
{
$confirm = "";
$endConfirm = "";
}
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() {".$confirm."$.ajax({url: '".$url."',type: 'POST',beforeSend: function(){ $('body').addClass('wait');},complete: function(){ $('body').removeClass('wait');},success : function(res){ $('#".$dviId."').html(res);}});".$endConfirm."});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}

angularjs make serial actions by condition

i'd like to do user friendly action at my app.
The issue is:
I have one button. When user 'mousedown' on it, i send ajax query to server to get some info. What i want is to show that info only after user 'mouseup' on this button. In other words, when he releases mouse button.
The problem is that user can release mouse button before or after server answers to my ajax call, by i still want to show info only after release button.
I think i can do this with deferred stuff, by i don't have a lot experience in this. Can you give me some info, how to do this?
Example code:
.html
<input type='button' ng-start='start()' ng-end='end()' >
.js
$scope.start = function(){
$http.get(url, data).success(function(result){})
}
$scope.end = function(){
//show result from first function
}
Tried to do it with use of $q, but it appears that $q is not necessary.
.html
<input type='button' ng-mousedown='start()' ng-mouseup='end()' >
<div ng-show="loaded && resolved" ng-bind="processedResult"></div>
.js
$scope.start = function(){
$scope.resolved = false;
$scope.loaded = false;
$http.get(url, data).success(function(result){
$scope.loaded = true;
$scope.processedResult = processResult(result);
});
};
$scope.end = function(){
$scope.resolved = true;
};
I think, i've solved my problem with pretty promise feature.
.html
<input type='button' ng-start='start()' ng-end='end()' >
.js
$scope.start = function() {
promise = $q.when($scope.ApiCall())
.then(function(result){
return result.data;
}, function(error){
console.log(error);
})
;
};
$scope.end = function() {
promise.then(function(result){
processResult(result.datat);
});
};
$scope.ApiCall = function(){
var data = {};
return $http.get(url, {params: data});
}

AJAX Form will only either show success message OR post data to database not both

I am using Codeigniter as my framework and have a simple contact form. This uses the form helper and i have used AJAX and a fallback in the controller if AJAX is not present.
At the moment, my code with only either show the success message from the ajax form OR post the data to the database depending on if i change them around in the controller - my error messages work fine.
I am confused to how it will not both post and show success message - i think i may be missing something in my controller or AJAX request?
Here is my code as a guidance and if anyone can spot anything that would be great as it's getting on my nerves now!
*The code i am posting now lets the data be posted into the database. When i move the post data elements below this -> return $this->output->set_output(json_encode($respond)); It doesn't post to the database but shows the success message and vice versa.
CONTROLLER,
// if ajax request
if($this->input->is_ajax_request()) {
$respond = array();
if($this->form_validation->run() == FALSE) {
$respond['result'] = 'false';
$respond['error_message'] = $error_message;
$respond['errors'] = validation_errors();
// set individual errors - for warning classes
$respond['first_name_error'] = form_error('first_name');
$respond['country_error'] = form_error('country');
$respond['email_error'] = form_error('email');
$respond['message_error'] = form_error('message');
} else {
$respond['result'] = 'true';
$respond['success_message'] = $success_message;
// add contact message to the database
$this->contact_model->insert_contact_message($curr_lang, $this->input->post('first_name'), $this->input->post('country'), $this->input->post('email'), $this->input->post('phone'), $this->input->post('message'));
}
return $this->output->set_output(json_encode($respond));
} else {
// if ajax request failed - use CI
if($this->form_validation->run() == FALSE) {
$data['error_message'] = $error_message;
$data['errors'] = validation_errors();
} else {
// add contact message to the database
$this->contact_model->insert_contact_message($curr_lang, $this->input->post('first_name'), $this->input->post('country'), $this->input->post('email'), $this->input->post('phone'), $this->input->post('message'));
$data['success_message'] = $success_message;
}
}
// set field labels
$data['first_name'] = $first_name;
$data['country'] = $country;
$data['email'] = $email;
$data['phone'] = $phone;
$data['message'] = $message;
// initialize view name
$data['content'] = $page;
// load the view
$this->load->view('template', $data);
}
AJAX
$('#submit').click(function(e) {
e.preventDefault();
// send the form data to the controller
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: $('form').serialize(),
dataType: 'json',
success: function(respond) {
if(respond.result === 'false'){
// function to add warning class
function add_error(response, field){
if(response){
$(field).addClass('warning');
}
}
// add warning classes - doing this individually as some inputs have more than one error message
add_error(respond.first_name_error, 'input[name="first_name"]');
add_error(respond.country_error, 'input[name="country"]');
add_error(respond.email_error, 'input[name="email"]');
add_error(respond.message_error, 'textarea');
// post all errors to the view
var error_msg = respond.error_message + respond.errors;
$('#error_message').html(error_msg);
}
if(respond.result === 'true'){
// empty the form
$('#error_message').empty();
$('form').find("input[type=text], textarea").val('');
// set the success message
var success_msg = respond.success_message;
$('#success_message').html(success_msg).fadeOut(6000);
}
}
});
return false;
});
It's likely because you aren't parsing the JSON response so your if statements will never be true (as respond.result is probably evaluating to 'undefined').
In your Ajax respond.result === true or false not 'true' or 'false'. You just need to remove the quotes because it is a Boolean not a string.

Resources