how connect with web service - json

I am trying to get some data from a web service:
$.ajax({
type: 'POST',
url: "http://192.******.asmx?op=GetJSONString",
method: "serverCallback",
data: "Select con.cod as codigo, con.res as descripcion from con where ide>0",
success: function(data){alert(data)},
});
How can I get the returned JSON data?

Here is what my calls look like. Can you be more specific of the issue you are having?
$.ajax({
type: "POST",
data: "SOME DATA",
dataType: "json",
url : "/myapp/service.json",
cache: false,
error: function() {
alert("There was an issue");
}
,
success: function(data)
{
processJson(data);
}
});

I will also post what has worked with me for asmx services.
In the example below, for "url": "/service/Details.asmx/Reject", the "/Reject" is the method name in the web service (asmx) file.
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": "/service/Details.asmx/Reject",
"data": "{\"itemId\":\"" + id + "\",\"comment\":\"" + comms + "\"}",
"success":
function (msg) {
alert("Yea it worked!");
});
}
});

Related

Update item in another site collection in sharepoint 2013

I need to update item in another site collection according to this article I make my code like this
<script type="text/javascript">
$(document).ready(function () {
var otherSiteUrl = "<sitecollectionurl>";
var listName = "TestList";
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": {
"type": itemType
},
"Title": "updated title"
};
$.ajax({
url: otherSiteUrl + "/_api/contextinfo",
type: "POST",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (contextData) {
alert(contextData.d.GetContextWebInformation.FormDigestValue);
$.ajax({
url: otherSiteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?#target='" + otherSiteUrl + "'",
method: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue
},
success: function (data) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
});
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
I used
"X-RequestDigest":
contextData.d.GetContextWebInformation.FormDigestValue
after that I chenge ajax header like
"X-RequestDigest":
$("#__REQUESTDIGEST").val(contextData.d.GetContextWebInformation.FormDigestValue)
for both RequestDigest I got this error:
Invalid JSON. A token was not recognized in the JSON content
after that I chenge ajax header as
How can I update item successfully in another site collection with api?
eventually, I can edit item in another site collection.I just little change in my code.
first, most important part is library full name dose not contain List I use this url to find out library full name .
[Site url]/_api/web/lists/GetByTitle('List Name')/ListItemEntityTypeFullName
then I change metadate as
"__metadata": { "type": 'SP.Data.DocumentsItem' },
second I added
"X-HTTP-Method": "MERGE" , "If-Match": "*"
to header like:
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue,
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},

GitHub API AJAX POST returning 422

I'm trying to post an issue via the GitHub API and keep getting a 422 error. I've tried various approaches over the past few days with no luck - I'm hoping this is a simple mistake that someone can spot quickly?
My call is below - I'm using my Personal Access Token for authorization.
$.ajax({
type: "POST",
url: `https://api.github.com/repos/MYUSERNAME/MYREPONAME/issues?access_token=MYACCESSTOKEN`,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
"title": "Found a bug",
"body": "I'm having a problem with this."
})
}).done(function( data ) {
console.log( data );
});
Thanks in advance.
FYI finally got this to work with the code below to POST to the GitHub API (creating an issue):
$.ajax({
url: 'https://api.github.com/repos/USERNAME/REPONAME/issues',
type: 'POST',
dataType: 'json',
headers: {
Authorization: 'token MY_PERSONAL_TOKEN'
},
data: JSON.stringify({
"title": "Found a bug",
"description": "Bug description"
}),
success: function (response) {
console.log(response);
}
});

How to send array with json using ajax

How do I send an array with json using ajax? I want to store email and name:
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: 'email=' + $('#txtemail').val() ,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});
Let's suppose you have an array?
var array = [
"student1" : {
"name": "jon",
"email": "test#example.com"
},
"student2" : {
"name": "jon2",
"email": "test2#example.com"
}
]
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array),
datatype : 'application/json',
}, function(success) {
console.log(success)
});
Your question is not clear.please write your question in correct format.then community can be resolve your question easily.
I assume your problem and give solution for that.
var array = {name:'dua',email:'dua#gmail.com'};
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array)
}, function(success) {
console.log(success)
});
var postData = { "email":email,"name":name }
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: postData,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});

Pass Date from View to Controller with JSON

I am trying to pass the date by ajax to controller as below:
$.ajax({
type: "POST",
contentType: 'application/json',
url: '/UserReport/GenerateReport',
data: JSON.stringify({
'clientId': $('#reportClientDropdown').val(),
'dateFrom': $('#datePickerFrom').val(),
'dateTo': $('#datePickerTo').val()
}),
success: function (succ) {
//
},
error: function (data) {
}
});
dateFrom and dateTo are in format dd/mm/yyyy.
I am getting 500 error after this call. Here is my controller
public JsonResult GenerateReport(int userId, int clientId, DateTime dateFrom, DateTime dateTo)
Is there a problem with DateTime parameter?
specify ajax request datatype jQuery.ajax()
$.ajax({
url: '/UserReport/GenerateReport',
type: "POST",
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
'userId': 1,
'clientId': $('#reportClientDropdown').val(),
'dateFrom': $('#datePickerFrom').val(),
'dateTo': $('#datePickerTo').val()
}),
success: function (result) {
console.log(result);
},
error: function (xhr) {
alert('Error: ' + xhr.statusText);
}
});

Why is the update operation not posting any data?

I am using the Kendo Grid with inline editing. When I click the "Update" button, a POST gets made to my controller method with this signature. The controller action gets hit, so the POST is working.
[HttpPost]
public HttpResponseMessage SaveAccountAdmin(string jsonCompanyContacts)
However the POST data in the update operation never arrives - its always null.
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: {
jsonCompanyContacts: "John Doe"
}
},
Here is the FULL data source code.
var dataSource = new kendo.data.DataSource(
{
batch: false,
pageSize: 10,
transport: {
create: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
read: {
url: "/Company/ReadAccountAdmin"
},
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: {
jsonCompanyContacts: "John Doe"
}
},
//destroy: {},
parameterMap: function (data, type) {
return kendo.stringify(data);
}
},
this doesnt work either:
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
//data: { "jsonCompanyContacts": kendo.stringify({ jsonCompanyContacts: "John Doe" }) }
data: { "jsonCompanyContacts": "John Doe" }
},
//destroy: {},
parameterMap: function (data, type) {
return kendo.stringify(data);
}
BUT THIS WORKS- WHY?
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
//data: { "jsonCompanyContacts": kendo.stringify({ jsonCompanyContacts: "John Doe" }) }
//data: { "jsonCompanyContacts": "John Doe" }
},
//destroy: {},
parameterMap: function (data, type) {
return kendo.stringify({ "jsonCompanyContacts": "John Doe" });
}
The value is not passed to the controller as a string. Try using a model. This might help: MVC3 & JSON.stringify() ModelBinding returns null model
UPDATE
You really don't want to do it like that. Might work in theis one case, but you are shooting yourself in the foot.
Model
public class CompanyContactModel
{
public string CompanyContacts { get; set; }
}
Controller Signature
public JsonResult SaveAccountAdmin(CompanyContactModel companyContactModel)
...
Better
public JsonResult SaveAccountAdmin([DataSourceRequest]DataSourceRequest request, CompanyContactModel companyContactModel)
...
Update and Return and put into List
If error: ModelState.AddModelError(string.Empty, e.Message);
DataSourceResult result = [Your Model List].ToDataSourceResult(request, ModelState);
return Json(result, JsonRequestBehavior.AllowGet);
}
Try doing this in your update definition:
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data:{ "jsonCompanyContacts": kendo.stringify({ jsonCompanyContacts: "John Doe" })}
}
You might have to remove the operation in your parameterMap for this to work. The main thing is that you want to post a variable with the same name as in your controller. That variable should contain your stringified data.
You could also move this operation to your parameterMap if you want.
I had similar problem like you.I am getting values from the broswer , but its not posting the values to the update action model.
In my case I used "[ScriptIgnore(ApplyToOverrides = true)]" on the model which works fine.