After calling sql adapter procedure through javascript function in worklight-->how to make use of the invocation data? - worklight-adapters

I called the adapter procedure through the JavaScript function and it worked correctly. Now I'm stuck with how to make use of the invocation data from the database.
<html>
<body>
<pre>
function aaa()
{
var x=document.getElementById("email").value;
var y=document.getElementById("mobile").value;
try{
WL.Client.invokeProcedure({
adapter : 'DB2',
procedure : 'procedure1',
parameters : [x,y]
}, { onSuccess : function(result)
alert("login Success");
},
onFailure : function(result){alert("login Failure");}
});
}
catch(e)
{
alert("ERROR::"+e);
}
}
/* Below is my adapter.js file */
var procedure1Statement = WL.Server.createSQLStatement("select * from user where email=? and contact=?");
function procedure1(x,y) {
return WL.Server.invokeSQLStatement({
preparedStatement : procedure1Statement,
parameters : [x,y]
});
}
/*
Ignore the html tags. Now how do I make use of the result
(i.e.data returned after execution of query?)
*/
</pre>
</body>
</html>

Look at the onSuccess callback function in your WL.Client.invokeProcedure call:
onSuccess : function(result)
alert("login Success");
}
This function well receive the result returned from your adapter call. Change the method to this:
onSuccess : function(result)
console.log(result);
}
And then view the call in your browser. You will be able to see the structure of the returned data. Then its up to you on what to do with it.

Related

How to passing Controller a FormCollection and a class type object to action

i am facing problem to Passing Controller a Form Collection and a class type object to action using ajax call.
below are the my code.
[HttpPost]
public ActionResult AddDealNotes(DealNote objDealNote,FormCollection fc)
{
//code
}
To send a javascript ajax request using the jquery $.post object you need to make sure you use the dataType & contentType parameters.
<script>
function sendDealNotes(note, form)
{
var dataOutput = {"note": note,"form": form.serializeArray()};
var sendData = JSON.stringify(dataOutput );
var jqxhr = $.ajax({url:"/Controller/AddDealNotes", type:"POST", dataType:"json", contentType:"application/json",data:sendData})
.done(function() {
alert( "success" );
})
.fail(function(err) {
alert( "error" + err );
})
.always(function() {
alert( "complete" );
});
}
</script>

Post from partial View change the URL

I have a partial view with a contact form.
My problem is that after the form is posted, the controller is redirecting to the actual URL of the partial view: ("LocalHost:/Views/ContactUs/MoreInformationRequest.cshtml")
I want to keep the same URL and to show only the ViewData["MsgSent"] message.
This is the call to the partial view:
#Html.Partial("~/Views/ContactUs/MoreInformationRequest.cshtml")
The View:
#using (Html.BeginForm( "MoreInformationRequest","ContactUs"))
{
.....
<input type="submit" value="send" /><br />
#ViewData["MsgSent"]
}
The Controller:
[HttpPost]
public ActionResult MoreInformationRequest(ContactUs contacts)
{
.....
ViewData["MsgSent"] = "Message sent!"
return View();
}
You could use a redirect to redisplay the page that loads the partial view:
return RedirectToAction("OriginalAction");
You could also return a specific view, particularly the view from the original action:
return View("OriginalView");
post to the server using jQuery and return false from the javascript function to stop the default processing (i.e. sending to the new url from the controller.
At the beginning I came out with this solution - to redirect to the same page using:
Request.Redirect("~/");
But I did not like this solution so I solved this by using client side code to send the data to the controller:
<script>
var request;
$('#formMoreInformationRequest').submit(function () {
var Name = document.getElementById('Name');
var Phone = document.getElementById('Phone');
// without this the validations in the page are not working.
if (Name.value == "") {
return false;}
else if (Phone.value == "") {
return false; }
else {
$('#overlay').show()
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/ContactUs/MoreInformationRequest",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
$('#overlay').hide()
$("#moreInfoMsg").html("Message Sent!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown) {
$('#overlay').hide()
// log the error to the console
alert(
"The following error occured: " +
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
}
</script>

How to call local MVC 4 function inside ajax call

In my SPA website i need to send antiforrgery token over to server by ajax. I use this article method:
http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-%28csrf%29-attacks
So in my layout.cshtml i have local function :
<script>
#functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
</script>
and i have separate js file named register.js where i call this function inside ajax:
$.ajax({
url: 'User/JsonRegister',
type: "POST",
data: d,
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
},
success: function (result) {
},
error: function (result) {
}
});
the problem is that i never #TokenHeaderValue() is never called and i m keep getting this error:
The required anti-forgery form field "__RequestVerificationToken" is not present.
How do i solve this problem?
The problem is using server side helper function in the separate js file. If you need to have ajax call in the separate js file, set #TokenHeaderValue() value to a hidden field and read the value of hidden field in the js file.
i add token to my data this way: which solves problem
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
Pass data in JSON format
$.ajax({
type:"POST",
datatype:"JSON",
data:{d:d}, // Remaining code is same
});
And use [HttpPost] before method signature in controller because it a Post request.

Why does POST without parameters not return JSON

I have a controller method
[HttpPost]
public ActionResult GetUserData()
{
return Json(GetCurrentUser());
}
I'm calling it $.ajax() through a method like this:
ServerCall: function (method, args, callback) {
$.ajax({
type: 'POST',
url: method,
data: JSON.stringify(args),
contentType: 'application/json;charset=utf8',
dataType: 'json',
success: function (result) {
if (callback) {
callback(result);
}
},
error: function (err) {
}
});
}
with the call being:
ServerCall('GetUserData', null, function(data){
});
As it is, when I make this call, $.ajax returns with success, but 'data' is null. Debugging, responseText is empty. On the server side, GetUserData is called, and it is returning a properly formatted Json object (I've gone so far as to create my own JSON ActionResult and verified that data is indeed being written to the response stream.
If I add a dummy parameter to the server side method:
[HttpPost]
public ActionResult GetUserData(string temp)
{
return Json(GetCurrentUser));
}
everything works perfectly. Browser is IE8. My question is, can anyone explain why this is happening?
UPDATE:
Note workaround solution below: I'd still be interested in knowing the root cause.
No repro.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetUserData()
{
return Json(new { foo = "bar" });
}
}
Index.cshtml view:
<script type="text/javascript">
var serverCall = function (method, args, callback) {
$.ajax({
type: 'POST',
url: method,
data: JSON.stringify(args),
contentType: 'application/json;charset=utf8',
dataType: 'json',
success: function (result) {
if (callback) {
callback(result);
}
},
error: function (err) {
}
});
};
serverCall('#Url.Action("GetUserData")', null, function (data) {
alert(data.foo);
});
</script>
result: 'bar' is alerted (as expected).
I was able to reproduce using Darin's code in IE8. While I don't know the root cause, I think it has something to do with how IE8 JSON.stringify handles null. Changing
data: JSON.stringify(args)
to
data: args ? JSON.stringify(args) : null
fixed the problem.
Note, the problem is intermittent - I was seeing failures in about one out of every ten calls. With the change, over 100 tests, the failure rate was zero.

Passing data from Controller to View using JSon object

I have the following to get the Json abject passed from the controller and populate the various textboxes in the view. However, nothing is happening even though controller is passing a valid Json object. What is wrong with this code???
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var url = '<%=Url.Action("DropDownChange") %>';
$("#vendorID").change(function() {
var selectedID = $(this).val();
if (selectedID != "New Vendor Id") {
//$.post('Url.Action("DropDownChange","Refunds")', function(result) {
$.post(url, { dropdownValue: selectedID }, function(result) {
alert(selectedID);
$("#name").val(result.Name);
$("#city").val(result.City);
$("#contact").val(result.Contact);
$("#address2").val(result.Address2);
$("#address1").val(result.Address1);
$("#state").val(result.State);
$("#zip").val(result.Zip);
});
}
});
});
This is the code in my controller;
public JsonResult DropDownChange(string dropdownValue)
// This action method gets called via an ajax request
{
if (dropdownValue != null && Request.IsAjaxRequest() == true)
{
paymentApplicationRefund =
cPaymentRepository.PayableEntity(dropdownValue);
paymentApplicationRefund.Address1.Trim();
paymentApplicationRefund.Address2.Trim();
paymentApplicationRefund.Name.Trim();
paymentApplicationRefund.City.Trim();
paymentApplicationRefund.Contact.Trim();
paymentApplicationRefund.State.Trim();
paymentApplicationRefund.Zip.Trim();
return Json(paymentApplicationRefund,"application/json");
}
else
{
return null;
}
}
You probably just need to tell it to expect JSON data back. By default it assumes it's HTML.
$.post(url, { dropdownValue: selectedID }, function(result) {
alert(selectedID);
$("#name").val(result.Name);
$("#city").val(result.City);
$("#contact").val(result.Contact);
$("#address2").val(result.Address2);
$("#address1").val(result.Address1);
$("#state").val(result.State);
$("#zip").val(result.Zip);
}, 'json');
I prefer sending Json to a ActionResult with my DTO as the parameter and use the JsonValueProviderFactory do the deserialization for me.
Sending JSON to an ASP.NET MVC Action Method Argument
Try this...
Add the ".change()" at the end of the function.
$(document).ready(function() {
var url = '<%=Url.Action("DropDownChange") %>';
$("#vendorID").change(function() {
.....
}).change();
});

Resources