jQuery AJAX POST - data doesn't get sent - javascript

$.ajax({
url: "/Configuration/AddServersAdvancedSelect",
type: "POST",
data: { selectedOUs: that.getByDataSelected() },
async: false,
dataType: "html",
success: result => {
cont.setTabContentFromHtmlString(result, 1);
cont.tabClicked($("td[data-value='1']").get(0));
},
error: (xhr, ajaxOptions, thrownError) => {
//
}
});
EDIT: I came back to work today and it magically started working. I guess that's something
This is my ajax request towards the server. For some reason the data doesn't get selected. The getByDataSelected function works just like it should and reuturns good values. The Controller method has the name selectedOUs and everything matches. Does anybody have any idea as to why this ajax POST doesn't send data?

jQuery defines the data parameter as
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing.
Object must be Key/Value pairs.
If value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
I'd be willing to bet that your return value of that.getByDataSelected() is not consistent with the expected parameter if it isn't getting sent.
In this case, your error function should be receiving an Internal Server Error [500]

Related

Getting null in return when executing Ajax request

Ajax request is executing, but it returns not curent_day variable but null.
Js:
$.ajax({
url: 'planing/next-day',
data: {new_curent_day: $('.owl-item.center .slide_day').text()},
dataType: 'json',
type: 'POST',
success: function(curent_day) {
alert(curent_day);
},
error: function(xhr, status, error) {
alert(xhr.responseText + '|\n' + status + '|\n' +error);
}
});
Controller:
public function actionNextDay() {
if (Yii::$app->request->isAjax){
$this->planing_model->curent_day = Yii::$app->request->post('new_curent_day');
return Json::encode($this->planing_model->curent_day);
}
}
May be the problem is your are sending the POST data as JSON so your not able get it through
Yii::$app->request->post('new_curent_day');
Try this they have updated JSON parser set and to get the JSON value through yii.
Error in accessing post json data in yii2
Use the Javascript console and debugger in your browser to see what $('.owl-item.center .slide_day') contains. Make your API endpoint log what it gets in the post variables.
The typos in variable names make me worry that you might refer to the wrong thing. planing has two n's, curent has two r's. This code looks consistent at least but if I came across this code I would suspect current and curent got mixed up.

"no element found" error when using JSON stringify method in jQuery ajax call

I want to update a section of a page using ajax when an image is clicked. When the image is clicked I pull values from a jQuery DataTable to populate an object. Then I call my action and pass in a JSON string of the object using JSON.stringify().
$("#image").click(function(e) {
data = {}
table = $("#myTable").dataTable();
$.each(table.fnGetData(), function(index, value) {
row = $(table.fnSettings().aoData[index].nTr);
data[row.find(".key")] = {
"val1": row.find(".val1").text(),
"val2": row.find(".val2").text(),
"val3": row.find(".val3").text(),
"val4": row.find(".val4").text(),
}
});
$.ajax({
url: "myAction",
contentType: "text/html",
data: {
json: JSON.stringify(data)
},
success: function(resp) {
alert(resp)
$("#myDiv").html(resp);
}
});
});
However, calling the ajax function results in an error in the javascript console that only says "no element found". When I check the network activity it tries to hit the correct url, but returns a 400 error.
I am sparing the back end details because I believe something in the stringify method to be the culprit here because when I pass a string literal as the ajax data such as data: {json: "foo"} it calls my action with no problem whatsoever.
The solution was to specify the ajax method as POST by adding the following attribute to the ajax call.
method: "POST"
No idea why this makes it work, but it does.

jQuery Ajax Array serializes incorrectly

This is a weird one, although it should be very simple.
The code:
var recipients = [];
recipients.push(uuid1);
recipients.push(uuid2);
$.ajax({
url: '/api-url/',
type: 'POST',
data: {'recipient': recipients, 'message': message, 'subject': subject},
dataType: 'json'
}) ...
This is caught in the Chrome Network inspector:
recipient[]:8b99fa41-0f8f-4882-b14f-dc258a765b15
recipient[]:add61999-9baa-4096-a92f-fbb144a4a981
subject:test
message:testtest
This arrives to the server:
{u'recipient[]': [u'8b99fa41-0f8f-4882-b14f-dc258a765b15', u'add61999-9baa-4096-a92f-fbb144a4a981'], u'message': [u'testtest'], u'subject': [u'test']}
As you can see, we have a 'recipient' in the ajax call, two instances of 'recipient[]' in network inspector and one 'recipient[]' on the server with correct data, but wrong param name.
Any ideas how is that '[]' in 'recipient[]' getting there?
This is what JQuery does to your data object:
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
To send it as JSON you need to convert it to JSON string:
...
type: 'POST',
data: JSON.stringify({'recipient': recipients, 'message': message, 'subject': subject}),

Jquery ajax success response is string not javascript object

I'm making a jQuery AJAX call to my Rails app (all run on localhost) which is responding with Javascript. The javascript is running because I'm getting the alert. But, I would like to read the my_var variable in the js.erb file. However, when I try to look at the data parameter of the success function it sees the data as a string. So doing data.my_var is undefined.
js.erb file
var my_var = "hi";
alert('this ran');
javascript
$.ajax({
url: "/a/validate?a_id=" + "<%= params[:id] %>",
context: this,
dataType: "script",
data:
{
json_a: JSON.stringify(this.a),
model_to_validate: model,
target_class: target_class,
current_class: current_class
},
success: function (data, textStatus, jqXHR) {
if(!this.orderFormViewed) {
this.orderFormViewed = data.order_block_opened;
}
},
error: function (data) {
console.log("error in ajax validate call");
debugger;
}
})
That's because that's exactly what you told it to do with dataType: "script" - look at the dataType options below. The script is run in it's own context and so you won't see that variable (I believe). You're going to need to communicate differently if you want that set. Or if you just need data send json.
https://api.jquery.com/jQuery.ajax/
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
try to change your dataType to json if you only need to get an object and be sure your server return a json.

Explain jQuery's JSONP and the _ parameter [duplicate]

When I look at the query string from a jsonp request (client code below), there are 2 objects, a "callback" string that you need to use in the response (so the client codes directs to the success handler) and one with a key of _... what is this underscore for? I can't find any reference to this in any documentation, it appears to be a number of some kind.
I though that it might be used to direct to the error handler (either on its on, in combination with the callback, or replacing the number after the underscore in the callback string), but it doesn't appear to be.
url = 'http://localhost:11767/Handlers/MyHandler.ashx';
...
$.ajax({
url: url,
dataType: "jsonp",
error: function (jqXHR, textStatus, errorThrown) {
//...
},
success : function(d) {
//...
}
});
or
$.getJSON(url + "?callback=?", function(d) {
}).success(function(d) {
//...
}).error(function(jqXHR, textStatus, errorThrown) {
//...
}).complete(function(d) {
//...
});
Side note in case this helps anyone reading this: as this is a jsonp request, error will only be hit if the exception occurs client side, e.g. there is a timeout or a problem with the formatting of response (i.e. not using the callback), to overcome this, I always log and swallow the exceptions in the handlers, but give a standard response object (which all response are made up of) that has a state property of exception and a message property.
The number you are referring is the date time stamp of the request. Grab the number and use a your browser's JavaScript console and type: alert(new Date(/*insert number here*/))
You'll get an alert with a date/time.
EDIT:
Here's a snippet from jQuery.ajax doc regarding an ajax request:
cache
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser.
Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]",
to the URL.

Categories