I have the following javaScript code:
const getReport = {
jobID: $('#jobID').val(),
startDate: $('#summaryStart').val(),
endDate: $('#summaryEnd').val(),
tableType: 'Summary',
};
$.ajax({
url: "php/reports.php",
contentType: "application/json",
type: "post",
dataType: "application/json",
data: function (d) {
return JSON.stringify(getReport);
},
success: function (response) {
if (response["tableColumns"].substring(0, 4) === "<h4>") { //if html returned here no detail query
} else {
$('#summaryTable').DataTable({
select: {
sytle: 'single',
items: 'row'
},
data: response["tableData"], columns: response["tableData"],
dataSrc: ""
});
}
}
});
And in my php code I have the following (to test values coming accross):
$rawJson = file_get_contents("php://input");
echo $rawJson;
return;
$parms = json_decode($rawJson, true);
$jobId = $parms["jobID"];
The code as stated above the XLR value from Chrome's developer tools is blank. If I run with this code instead:
$rawJson = file_get_contents("php://input");
// echo $rawJson;
//return;
$parms = json_decode($rawJson, true);
$jobId = $parms["jobID"];
I get:
Warning: Trying to access array offset on value of type null at the statement: $jobId = $parms["jobID"];
Note: when I get the warning message, javascript executes my success: routine, but the response appears to be null or blank.
I do a similar thing with fetch in another part of the app and it works. I could probably switch to that method, but would like to know why my jQuery call does not work.
The data option can't be a function. So this:
data: function (d) {
return JSON.stringify(getReport);
},
should be:
data: JSON.stringify(getReport),
The data parameter of $.ajax does not take a function it takes a PlainObject or String or Array. Also dataType for JSON is json not the json content type application/json.
const getReport = {
jobID: $('#jobID').val(),
startDate: $('#summaryStart').val(),
endDate: $('#summaryEnd').val(),
tableType: 'Summary'};
$.ajax({
url: "php/reports.php",
contentType: "application/json",
type: "post",
dataType: "json",
data: JSON.stringify(getReport),
success: function (response) {
if (response["tableColumns"].substring(0, 4) === "<h4>") { //if html returned here no detail query
} else {
$('#summaryTable').DataTable({
select: {
sytle: 'single',
items: 'row'
},
data: response["tableData"], columns: response["tableData"],
dataSrc: ""
});
}
}
});
Related
This code works perfectly in DEV environment. Now that it's in UAT, it's returning a 405 Method Not Allowed error. All I'm trying to do is a GET. For some reason, the response headers in the console are now showing "Allow: POST". I don't know why it's allowing POST, and I don't know how to change it. Here's the code below. The call failing is the first one being made to the GetThings stored procedure. Why is the response header allowing a POST when I'm trying to do a GET? How can I change the response header from POST to GET? Again, this works perfectly in DEV. Thanks
var comboBox = $("#cappfMTF").kendoComboBox({
dataTextField: "Name",
dataValueField: "ID",
template: '#:data.ID# - #:data.Name#',
placeholder: "Select Thing",
height: 260,
autoBind: true,
dataSource: {
type: "json",
serverFiltering: true,
serverPaging: true,
transport: {
read: {
type: "GET",
url: "/_layouts/15/_Service/Service.svc/GetThings",
dataType: "json",
contentType: "application/json",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json;odata=verbose");
}
}
},
change: function () {
var mtfValue = comboBox.value();
$.ajax({
url: "/_layouts/15/_Service/_Services.svc/v_Things?$filter=IDName eq '" + mtfValue + "'",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json;odata=verbose");
},
success: function (result) {
//set value of diff dropdown
var diffCombo = $("#cappfMarket").data("kendoComboBox");
if (result.d.length == 1) {
var diffValue = result.d[0].diff;
diffCombo.value(diffValue);
}
}
});
},
schema: {
model: {
Id: "ID",
fields: {
ID: { type: "string" },
Name: { type: "string" }
}
},
data: function (response) {
return response.d;
}
}
}
}).data('kendoComboBox');```
I am trying to pass value from js to a method gateway in Home controller and I want the result back(Integer)
$.ajax({
url: '/Home/gateway?s=' + dates[],
type: 'POST',
dataType: 'json',
data: { id: 'value' },
success: function (data) {
alert("success");
},
error: function () {
alert('error');
}
});
You're passing url query parameters in a POST request which by design should expect a payload body. Why not add another property called dates inside of your data object and set its value to the dates array?
$.ajax({
url: '/Home/gateway',
type: 'POST',
dataType: 'json',
data: {
id: 'value',
dates
},
success: () => {
alert("success");
},
error: () => {
alert('error');
}
});
I have a problem with formatting JSON object in Google Chrome browser. I wrote example code:
var sendData = {
'flag': 1,
'sort': {
'imie_nazwisko': 'asc'
},
'where': {
'global_percent': 0,
'analityk': ["Dariusz Doda", "Arkadiusz Garbarczyk"]
}
};
Bellow is a screen from browser inspector:
Data in browser
To be sure if all is correct with ajax methodes I attached it:
$.ajax({
url: '/admin/setData',
type: "POST",
dataType: 'json',
data: sendData,
success: function (data) {
done(data.MESSAGE);
},
error: function(data) {
console.log(data);
}
});
In my opinion, code which is going to server had to be a little bit different. Some advice what is wrong?
You need:
Declare your object:
var sendData = {
flag: 1,
sort: {
imie_nazwisko: "asc"
},
where: {
global_percent: 0,
analityk: ["Dariusz Doda", "Arkadiusz Garbarczyk"]
}
};
Set in the $.ajax() function:
data: JSON.stringify(sendData),
contentType: "application/json;charset=UTF-8",
So, you can send JSON Object.
See this demo:
var sendData = {
flag: 1,
sort: {
imie_nazwisko: "asc"
},
where: {
global_percent: 0,
analityk: ["Dariusz Doda", "Arkadiusz Garbarczyk"]
}
};
$.ajax({
url: 'https://jsonplaceholder.typicode.com/post',
type: "POST",
dataType: 'json',
data: JSON.stringify(sendData),
contentType: "application/json;charset=UTF-8",
success: function(data) {
done(data.MESSAGE);
},
error: function(data) {
console.log(data);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I want to split the ajax returned values using jQuery.
Here is my code:
var url = "/StudentProgress/GetStudProgDet/";
$.ajax({
url: url,
data: { currentAcadYr: iAcademicYearText, currentSem: iSemesterText },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (data) {
var result = $(data).text().split(':');
var ProgAcadYearCode = result[0].ProgAcadYearCode;
var productSize = result[1];
// alert(data.ProgAcadYearCode);
//$("#ToProgressAcademicYearId option").filter(function () {
// return this.text == testsem;
//}).attr('selected', true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
I got a result like this:
data = {
success: true,
progAcadYearCode: 20172018,
progAcadYearId: 17,
progressSemId: 47,
progressSemNo: 2
}
How do I extract the desired values from the JSON using jQuery?
Based on data what you shown,you have to directly fetch it's properties like below:-
success: function (data) {
console.log(data.success);
console.log(data.progAcadYearCode); //and so on
},
When I preload values into Select2 dropdown, and expand the control to type in a value. It filters the preloaded values. How do I configure Select2 to make ajax calls (new search) when I type in the text box? If I don't preload values into Select2, the ajax calls work. So how can I have both?
I preload my select2 control with something like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: url,
data: json,
dataType: "json",
success: function (data, textStatus) {
var json = JSON.parse(data.d);
var arrData = [];
if (json !== null && json !== undefined) {
if (json.length > 0) {
$.each(json, function (index, element) {
var item = { id: element.CommonName, text: element.CommonName, name: element.CommonName };
arrData.push(item);
});
}
}
$("[ID$=ddlDropDown]").select2({
data: arrData
});
}
});
I instantiate my Select2 control with this:
$("[ID$=ddlDropDown]").select2({
ajax: {
url: url,
type: "POST",
dataType: 'json',
async: true,
contentType: "application/json; charset=utf-8",
delay: 500,
data: function (params) {
var query = {
searchString: (params.term || ""),
page: params.page
}
// Query paramters will be ?search=[term]&page=[page]
return JSON.stringify(query);
},
processResults: function (data, page) {
var json = JSON.parse(data.d);
if (json != null) {
if (json.length > 0) {
return {
results: $.map(json, function (item) {
return {
text: item.CommonName,
name: item.CommonName,
id: item.CommonName
}
})
};
} else {
return false;
}
}
else {
return false;
}
},
success: function (data, page) {
$("[ID$=ddlDropDown]").select2("data", data, true);
}
},
minimumInputLength: 2,
placeholder: "Select a Value",
disabled: false,
cache: true
});
as i had this problem and could not found any solution, I would like to share a solution which i did.even this is an old question which is not answered yet.would be helpful for others
$('#select2').select2({
allowClear: true,
multiple: false,
// minimumInputLength: 3,
ajax: {
url: "url",
dataType: 'json',
delay: 250,
type: 'POST',
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function (data, container) {
return {
results: $.map(data, function (item) {
return {
text: item.title + '| <b>' + item.title_2 + '</b>',
id: item.id,
}
})
};
},
cache: false
},
escapeMarkup: function (markup) {
return markup;
},
placeholder: __('select.project_search'),
}).live('change', function (e) {
// on change code
});
And in your controller you can check
if search term is null then return the preload options
else run the SQL for search data or return remote data.
the trick is you have to comment out minimumInputLength
this will trigger select2 ajax whenever you click it. and loads preload for you like following
and when you search you will get remote results like this
I hope this will help someone searching for a solution