Dynamic / Changing variable in AJAX get Request - javascript

I have a page on a project I'm developing that is attempting to make an ajax request with a specific value assigned by the button's (there are multiple) id tag. This works; the value is successfully passed and an ajax call is triggered on every click.
When I try to make the call again to the same page with a different button the variables are reassigned however the GET request that is sent remains unchanged.
How do I pass a NEW variable (in this case id) passed into the GET request?
function someAJAX(target) {
var trigger = [target.attr('id')];
console.log[trigger];
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: target.attr("class"),
tableCall: true,
sort: trigger,
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}
$(document).ready(function () {
$(".sort").on( "click", function (e) {
//e.stopPropagation();
//e.preventDefault();
target = $(this);
//console.log(target.attr("class"));
console.log(target.attr("id"));
/* ADD CHILDREN TO ELEMENT*/
if (target.hasClass('asc')) {
target.removeClass('asc')
} else {
target.addClass('asc')
}
/* MANAGE CLASS ADD/REMOVE FOR TARGET AND SIBLINGS */
if (target.hasClass('btn-primary')) {
} else {
target.addClass('btn-primary')
}
someAJAX(target);
target.siblings().removeClass('btn-primary');
})
});

Try to call your ajax like this someAJAX.bind(target)();
Then in function become
function someAJAX() {
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: this.attr("class"),
tableCall: true,
sort: this.attr('id'),
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}

trigger doesn't seem to be defined anywhere. That's the only data that would be changing between your requests as the other ones are statically coded.
You just need to make sure trigger is defined and changes between the two requests.

Thanks for the input on this problem. I got down to the bottom of my problem. My requests were being handled correctly but dumping the tables was creating syntax errors preventing the appending of new information to my page.
Thanks for the quick replies!
It wall works now.

Related

TypeScript : Ajax call call always calling Error rather than success on success

In typescript I have a DataAccess Class so that all Ajax calls are routed through a single object to save repetition of code in a lot of places within my application.
In using this approach I have needed to use call backs to get the response back to the calling class so that the success and error can be handled accordingly.
This is the typescript
ajaxCall(retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
}
This is the compiled Javascript
AjaxDataAccessLayer.prototype.ajaxCall = function (retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
};
return AjaxDataAccessLayer;
This calls through to the ASP.Net MVC controllers perfectly fine, however the problem that I have is regardless of Success or Error the call back is always retError.
This is the calling Typescript
var _this = this;
var dataAccess = new DataAccess.AjaxDataAccessLayer(Fe.Upsm.Enums.AjaxCallType.Post,
Fe.Upsm.Enums.AjaxDataType.json,
"../../PrintQueue/DeletePrintQueueItems",
jsonObj);
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, xhr => {
// failure
alert("An Error Occurred. Failed to update Note");
});
When stepping through and looking at this the Status is OK and the response is 200.
So, Problem (as mentioned above) always calling xhr \ retError regardless of success.
Question: How do I get it to go into the right call back?
In your error handler, you were not passing all the parameters, so you are only checking whether the request finished successfully. However, there can be errors after that, like when the response is processed. You can handle errors betters like this:
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, (xhr, errorText, errorThrown => {
// failure
console.log(xhr, errorTest, errorThrown);
alert("An Error Occurred. Failed to update Note");
});
Based on the discoveries using this method, the error is that your controllers are returning empty responses, so you're getting an exception when jQuery tries to parse them, because an empty string is not valid JSON.

Update a p element from a nodejs function

I need to send a value from a input form to a nodejs server, which triggers a calculation with this value and needs to update an p element with the result of the calculation on the client side.
How can this be done?
This is what i have:
//Server side:
app.post('/calculate/:id', function(req, res){
var title = 'Tax Calculation';
var tax= taxcalculation(req.params.id);
res.render('index', {
title: title,
tax: tax,
});
});
//Client side:
var income= document.getElementById("income");
var tax = document.getElementById("tax")
$(income).on('change', function() {
console.log("changed");
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function() {
$('#tax').html('<%= tax %>');
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
});
Okay, so you don't give a lot of data, but this sounds as simple as sending a response with the results to the client side in your Node web service that does the calculations and append the result to the P element
Your server code to handle the ajax call should output a json response which will contain the content for the <p>. It should not re-render the whole index page. I don't do a lot of node.js so I'll leave that for you to figure out.
The ajax success function should accept a response as a parameter, and then operate on that response.
Assuming the server response to this ajax request is of the format {"tax": 15.99}:
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function(response) {
if (response.tax || response.tax === 0) {
$('#tax').html(response.tax);
}
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});

Upload file using Jquery form plugin

I am using Jquery form plugin to upload file in Ajax request.File is successfully sent to server but on response browser is asking to save response with following popup
Here is my HTML
<form:form name="newRequestForm" id="newRequestForm" modelAttribute="requestForm" method="POST">
<form:input path="mrnFile" type="file" size="40"/>
</form:form>
JS
// Initializing Jquery form
$(function() {
$('#newRequestForm').ajaxForm();
});
// This function is called on click event of submit button
function submitDataRequest(formAction) {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
url: formAction,
dataType: 'json'
};
$('#newRequestForm').ajaxSubmit(options);
}
function showRequest(formData, jqForm, options) {
alert('About to submit: ');
return true;
}
function showResponse(data, statusText, xhr, $form) {
Alert("In response..")
if (!data.actionPassed) {
showErrors(data.errors);
$("#hideOrShowErrors").show();
} else {
showConfirmation(data, confirmationMsg, formName, successFormAction);
}
}
showResponse is never invoked instead browser shows the popup.
I checked through Firebug, the response code is 200 still success callback is not executed.
After reading some similar question I think it has something to do with server response type. So I did following in my spring controller
public ResponseEntity<ResponseDTO> save(#ModelAttribute("dataRequestForm") DataRequestFormDTO dataRequestFormDTO, BindingResult result, SessionStatus status, Model model, HttpServletResponse response) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<ResponseDTO>(responseDTO, responseHeaders, HttpStatus.CREATED);
}
On both side I have data type as json but still I am getting the popup.Am I making any blunder?
Thanks!
EDIT:
Updated JS
function submitDataRequest(formAction) {
var options = {
beforeSubmit: function(){
alert("Before submit");
}, // pre-submit callback
success: function(){
alert("On success");
}, // post-submit callback
url: formAction
}
$('#newRequestForm').ajaxSubmit(options);
}
Still I get the same popup and success callback is not fired.
Added initBinder in controller
#InitBinder
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws ServletException {
binder.registerCustomEditor(CommonsMultipartFile.class,
new ByteArrayMultipartFileEditor());
}
After adding initBinder I got following error
No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer
This is a common issue with IE and iframe (used by jquery form plugin to upload files with ajax).
I solved in two steps:
1) Server Side: remove headers, send back just the content.
2) Client-Side: do not set the ajax request dataType parameter and on success use the following code to extract json:
success: function(data)
{
try{
jsonData = jQuery.parseJSON(data);
// continue process with json encoded data
}
catch(e)
{
// handle parsing error
}
}

Trapping Function not defined error in Javascript and jQuery

Okay, I do use firebug to determine when a function is not defined in Dev. What I would like to do in production is show a modal window saying an error has been received which would then redirect them to another page upon click. Not so easy.
Please understand that this function does work and the component that is called works. I am going to misspell the function call on purpose to demonstrate the error I am not receiving thru the jquery ajax function.
I am using .ajaxSetup to set up the default options for several ajax functions that will be running asynch:
$.ajaxSetup({
type: "POST",
dataType: "json",
url: "DMF.cfc",
data: {
qID: 1,
returnFormat: "json"
},
beforeSend: function() {
$('#loadingmessage').fadeIn(); // show the loading message.
},
complete: function() {
$('#loadingmessage').fadeOut(); // show the loading message.
}
}); //end AjaxSetup
The actual ajax call is:
$.ajax({
data: {
method: 'getCurrentIssues'
},
success: function(response) {
nsNewDebtshowDebtIssues(response);
},//end success function
error: function(jqXHR, exception) {
alert("Error running nsNewDebt.showDebtIssues");
}
}) //end getCurrentIssues Ajax Call
The error I forced is that the method run in the success function should actually be nsNewDebt.showDebtIssues. Firebug correctly displays in console the error nsNewDebtshowDebtIssues is not defined but the actual error message for the ajax call does not run, so if an enduser was running the page it would appear the page was hung.
So, In summary I want to know how to track when such an error occurs, preferrable to place in the error section of the .ajaxSsetup but if neccessary in each .ajax call.
It is not an ajax error, so you cannot handle it from the ajaxError method.
You should do a try/catch in the success method.
success: function(response) {
try {
nsNewDebtshowDebtIssues(response);
} catch (ex) {
//exception occured
//alert("Error running nsNewDebt.showDebtIssues");
alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
}
}
Before making the call, you can do:
if(typeof nsNewDebtshowDebtIssues == 'function') {
// .. call it ..
}
Well, the error actually occurs after the AJAX call has succeeded (since it comes from your success handler), so the error handler indeed won't be called.
If you want to use the same handler for actual AJAX request errors and for further errors originating from your success handler, you can define a named function and use it both as your error handler and from a try/catch block in your success handler:
function handleError(jqXHR, status, exception)
{
alert("Error running request.");
// Or print something from 'jqXHR', 'status' and 'exception'...
}
$.ajax({
data: {
method: "getCurrentIssues"
},
success: function(response, status, jqXHR) {
try {
nsNewDebtshowDebtIssues(response);
} catch (x) {
handleError(jqXHR, status, x);
}
},
error: handleError
});

ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with asp.net mvc, which returns pure json data. On my client, I'm using backbone.js to communicate to it.
My question is, how do I capture the message in javascript? For eg. What if a user has no permission to delete or there was no item matching the id? I've been told to throw http errors instead of custom json.
So my code would be:
[HttpDelete]
public ActionResult Index(int id)
{
if (id == 1)
{
throw new HttpException(404, "No user with that ID");
}
else if (id == 2)
{
throw new HttpException(401, "You have no authorization to delete this user");
}
return Json(true);
}
How do I access the message in my javascript callback? The callback would look like:
function (model, response) {
alert("failed");
//response.responseText would contain the html you would see for asp.net
}
I do not see message i threw in the exception anywhere at all in the data that was returned from the server.
You should use the error callback on the client. The success callback is triggered only when the request succeeds:
$.ajax({
url: '/home/index',
type: 'DELETE',
data: { id: 1 },
success: function (result) {
alert('success'); // result will always be true here
},
error: function (jqXHR, textStatus, errorThrown) {
var statusCode = jqXHR.status; // will equal to 404
alert(statusCode);
}
});
Now there is a caveat with 401 status code. When you throw 401 HTTP exception from the server, the forms authentication module intercepts it and automatically renders the LogIn page and replaces the 401 status code with 200. So the error handler will not be executed for this particular status code.
I just answered this in my question What is the point of HttpException in ASP.NET MVC, but you can actually get that string if you use the HttpStatusCodeResult like this:
In your controller:
return new HttpStatusCodeResult(500,"Something bad happened")
And you can access "Something bad happened" using, say, jQuery $.ajax() like this:
$.ajax: {
url: "#Url.Action("RequestsAdminAjax", "Admin")",
type: "POST",
data: function(data) { return JSON.stringify(data); },
contentType: "application/json; charset=utf-8",
error: function (xhr, textStatus,errorThrown) {
debugger;
toggleAlert('<strong>Error: </strong>Unable to load data.', 'alert alert-danger');
}
},
and errorThrown will contain "Something bad happened".
HTH.

Categories

Resources