values are not saved in session array - ruby-on-rails

In my controller action i initialize a session of array and inserting values. These values are coming from the client side through ajax, so the page is not refreshed while inserting these values to an array.But suprisingly every time it iniatialize a new session instead of inserting to the same defined session. Here is my code
controller
def receive_tags
parser = Yajl::Parser.new
#hash = parser.parse(request.body.read)
log=Logger.new(STDOUT)
log.error(#hash)
session[:tags]||=[]
session[:tags] << #hash["tag"]
unless session[:tags].empty?
log.error(session[:tags] ) #this keeps printing the current value i was expecting it to print a list of values including the previous
end
render :nothing=>true
end
Ajax
var myobj={tag:"mytag"};
$.ajax({
url: 'ips/receive_tags',
type: 'post',
contentType: 'application/json; charset=UTF-8',
accept: 'application/json',
dataType: 'json',
data:JSON.stringify(myobj),
success: function(res) {
if (res.ImportResponse !== void 0) {
console.log('Success: ' + res);
} else if (res.Fault !== void 0) {
console.log('Fault: ' + res);
}
},
error: function() {
console.error('error!!!!');
}
});

This sounds like the browser isn't saving cookies, which would explain the behavior you are seeing where the session is reinitialized every time. To confirm this, you can do
print "Session ID: #{request.session_options[:id]}"
in your action and see if the session id changes for each request. If it does, check your browser privacy settings and see if it is saving any cookies.

Finally i figured it out, The problem is i wasn't setting the request header for the token before sending ajax call so Rails was receiving data without the token, thus kept assuming it is a new object for every request.You can read more here.To set the request header add
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
Below is my ajax function that works
var myobj={tag:"mytag"};
$.ajax({
url: 'ips/receive_tags',
type: 'post',
contentType: 'application/json; charset=UTF-8',
accept: 'application/json',
dataType: 'json',
data:JSON.stringify(myobj),
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
success: function(res) {
if (res.ImportResponse !== void 0) {
console.log('Success: ' + res);
} else if (res.Fault !== void 0) {
console.log('Fault: ' + res);
}
},
error: function() {
console.error('error!!!!');
}
});

Related

Making AJAX call to MVC API

I am trying to make an API call with ajax:
svc.authenticateAdmin = function (id, code) {
$.ajax({
url: 'api/event/authenticate',
data: { 'id': id, 'code': code },
datatype: 'json',
contentType: 'application/json',
type: 'GET',
success: function (data) {
App.eventBus.publish('authenticationComplete', data);
}
});
};
The method in the API Controller:
[ActionName("All")]
public bool Authenticate(int id, string code)
{
var repo = new MongoRepository<Event>(_connectionString);
var entry = repo.FirstOrDefault(e => e.Id == id);
return entry.AdminPassword == code;
}
But I am getting a 404 error: urlstuff/api/event/authenticate?id=123&code=abc 404 (Not Found)
I have copied the implementation from a number of known working calls (that I did not write). That look like:
svc.getEventFromCode = function (code) {
$.ajax({
url: '/api/event/',
data: { 'code': code },
dataType: 'json',
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedEvent', data);
App.eventBus.publish('errorEventCodeExists');
},
error: function () {
App.eventBus.publish('eventNotFound', code);
}
});
};
and
svc.getEventPage = function (pageNumber) {
$.ajax({
url: '/api/event/page/',
data: { 'pageNumber': pageNumber },
dataType: "json",
contentType: "application/json",
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedNextEventsPage', data);
}
});
};
But neither has to pass in 2 parameters to the API. I'm guessing it's something really minor :/
Your action name is called "Authenticate", but you have included the following which will rename the action:
[ActionName("All")]
This makes the URL
/api/event/all
The problem lies in your url.
Apparently, ajax interpret / at the start of the url to be root
When the application is deployed on serverserver, its URL is something like http://localhost:8080/AppName/
with api/event/page/, ajax resolve the URL to http://localhost:8080/AppName/api/event/page/ or an url relative to your current directory.
However, with /api/event/page/, the URL is resolved to http://localhost:8080/api/event/page/
Hope it helped.

Success and Error functions not firing in Ajax call

Below is an Ajax call I'm using to determine which menu options to show to users (I know it's a flawed method, just up against a time crunch for a demo). When the page loads, I can step through the controller method in Visual Studio so I know it's hitting the controller and sending back the right information.
Looking at Chrome's Network console I can also see that the browser received the right response. However, neither the console.log or the alert are firing. Nothing in the success or error methods is executed either. Does anyone see what's going wrong?
View
$(document).ready(function ($) {
//Determine which links to show in navbar
window.onload = function () {
$.ajax({
type: 'GET',
url: '#Url.Action("CheckSecurity","Home")',
dataType: 'json',
succcess: function (data) {
console.log(data);
alert(data);
if (data == "admin") { $('#adminLink').show(); }
else if (data == "IT") { $('#ITLink').show(); }
else if (data == "viewer") { $('#viewerLink').show(); }
else if (data == "modifier") { $('#modifierLink').show(); }
},
error: function (data) {
alert("error");
}
});
};
Controller
[HttpGet]
public JsonResult CheckSecurity()
{
if (Security.IsAdmin(User)) return Json("admin", JsonRequestBehavior.AllowGet);
if (Security.IsItSupport(User)) return Json("IT", JsonRequestBehavior.AllowGet);
if (Security.IsViewer(User)) return Json("viewer", JsonRequestBehavior.AllowGet);
if (Security.IsModifier(User)) return Json("modifier", JsonRequestBehavior.AllowGet);
return Json("NA", JsonRequestBehavior.AllowGet);
}
Here are a couple screen shots of the Network and regular console in Chrome. Bother are from after I've stepped through the controller method and the program has returned a value back to the browser.
Network Console
Standard Console
There is an extra c in your
succcess:
So the response is a 200 request , but because you have no mapping for success defined, it is just never logged
It is success instead of succcess
NealR
Deprecation Notice:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks
will be deprecated in jQuery 1.8. To prepare your code for their
eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always()
instead.
Check the done, fail and always callbacks below.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
}).fail(function (data) {
debugger;
}).always(function(data) {
alert("complete");
});
.ajax().always(function(a, textStatus, b){});
Replaces method .complete() which was deprecated in jQuery 1.8.
In response to successful transaction, arguments are same as .done() (ie. a = data, b = jqXHR) and for failed transactions the arguments are same as .fail() (ie. a = jqXHR, b = errorThrown).
This is an alternative construct for the complete callback function above. Refer to deferred.always() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).always(function(data) {
alert("complete");
});
.ajax().done(function(data, textStatus, jqXHR){});
Replaces method .success() which was deprecated in jQuery 1.8.
This is an alternative construct for the success callback function above. Refer to deferred.done() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
});
.ajax().fail(function(jqXHR, textStatus, errorThrown){});
Replaces method .error() which was deprecated in jQuery 1.8.
This is an alternative construct for the complete callback function above. Refer to deferred.fail() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).fail(function (data) {
debugger;
});
Check here for more details
Check here for the documentation details

AJAX POST to MVC Controller showing 302 error

I want to do AJAX POST in my MVC View. I've written the following:
Script Code in View
$('#media-search').click(function () {
var data = { key: $('#search-query').val() };
$.ajax({
type: 'POST',
url: '/Builder/Search',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('.builder').empty();
alert("Key Passed Successfully!!!");
}
});
});
Controller Code
[HttpPost]
public ActionResult Search(string key)
{
return RedirectToAction("Simple", new { key=key });
}
But on AJAX POST I am getting the 302 found Error
The '302' response code is a redirect. Your controller action explicitly returns a RedirectToAction, which simply returns a 302. Since this redirect instruction is consumed by your AJAX call and not directly by your browser, if you want your browser to be redirected, you will need to do the following:
$.ajax({
type: 'POST',
url: '/Builder/Search',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.redirect) {
window.location.href = data.redirect;
}
$('.builder').empty();
alert("Key Passed Successfully!!!");
}
});
If not, you'll need to return something more meaningful than a redirect instruction from your controller.

how do I get the form data in a javascript object so I can send it as the data parameter of an $.ajax call

How to return json after form.submit()?
<form id="NotificationForm" action="<%=Url.Action("Edit",new{Action="Edit"}) %>" method="post" enctype="multipart/form-data" onsubmit='getJsonRequestAfterSubmittingForm(this); return false;'>
<%Html.RenderPartial("IndexDetails", Model);%>
</form>
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").submit(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
I guess what you're actually looking for is not the Submit method, but how to serialise the form data to a json object. To do this you have to use a helper method like here: Serialize form to JSON
Use this instead of running the submit() method, and you'll be fine.
Also, this question is a duplicate of this (even though the question text, and the title are completely misleading): Serialize form to JSON with jQuery
Posting the jQuery extender, just in case, so that it doesn't get lost :)
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
After you have this in your page, you can update your ajax call with this:
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").serializeObject(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
UPD: If you want to POST the form, then get the response as a json object, and do another ajax call.. then you should look at the jquery.form plugin. you will be able to post your form using an ajax call, then get the response, and run some js when it will return.

Sending String Data to MVC Controller using jQuery $.ajax() and $.post()

There's got to be something I'm missing. I've tried using $.ajax() and $.post() to send a string to my ASP.NET MVC Controller, and while the Controller is being reached, the string is null when it gets there. So here is the post method I tried:
$.post("/Journal/SaveEntry", JSONstring);
And here is the ajax method I tried:
$.ajax({
url: "/Journal/SaveEntry",
type: "POST",
data: JSONstring
});
Here is my Controller:
public void SaveEntry(string data)
{
string somethingElse = data;
}
For background, I serialized a JSON object using JSON.stringify(), and this has been successful. I'm trying to send it to my Controller to Deserialize() it. But as I said, the string is arriving as null each time. Any ideas?
Thanks very much.
UPDATE: It was answered that my problem was that I was not using a key/value pair as a parameter to $.post(). So I tried this, but the string still arrived at the Controller as null:
$.post("/Journal/SaveEntry", { "jsonData": JSONstring });
Answered. I did not have the variable names set correctly after my first Update. I changed the variable name in the Controller to jsonData, so my new Controller header looks like:
public void SaveEntry(string jsonData)
and my post action in JS looks like:
$.post("/Journal/SaveEntry", { jsonData: JSONstring });
JSONstring is a "stringified" (or "serialized") JSON object that I serialized by using the JSON plugin offered at json.org. So:
JSONstring = JSON.stringify(journalEntry); // journalEntry is my JSON object
So the variable names in the $.post, and in the Controller method need to be the same name, or nothing will work. Good to know. Thanks for the answers.
Final Answer:
It seems that the variable names were not lining up in his post as i suggested in a comment after sorting out the data formatting issues (assuming that was also an issue.
Actually, make sure youre using the
right key name that your serverside
code is looking for as well as per
Olek's example - ie. if youre code is
looking for the variable data then you
need to use data as your key. –
prodigitalson 6 hours ago
#prodigitalson, that worked. The
variable names weren't lining up. Will
you post a second answer so I can
accept it? Thanks. – Mega Matt 6 hours
ago
So he needed to use a key/value pair, and make sure he was grabbing the right variable from the request on the server side.
the data argument has to be key value pair
$.post("/Journal/SaveEntry", {"JSONString": JSONstring});
It seems dataType is missed. You may also set contentType just in case. Would you try this version?
$.ajax({
url: '/Journal/SaveEntry',
type: 'POST',
data: JSONstring,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
Cheers.
Thanks for answer this solve my nightmare.
My grid
..
.Selectable()
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.Render();
<script type="text/javascript">
function onRowSelected(e) {
id = e.row.cells[0].innerHTML;
$.post("/<b>MyController</b>/GridSelectionCommand", { "id": id});
}
</script>
my controller
public ActionResult GridSelectionCommand(string id)
{
//Here i do what ever i need to do
}
The Way is here.
If you want specify
dataType: 'json'
Then use,
$('#ddlIssueType').change(function () {
var dataResponse = { itemTypeId: $('#ddlItemType').val(), transactionType: this.value };
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocationList", "../InventoryDailyTransaction")',
data: { 'itemTypeId': $('#ddlItemType').val(), 'transactionType': this.value },
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlStoreLocation').get(0).options.length = 0;
$('#ddlStoreLocation').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlStoreLocation').get(0).options[$('#ddlStoreLocation').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you do not specify
dataType: 'json'
Then use
$('#ddlItemType').change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("IssueTypeList", "SalesDept")',
data: { itemTypeId: this.value },
cache: false,
success: function (data) {
$('#ddlIssueType').get(0).options.length = 0;
$('#ddlIssueType').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlIssueType').get(0).options[$('#ddlIssueType').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you want specify
dataType: 'json' and contentType: 'application/json; charset=utf-8'
Then Use
$.ajax({
type: 'POST',
url: '#Url.Action("LoadAvailableSerialForItem", "../InventoryDailyTransaction")',
data: "{'itemCode':'" + itemCode + "','storeLocation':'" + storeLocation + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlAvailAbleItemSerials').get(0).options.length = 0;
$('#ddlAvailAbleItemSerials').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlAvailAbleItemSerials').get(0).options[$('#ddlAvailAbleItemSerials').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again.");
}
});
If you still can't get it to work, try checking the page URL you are calling the $.post from.
In my case I was calling this method from localhost:61965/Example and my code was:
$.post('Api/Example/New', { jsonData: jsonData });
Firefox sent this request to localhost:61965/Example/Api/Example/New, which is why my request didn't work.

Resources