'[]' appended to the end of my post request parameter in javascript - javascript

I am trying to make post request with the following parameters:
const postParams = { 'submission': submission };
However, when the request is actually sent, I observe that submission becomes submission[] in the browser's network tab. This is problematic because my server expects submission and not submission[]. Check the image below for more information.
[Note that the [] was appended to submission][1]
[1]: https://i.stack.imgur.com/pXpNq.png
Note that submission (the variable) is an array of integers, so while it makes sense why the [] is attached, is there a way to get rid of that?
Below is the full function.
const postParams = { submission: str_sub };
console.log(postParams)
$.post(root+'/problems/multiple_choice/'+problem_pk+'/run',
postParams,
function(data) {
// Omitted / not relevant
})
.fail(function(jqXHR, textStatus, errorThrown) { console.log(textStatus); });

This is jQuery's default behaviour where it follows PHP (instead of traditional) conventions.
See the documentation.
Use .ajax instead of .post and include traditional: true in the options object.
$.ajax(
root+'/problems/multiple_choice/'+problem_pk+'/run',
{
data: postParams,
traditional: true,
success: (data) => { ... }
}(

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.

Dynamic / Changing variable in AJAX get Request

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.

how to handle ajax parsererror nicely?

I have a google ad project which requires me to get multiple "setTargeting('', '');" from an object array on json file (via url) --> {"country": "Netherlands", "city": "Amsterdam" }. So far everything works; however, suppose the network fails, or requested JSON parse failed, etc - I'd like to pass an empty array to make sure that the slot will still show ads with no targeting.
What would be a good practise for it?
Advertisements.cachedCategoriesByUrl = {};
Advertisements.getCategories = function(categoriesUrl) {
var cachedCategories = Advertisements.cachedCategoriesByUrl[categoriesUrl];
if(cachedCategories){
return cachedCategories;
} else {
var getCategories = $.ajax({
url: categoriesUrl,
data: { format: 'json' },
error: function(jqXHR, status, thrownError) {
=> I'd like to pass an empty array so the slot will show
ads with no targetting set.
However this doesn't seem to be working.
Do I need to do callback?
}
});
Advertisements.cachedCategoriesByUrl[categoriesUrl] = getCategories;
return getCategories;
}
}
Note:
return getCategories runs before the ajax call finishes. How do I make sure that return getCategories gets my error update(I want to pass an empty array if JSON request fails or invalid). Sorry I am in the learning process.
Solved it with this:
$.ajax({
url: ad.categoriesUrl
}).then(function(data){
Advertisements.advertisementSlot(ad, data);
}, function(data){
data = {};
Advertisements.advertisementSlot(ad, data);
});

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

Using data returned from AjaxSubmit

I am trying to get access to the data returned from an ajaxSubmit request.
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {
populate('#registrationform', data);
},
resetForm: true
});
});
The data that is returned is not being recognise by my populate function, If i do however with raw data,
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {
populate('#registrationform', {studentId: 1, firstName: 'Kay'});
},
resetForm: true
});
});
my populate function works. Any ideas why the data returned is not recognised?
My guess is that the data is actually coming back as a String, NOT a JavaScript object. If you are inspecting with console.log(data), this distinction would be very easy to miss.
Looking at the documentation for the success method and the dataType option, it is quite possible that your server's response is being taken for a simple String. Try explicitly setting dataType: "json" and see what comes back. That, or deserialize to an object with JSON.parse().
Use it like,
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {// data should be return as json
populate('#registrationform',{studentId: data.id, firstName: data.name});
},
resetForm: true
});
});

Categories

Resources