Parameters to dojo.xhrPost - post

When I use dojo.xhrGet , I use it this way to send more than one parameter via the GET
dojo.xhrGet
({
url:"MyServerPageURL?Param_A="+"ValueA"+"&Param_2="+"Value2",
load: function(data)
{
//do something
},
preventCache: true,
sync: true,
error: function(err)
{
alert("error="+err);
}
});
How could I do similar thing (send more than one parameter) when I have to use the dojo.xhrPost instead?

You do not want to use postData parameter unless you want to send a raw POST string. You normally want to use the 'content' parameter. For example:
dojo.xhrPost({
url: 'http://whatever...',
contents: {
ParamA: 'valueA',
ParamB: 'valueB'
},
load: function(response) {
// ...
}
});
Note: Use 'contents' works for xhrGet also, eliminating the need to build up the query string yourself and append to the URL.

Try to use postData parameter.
E.g:
var myParameters= {"Param_A":"Value_A", "Param_B":"Value_B"};
var xhrArgs = {
url: "postIt",
postData: dojo.toJson(myParameters),
handleAs: "text",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load: function(data) {
},
error: function(error) {
}
}
var deferred = dojo.xhrPost(xhrArgs);

For xhrPOst, it's possible to mention the form name to be posted. thus all your form elements get posted. If you want to pass some additional parameter then use hidden variable in the form that is posted.

Related

Ajax not allowing View rendering

I have a couple of variations on the ajax depending on the flow of interactions on the page. But it's only the variables that changes. here is one of them:
$('#btn_skickaEnkel').bind('click', function () {
$.ajax({
type: 'POST',
url: '/Contact/IntresseAnmälan/',
dataType: 'json',
data: {
Namn: $('#namn').val(),
Mail: $('#mail').val(),
Info: $('#meddelande').val(),
Nivå: $('#nivå').find(":selected").text(),
IsEnkel: true,
Telefon: $('#nr').val(),
ID: function () {
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
return id;
}
},
traditional: true
});
});
In my controller i am unable to redirect or return a different view. At this point the data from JSON is no longer relevant because it's already been saved to DB.
My Controller:
public ActionResult IntresseAnmälan(BokningContainer bokning)
{
db = new DbContext();
//Saving some data to database(removed)
//Just determening the state of container obj.
if (bokning.IsEnkel)
{
//Geting som information from db (removed)
//Creating a mail (removed)
email.Send(bokning.Namn, bokning.Mail, body);
}
else
{
}
//db.SaveChanges();
//This part is not working, I think it's beacuase of the Ajax
return View("IntresseAnmälan");
}
The view is not rendered and I think it's related to the ajax. The view is simply not rendered. Is there some way to force returning it and ignoring the ajax? As I said the data is no longer needed because the content is already saved to the DB.
You cannot render view on ajax call,simply you can use form post method or just redirect it to desired action on "succcess" of ajax call as below:
$('#btn_skickaEnkel').bind('click', function () {
$.ajax({
type: 'POST',
url: '/Contact/IntresseAnmälan/',
dataType: 'json',
data: {
Namn: $('#namn').val(),
Mail: $('#mail').val(),
Info: $('#meddelande').val(),
Nivå: $('#nivå').find(":selected").text(),
IsEnkel: true,
Telefon: $('#nr').val(),
ID: function () {
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
return id;
}
},
traditional: true,
success: function(result) {
window.location.href = '#Url.Action("action", "Controller")';
}
});
});
I couldn't believe my eyes when I figured out this "Bugg". The problem was that I, at some point, changed the submit to a button. So the form was never submiting. Well, at least I learnt a bit about views and Ajax.
Sorry for taking your time.

Prevent $.ajaxStart() from being executed during jquery-ui autocomplete

I'm using jquery-ui autocomplete on a page I'm creating. On the same page I have some ajax events going on. During the other ajax events I'm adding an overlay to my page, so that all the links on the website aren't clickable anymore for the user. I don't want that to happen during the autocomplete.
autocomplete:
$(function() {
$( "#search_input" ).autocomplete({
source: '/search_autocomplete/',});
});
ajax:
$.ajax({
url: "/ajax_login/",
login_user: $("#login_user").val(),
password: $("#login_password").val(),
});
ajaxStart:
$("#loading_gif").ajaxStart(function() {
$("#overlay").show();
$(this).show();
});
To prevent the ajaxstart function from being executed during the ajax events where it's not necessary. I add
global:false,
to the corresponding ajaxfunctions. How can I do something similar during the autocomplete without changing the jquery-ui source?
For this you have to omit the shorthand call with source and change the call like this.
$('#search_input').autocomplete({
source: function (request, response) {
var DTO = { "term": request.term };
//var DTO = { "term": $('#search_input').val() };
$.ajax({
data: DTO,
global: false,
type: 'GET',
url: '/search_autocomplete/',
success: function (jobNumbers) {
//var formattedNumbers = $.map(jobNumbersObject, function (item) {
// return {
// label: item.JobName,
// value: item.JobID
// }
//});
return response(jobNumbers);
}
});
}
//source: '/search_autocomplete/'
});
The advantage of this long-hand method is
You can pass more than one parameter. Also the parameter name should not have to be term.
The short-hand notation expects an array of strings. Here you could return an array of objects also.
If you want $.ajax() to work a certain way most of the time but now all the time, then you probably shouldn't change its default behavior.
I recommend creating a function that wraps an ajax request in a function that enables and disables the overlay at the appropriate times. Call this function where you want the overlay to be used, and use plain $.ajax() for your autocomplete.
I would agree that naveen's answer is the best solution. In my case the vast amount of code that would require changing wasn't cost effective as we're in the process of doing a re-write and we needed a short term solution.
You can override the ajax call in jQuery UI, I copied the source for the _initSource function call that handles the AJAX request. Then simply added the global: false to the $.ajax options. The code here is based on jquery-ui 1.9.2, you may have to find the correct source for your version.
$.ui.autocomplete.prototype._initSource = function () {
var array, url,
that = this;
if ( $.isArray(this.options.source) ) {
array = this.options.source;
this.source = function( request, response ) {
response( $.ui.autocomplete.filter( array, request.term ) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
if ( that.xhr ) {
that.xhr.abort();
}
that.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
global: false,
success: function( data ) {
response( data );
},
error: function() {
response( [] );
}
});
};
} else {
this.source = this.options.source;
}
};

Url pathname issue in Ajax Post

In development I make an Ajax post which works in development. However when I put it on the Test server it doesn't work because IIS has assigned the application a subfolder, and this is missing in my development environment.
I have found work around (see below) but I am the first to admit this should not be the solution, as I have to remember to call a function for the url everytime I make an Ajax call.
There must be a better way.
However the code will show you what I am fixing;
function OperationsManagerFlagClickFunc(userId) {
$.ajax({
url: GetUrl("/Users/UpdateOperationsManagerFlag"),
type: "POST",
data: { "userId": userId },
success: function (data) { }
});
}
function GetUrl(path) {
var pathArray = window.location.pathname.split('/');
if (pathArray[1] === "ITOC")
return "/ITOC" + path;
else
return path;
}
If you have your javascript in .aspx file, you can generate url like this:
function OperationsManagerFlagClickFunc(userId) {
$.ajax({
url: "<%= Url.Action("UpdateOperationsManagerFlag","User") %>",
type: "POST",
data: { "userId": userId },
success: function (data) { }
});
}
Why not have a variable defined separately, like siteUrl, that will hold your site's url, with different values on the 2 servers?
Then just do:
url: siteUrl + "/Users/UpdateOperationsManagerFlag"

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