Formatting JSON sending by AJAX in browser - javascript

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>

Related

jQuery ajax parameters not being passed to php as expected

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: ""
});
}
}
});

ReferenceError: response is not defined on autocomplete jquery ajax call in singleton design pattern

I am trying to implement jQuery autocomplete in my solution but I got an error ReferenceError: response is not defined
Here is my code
(function ($) {
$.SupportArticleObj = function (p) {
var SupportArticle = {
config: {
isPostBack: false,
async: false,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: { data: '' },
dataType: 'json',
baseURL: "Modules/SupportArticle/Services/SupportArticleWebService.asmx/",
url: "",
method: "",
ajaxCallMode: 0,
PortalID: PortalID,
UserModuleID: UserModuleID,
SecureToken: SecureToken,
UserName: UserName
},
init: function () {
$("#searchSupport").autocomplete({
source: function (request, response) {
searchTerm = request.term;
SupportArticle.getSearchData(searchTerm);
}
});
},
getSearchData: function (searchTearm) {
SupportArticle.config.method = "SearchSupportArticle";
SupportArticle.config.url = SupportArticle.config.baseURL + SupportArticle.config.method;
SupportArticle.config.data = JSON2.stringify({
searchTerm: searchTerm,
portalID: SupportArticle.config.PortalID,
userModuleID: SupportArticle.config.UserModuleID,
userName: SupportArticle.config.UserName,
secureToken: SupportArticle.config.SecureToken
});
SupportArticle.ajaxCall(SupportArticle.config);
},
ajaxSuccess: function (data) {
response(data);
},
ajaxFailure: function () {
jAlert('Somethings went wrong', 'Support Article');
},
ajaxCall: function (config) {
$.ajax({
type: SupportArticle.config.type,
contentType: SupportArticle.config.contentType,
cache: SupportArticle.config.cache,
url: SupportArticle.config.url,
data: SupportArticle.config.data,
dataType: SupportArticle.config.dataType,
success: SupportArticle.ajaxSuccess,
error: SupportArticle.ajaxFailure,
async: SupportArticle.config.async
});
}
};
SupportArticle.init();
};
$.fn.callSupportArticle = function (p) {
$.SupportArticleObj(p);
};
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
What I am trying to do here is, I am calling a webservice which will search the records on database and return as a list and I want to bind that list on textbox as a autocomplete. But the problem is while running the solution in browser I got an error ReferenceError: response is not defined.
I was trying http://www.c-sharpcorner.com/UploadFile/da55bf/Asp-Net-autocomplete-textbox-using-jquery-json-and-ajax/ as reference.
How can I solve the issue of ReferenceError: response is not defined
Write your script like below:
AutoDemoDataBase: function () {
$("#lytA_ctl29_txtSearchName").autocomplete({
source: function (request, response) {
var param = JSON.stringify({
userModuleID: UserModuleID,
portalID: autoComplete.config.portalId,
prefix: $("#lytA_ctl29_txtSearchName").val(),
userName: autoComplete.config.UserName,
secureToken: SageFrameSecureToken
});
$.ajax({
type: autoComplete.config.type,
contentType: autoComplete.config.contentType,
cache: autoComplete.config.cache,
url: autoComplete.config.baseURL + "GetNames",
data: param,
dataType: autoComplete.config.dataType,
async: autoComplete.config.async,
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (response) {
jAlert(response.responseText);
},
failure: function (response) {
jAlert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfId").val(i.item.val);
$('#test').text(i.item.val);
},
minLength: 1
});
}
Your ajax success function is out of response scope.

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

how to get the json string in a variable

i got my json string inside the ajax as function like this way
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
here i get data like
[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
i want it in a variable like
var myjsonobject =[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
There you go :
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
var jsonobject = data;
},
error: function () {
alert('Error');
}
});
Also I strongly advise you to use promises to make API calls: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
var jsonobject= null;
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
jsonobject=data;
alert('Success');
},
error: function () {
alert('Error');
}
});
If you want wait for ajax response and fill up variable then pass async: false in ajax request options.
Based on your comment, you need to parse the JSON in your success handler,
success: function (data) {
alert('Success');
var myjsonobject = JSON.parse( data );
},

ASP.NET WebMethod returns whole page to JQuery ajax requests

I am building a web application where I am calling a ASP.NET WebMethod from jQuery on click of a textbox. The problem is that it returns me the whole ASPX Page. How can I get just the values returned by the Web Method? This is my code:
$("#<%= groupNameTxt.ClientID %>").click(function () {
$.ajax({
url: "../UserGroups.aspx/GetGroupList",
data: "{ }",
// dataType: "json"
type: "POST",
// contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});
});
This is my WebMethod from CodeBehind
[System.Web.Services.WebMethod]
public static List<Groups> GetGroupList(string mail)
{
List<Groups> empList = new List<Groups>();
empList.Add(new Groups() { GroupID = 1, GroupName = "Admins" });
empList.Add(new Groups() { GroupID = 2, GroupName = "Employees" });
empList.Add(new Groups() { GroupID = 3, GroupName = "Engineers" });
empList.Add(new Groups() { GroupID = 4, GroupName = "Managers" });
empList.Add(new Groups() { GroupID = 5, GroupName = "Assistants" });
return empList;
}
You need to pass email as parameter as webmethod is expecting a parameter.
$.ajax({
url: "../UserGroups.aspx/GetGroupList",
data: JSON.stringify({ email: "someemail#test.com"}),
dataType: "json"
type: "POST",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});
Also specify contentType and dataType
The page was returning since it was not hitting the Web Method. The below code will hit the Web Method correctly. Pass in data as shown below.
$.ajax({
url: "UserGroups.aspx/GetGroupList",
data: '{ mail: "a#a.com"}',
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});

Categories