According to the Backend API: https://docs.typo3.org/typo3cms/CoreApiReference/JavaScript/Ajax/Backend/Index.html I could use every library to do AJAX calls in the TYPO3 Backend.
I get the success message, but my params array is always empty:
Controller
public function renderShowModal($params = array(), \TYPO3\CMS\Core\Http\AjaxRequestHandler &$ajaxObj = NULL){
var_dump($params);
}
jQuery
$.ajax({
type: 'POST',
url: TYPO3.settings.ajaxUrls['Controller::renderShowModal'],
data: {
"test": "bar"
},
success: function (result) {
console.log(result);
},
error: function (error) {
console.log(error);
}
});
What am I missing or how do I have to send my data?
It's even not working like this:
{"tx_ext_bm[test]": "bar"}
Thanks in advance
There is no answer in any of the forums I've questioned this, so I ended up accessing the params the traditional way with $_POST.
Related
I am creating a game that I am using ajax and ASP.net to create a two player game. So I am trying to create a couple of buttons for the player to use to "play" a card if it is their turn. I am currently stuck on trying to get the json to call the c# code, but have not been successful yet.
Here is where I'm at:
$(document).ready(function () {
$("#slap").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "Pages/index/",
data: {
//Something goes here
},
success: function (result) {
alert('ok');
},
error: function (result) {
alert('There was an error');
}
});
});
}
Then in the C# code index.cshtml.cs I have a function like playCard().
Thanks in advance!
Url format is wrong. It should be like "/controller/action"
I'm developing an app with an Angular based front-end and an ASP.NET back end using oData and Oracle. I'm at the point where I'm trying to patch records on the back end. I'm using generic boilerplate code on the back end in my controller and the patch method looks like this:
<AcceptVerbs("PATCH", "MERGE")>
Async Function Patch(<FromODataUri> ByVal key As Decimal, ByVal patchValue As Delta(Of FTP_ORDERS)) As Task(Of IHttpActionResult)
Validate(patchValue.GetEntity())
If Not ModelState.IsValid Then
Return BadRequest(ModelState)
End If
Dim fTP_ORDERS As FTP_ORDERS = Await db.FTP_ORDERS.FindAsync(key)
If IsNothing(fTP_ORDERS) Then
Return NotFound()
End If
patchValue.Patch(fTP_ORDERS)
Try
Await db.SaveChangesAsync()
Catch ex As DbUpdateConcurrencyException
If Not (FTP_ORDERSExists(key)) Then
Return NotFound()
Else
Throw
End If
End Try
Return Updated(fTP_ORDERS)
End Function
On the Angular side, I'm using $resource based service to send the update. The code that calls the resource looks like this:
(new FTPOrderService({
"key": vm.ID,
"data": vm
}, vm))
.$patch()
.then(function (data) {
alert("Order Saved!");
},
function (error) {
debugger;
}
);
The service is defined with:
.factory('FTPOrderService', function ($resource) {
var odataUrl = '../odata/FTP_ORDERS';
var results = $resource('', {}, {
'patch': {
method: 'PATCH',
params: {
key: '#key',
},
url: odataUrl + '(:key)'
}
});
return results;
})
I've also tried:
(new FTPOrderService({
"key": vm.ID,
}, vm))
.$patch(vm)
.then(function (data) {
alert("Order Saved!");
},
function (error) {
debugger;
}
);
and get the same results.
I believe that I have configured angular to send the data properly with:
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.patch = {
'Content-Type': 'application/json;charset=utf-8'
};
}])
The debugger shows that I'm calling the URL with the appropriate key appended to it in parens and the request payload looks like this:
{key: "1239990990", data: {loading: false, selectedRow: {}, lineItems: [,…], orderId: "1239990990",…}}
data: {loading: false, selectedRow: {}, lineItems: [,…], orderId: "1239990990",…}
key: "1239990990"
Any idea of what I'm missing? There are numerous examples out there using direct calls to $http.post and a few for .patch, but nothing current using $resource.
I am not entirely sure what the cause of this issue was, but in tracing it, I did discover that intermittently an object was not being received by the patch method in .NET. The object I'm passing in is particularly heavy and what I was passing by default was actually heavier than what the ASP.NET side of the app requires. Adding code prior to the patch call to assemble an object that meets the requirements at a minimum level resolved the issue.
I want to incorporate jquery autocomplete widget to my aspx page. The "source" for the autocomplete comes from a webservice method.
My script looks like this:
$(".paisProc").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
type: "POST",
url: "/ManifestService.asmx/GetPaises",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'term': request.term }),
success: function (data) {
console.log("reading results...");
response($.map(data, function (item) {
console.log(item.CodigoAduana);
return {
label: item.Descripcion,
value: item.CodigoAduana
};
}));
},
error: function (err, status, error) {
console.log(status);
console.log(error);
}
});
With this setup, as users type in the input control, the expected values are returned from the webservice but the autocomplete does not seem to work. Inspecting the page with Firebug i see the ajax call to the service returns data with this format:
{"d":[{"__type":"dhl.domain.Pais","PaisId":1,"CodigoDHL":"AR","CodigoAduana":"528","Descripcion":"ARGENTINA"},
{"__type":"dhl.domain.Pais","PaisId":481,"CodigoDHL":"DZ","CodigoAduana":"208","Descripcion":"ARGELIA"}]}
I cannot see what the problem with my code, I have followed the indications from the many questions with the same issue in this site with no success yet.
If it can help, the line console.log(item.CodigoAduana) from success callback write "undefined" to the console.
.Net web services returning JSON do so by embedding the payload into a "d" property (as you can see in your capture of the JSON).
Try changing your processing of the response to read from data.d instead of just data, to get to the array you want to map, like this:
response($.map(data.d, function (item) {
console.log(item.CodigoAduana);
return {
label: item.Descripcion,
value: item.CodigoAduana
};
}));
I have a generic-http-handler and I am calling it from jQuery.
My handler only insert values in database but does not return anything.
I am calling the handler as follow
function InsertAnswerLog(url) {
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: { 'Url': url, 'LogType': "logtype" },
success: function (data) {
},
error: function (Error) {
}
});
}
Everything is working fine for me.
But is it the best way to post the values to the server.
Or can I use it in a better way.
it seems the type of data you are sending is JSON encoded try serializing the data in this form before sending and then on the server side you should encode the data before sending it back.
serializing before sending to server
function InsertAnswerLog(url) {
var DatatoSend = { 'Url': url, 'LogType': "logtype" } ;
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: {Jsondata: JSON.stringify(DatatoSend)},
success: function (data) {
},
error: function (Error) {
}
});
}
now on the sever side scipt
// NB: i use PHP not asp.net but it think it should be something like
Json.decode(Jsondata);
// do what you want to do with the data
// to send response back to page
Json.encode(Resonponse);
// then you could in php echo or equivalent in asp send out the data
It is important that you decode the json data on the server-side script and when a response is to be sent it should be encoded back it JSON form for it to be understood as a returned json data.
I hope this helps.
I have in my .js file a function that call a webservices method called getStudents:
[WebMethod(Description = "white student list")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Job> getStudents(long classId)
{
return (new classManager()).getStudents(classId);
}
the method is callled like:
function loadStudents() {
var parameters = JSON.stringify({ 'classId': 0 });
alert(parameters);
$("#ProcessingDiv").show('fast', function() {
$.ajax({
type: "POST",
url: "myWebService.asmx/getStudents",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$("#ProcessingDiv").hide();
var students= response.d;
alert('yes');
},
error: function(request, status, error) {
alert(request.responseText);
}
,
failure: function(msg) {
alert('somethin went wrong' + msg);
}
});
});
}
$(document).ready(function() {
loadStudents();
});
when i debug,the service web method is executed successfully but i don't get my alert('yes') and neither msg error.
What's wrong?
If you're returning (serialized to JSON) List of objects, then in response you will get JS array of JS objects, so (assuming Job has property p) try response[0].p for p value from first element.
note: I don't know ASP.NET, so maybe response is serialized in another way, thats where tools like Firebug (or other browsers Dev tools) are extremely useful - because you can look how exactly you'r http requests and responses looks like.
ps. And change alert to console.log and look for logs in Firebug console - its better than alert in many, many ways ;]