How to get values from data: part in ajax call - ajax

$.ajax({
type: "POST",
url: baseUrl + "query?v=21266702",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({ query: text, lang: "en", sessionId: reqIdToken }),
success: function(data) {
xyz
}else{
setResponseForIT(data,"");
}
},
error: function() {
setResponse("Internal Server Error");
}
});

You would assign this stuff to variables before sending the raw data.
You have the data right here :
query: text, lang: "en", sessionId: reqIdToken
you are basically building the JSON on the fly, just process these before by setting them as variables.
Update (for clarification) :
This is creating json for you based on the variables already set etc.
JSON.stringify({ query: text, lang: "en", sessionId: reqIdToken })
This means you have access to 'text' and 'reqIdToken' and hence don't need to look at the 'data' variable that contains the json. Just use reqIdToken if you want to know the sessionId. (e.g. if (reqIdToken == "999") alert();)

Related

SharePoint ajax ValidateUpdateListItem

I would like to post an ajax call to update a list without updating the version. I was told I can make use of the ValidateUpdateListItem() function. However, when I try using it, I have the error: System.ArgumentNullException value cannot be null parameter name: formValues. Here is a code snippet.
url: "path/ValidateUpdateListItem()",
method: "POST",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json; odata=verbose",
"IF-MATCH": request.ETag,
"X-HTTP-Method": "MERGE",
"X-RequestDigest": $('#__REQUESTDIGEST').val()
},
data: JSON.stringify({
"formValues":[
{
'Field1': 'value1'
}
],
'bNewDocumentUpdate': true
}),

Modify xml using AJAX

I have the following xml file:
<User>
<Address>123</Address>
<FirstName>John</FirstName>
<SecondName>Smith</FirstName>
</User>
I am trying to get it changed with an AJAX call:
var addressid= = 123;
$.ajax({
type: "GET",
url: url,
headers: {
"Authorization": "Basic " + btoa("username:password"),
},
contentType: "application/xml",
dataType: "xml",
async: true,
crossDomain: true,
success: function(xmlResponse) {
alert("Your user has been edited");
$(xmlResponse).find('User').each(function(){
if($(this).find('Address').text() == addressid) {
$(this).find('FirstName').text("Jenifer");
$(this).find('SecondName').text(secondName);
}
});
}
});
An alert comes, this does not display any errors, but it doesn't get passed on to the system. Which means, if I fetch the data from the server, the old name gets displayed. What am I doing wrong?

How do I pass an Image in the body of a OData Request in SAPUI5?

I need to pass an sap.m.Image file to the body(Data) of an OData request. Below is the code and I would like to know what to pass to the data parameter of the request so that my Image gets uploaded to the backend. When I pass the ImgValue which contains the dataurl it gives out an error saying
DOMException: Failed to execute 'createElementNS' on 'Document': The qualified name provided ('d:0') contains the invalid name-start character
OData.request({
requestUri: "http://ambrifiori.am.brothergroup.net:8081/sap/opu/odata/sap/ZPVSYSTEM_SRV/PromoImagesSet/",
method: "POST",
headers: {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/atom+xml",
"DataServiceVersion": "2.0",
/*"Accept": "application/atom+xml,application/atomsvc+xml,application/xml", */
"X-CSRF-Token": header_xcsrf_token,
"slug": "ajay122",
},
data: ImgValue,
});
I wasn't able to post image data through OData hence I used ajax...
This is what I did.
OData.request
({
requestUri: "http://AMBRIFIORI.am.brothergroup.net:8081/sap/opu/odata/sap/ZUI5_DAILY_SALES_SRV/DailySalesSet",
method: "GET",
headers:
{
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/atom+xml",
"DataServiceVersion": "2.0",
"X-CSRF-Token":"Fetch" }
},
function (data, response)
{
header_xcsrf_token = response.headers['x-csrf-token'];
csrftoken = header_xcsrf_token;
$.ajax({
url: 'http://ambrifiori.am.brothergroup.net:8081/sap/opu/odata/sap/ZPVSYSTEM_SRV/PromoImagesSet/',
//dataType: 'json',
data: imgData,
//data: image,
type: 'POST',
headers: { "X-Requested-With": "XMLHttpRequest",
"Content-Type": "image/png",
"DataServiceVersion": "2.0",
/*"Accept": "application/atom+xml,application/atomsvc+xml,application/xml", */
"X-CSRF-Token": csrftoken,
"slug": slug,
},
success: function(data) {
debugger;
console.log(data);
},
error: function(data) {
debugger;
console.log(data);
}
});
My ImgData consists of image in Data URI format base64. I just added one statement in my Imgvalue to convert it to ImgData which is
var imgData = JSON.stringify(ImgValue);

Ajax Post not sending data Correctly

VB.net, MVC4, asp.net views.
I would like to know why I cannot send or what I am doing wrong sending a parameter(int), parameter(model).
data:
var ID = '<%: Model.ID%>';
var data = $('#dlg').find('form').serialize();
Ajax Post:
$.ajax({
url: '<%: Url.Action("EST", "Now")%>',
type: 'POST',
data: { id: ID, model: data },
success: function (rData) {
$('#divE').html(rData);
}
});
Now - Controller:
<HttpPost> _
Function EST(id As Integer, model As EViewModel) As ActionResult
So I'm passing a modelID and the forms data, sending them separately( with modifications ) both work, but sending them together it seems to null the 2nd parameter. Found by debugging the action.
try use JSON.stringify.
Include contentType: "application/json; charset=utf-8", when you omit the contentType value default is 'application/x-www-form-urlencoded; charset=UTF-8' this could become a trouble when you will post data
$.ajax({
url: '<%: Url.Action("EST", "Now")%>',
type: 'POST',
data: JSON.stringify({ id: ID, model: data }) ,
contentType: "application/json; charset=utf-8",
success: function (rData) {
$('#divE').html(rData);
}
});

Correct spelling in ajax POST

I have two verions of code I believe should do the same thing, but the first one works and other one doesn't (Post vars: agenti, week_, team_). I have searched for few examples of how to do it the other way and I am sure my example is similar.
What do I do wrong?
First:
$.post("index.html",
{
agenti: getItems(),
week_: week_array,
team_: team
},
function(data,status){
if (status = 'Success'){
alert('Aktuální řazení operátorů bylo úspěšně uloženo.');
} else {
alert('Aktuální řazení operátorů se nepodařilo uložit.\nKontaktujte prosím správce aplikace.');
}
Second:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "index.html",
data: JSON.stringify({agenti: getItems(), week_: week_array, team_: team}),
success: function (msg)
{
alert('Aktuální řazení operátorů bylo úspěšně uloženo.')
},
error: function (msg)
{
alert('Aktuální řazení operátorů se nepodařilo uložit.\nKontaktujte prosím správce aplikace.')
}
});
I want to do the second one because I need to specify content type and i couldn't figure how to do it in the first way.
Thanks you!
edit: I use IE; this code will be used only in IE.
so the first thing is that, no need to use JSON.stringify function, as the data accepts JSON objects, as well the string represented like a url (test1=1&test2=2...). So to use it like the following is ok.
data: {agenti: getItems(), week_: week_array, team_: team},
Also when you are using contentType: 'application/json' the GLOBAL $_POST variable is not being populated as it is being populated only for form-urlencoded data which is default value for contentType option, here you go with data from jQuery reference`
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
In order you like to use application/json, you can retrieve that information in PHP side using php input like this following. file_get_contents('php://input');
---Working Example---
Javascript:
$.ajax({
type: "POST",
// contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost",
data: {agenti: 'test1', week_: 'test2', team_: 'test3'},
success: function(msg) {},
error: function(msg) {}
});
PHP:
// Retrieve the input
var_dump(file_get_contents('php://input'));
// Use $_POST var
echo json_encode($_POST);

Resources