i have an ajax call
$.ajax({
url: '<%=Url.Action("SaveDetails","Survey") %>',
dataType: 'JSON',
cache: false,
data: { Id: selectedRow.Id, Value: surveyValue, FileName: filename, FileGuid: fileguid },
success: function(data) {
...
}
});
where the surveyValue is a html string. this call doesn't work. but is i change the surveyValue to an ordinary text i works fine.
how can i pass the html to the server?
I'm guessing you'll need to encode it:
data: { ... Value: encodeURIComponent(surveyValue), ... }
And on the server side:
string value = Server.UrlDecode(surveyValue);
Related
how can I send the var lang to the controller so I can use it in partiel. here is my shot:
$("#search-select").on("click", function() {
var lang = $('#search-select').dropdown('get value');
$.get({
url: translations_url
data: lang,
success: function(){
console.log('data sent');
}
});
});
EDIT
current code:
$("#search-select").dropdown();
$("#search-select").on("click", function() {
var lang = $('#search-select').dropdown('get value');
$.get({
url: "#{translations_url}",
dataType: "script",
data: {
lang: lang
}
});
});
problem: params[:lang] still don't work in controller
Set correct _path to your post method:
$.ajax({
url: '<%= controller_path %>', method: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
data: { lang: lang },
dataType: 'json',
success: function (data) {
console.log(data);
}
});
Now you can work with lang in your controller
def method
params[:lang] # do something
answer = 'Then, you can return some data to view'
respond_to do |format|
format.json { render json: answer }
end
end
you're missing , after url: translations_url, also if you can send data as JSON with key and value, like data: {lang: 'value'}, also you don't need to specify method name if you're using GET, see the below example
$.ajax({
url: translations_url,
data: {lang: 'value'},
success: function(){
console.log('data sent');
}
});
if you need to use POST Method then include method: 'post' incase jquery ajax method doesn't call js.erb file you need to add dataType: 'script'
You can't use route path helpers on the frontend. But you can send proper URL from backend to frontend via data-attribute:
#search-select{ data: { path: translations_url } }
And then in your js:
$("#search-select").on("click", function() {
var url = $(this).data('path'),
data = { lang: $(this).dropdown('get value') };
$.get({
url: url,
data: data,
success: function(){
console.log('data sent');
}
});
});
I'm using ajax to pull in data from a php file (which returns json).
I'm wondering, can you have results pulled from Ajax and loads on click without having to search? so essentially you click the field, it drops down with all the elements from Ajax. Couldn't find in the documentation.
Code:
jQuery('.producttypesajax').select2({
allowClear: true,
placeholder: {
id: '',
text: 'Search by Product Type'
},
ajax: {
url: base + '/appProductTypeSearch.php',
dataType: 'json',
delay: 250,
data: function( params ) {
return {
q: params.term // search term
};
},
processResults: function( data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1
});
jQuery('.producttypesajax').on('select2:select', function (e) {
var data = e.params.data;
});
https://select2.org/data-sources/ajax
I believe there's no native solution for this, but I managed to do it somehow.
Since Select2 accepts Arrays as a data source, you can make an Ajax request returning your Json object and use it as an "Array".
Sample code:
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function (jsonObject){
$('#mySelect').select2({ data: jsonObject });
}
});
It worked for me. Hope it helps.
I am trying to post some data using Ajax, but it is not getting through when using content type of application/json (HTTP/1.1 406 Not Acceptable), however if I change the content type to 'application/x-www-form-urlencoded' then it does work.
Any ideas?
Ajax code extract:
$.ajax({
type: "POST",
data: {"hello":"test"},
url: "http://workingUrl/controller",
contentType : 'application/json',
cache: false,
dataType: "json",
.....
Web API 2:
public IHttpActionResult Post(testModel hello)
{
/// do something here
}
Model:
public class testModel
{
public string hello {get;set;}
public testModel()
{ }
}
Fiddler:
HTTP/1.1 406 Not Acceptable (In the IDE, I have a breakpoint in the Post method which is not hit).
I have tried adding a formatter to WebAPi.config, but no luck
config.Formatters.Add(new JsonMediaTypeFormatter());
Try with this JSON.stringify(TestData) as shown below -
var TestData = {
"hello": "test"
};
$.ajax({
type: "POST",
url: "/api/values",
data: JSON.stringify(TestData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Output -
I've never specified contentType when I've done this and it's always works. However, if it works when you use 'application/x-www-form-urlencoded' then what's the problem?
I do see a couple thing off in your ajax. I would do this
$.ajax({
type: "POST",
data: {hello:"test"},
url: "http://workingUrl/controller/Post",
cache: false)}
For data, maybe quotes around the variable name will work but I've never had them there.
Next, the url in the ajax call doesn't have the name of your controller action. That needs to be in there.
I need to pass a json data to the controller. hence i have created a ajax post. But it is not calling the action method.
function DeleteRow(postData) {
$.ajax({
url: '#Url.Action("DeleteGridRow","Project")',
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
data: JSON.stringify(postData),
success: function (data) {
}
});
}
My Actionmethod
[HttpPost]
public JsonResult DeleteGridRow(string postData)
{
return Json(null);
}
Please help
If you have separated your javascript file from your cshtml or vbhtml page, then this is not going to work. Your URL would be interpreted wrongly. You should pass URL where you are submitting to your function DeleteRow. Something like this:
$("#myForm").submit(function() {
var url = $(this).attr("action");
var data = Use your method to collect data or $(this).serialize();
DeleteRow(url, data);
});
function DeleteRow(url, postData) {
$.ajax({
url: url,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
data: JSON.stringify(postData),
success: function (data) {
}
});
Something like this should work.
I am doing a simple $.ajax request:
$.ajax({
type: "POST",
url: "/Run/" + param1 + "/" + param2,
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
If my param2 value is like http://localhost/pub/file?val1=Some Text&val2=Some Text then encoding done using escape(param2), encodeURI(param2), encodeURIComponent(param2) doesn't help. And I get following ERROR -->
HTTP Error 400.0 - Bad Request
ASP.NET detected invalid characters in the URL
My Questions -->
How should I encode param2 ?
What is the maximum length of request URL in $.ajax call ?
Is request URL max length dependent on type of browser from which request is made ?
I have observed that if I use Ajax.ActionLink then I do not need to encode the parameters passed to action and I can pass parameters with length > 10,000 characters as well. But I do not know how to make an explicit call using Ajax.ActionLink from my java script. I need to click on that actionlink to make call through Ajax.ActionLink.
Benefits of Ajax.actionLink-->
Please see the length of parameter categoryName passed to action using Ajax.ActionLink (This is mine observation)
Such big parameters should be posted and not sent in the URL.
$.ajax({
type: 'POST',
url: '/Run',
data: { param1: param1, param2: param2 },
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
This will automatically handle parameter encoding. If you absolutely insist on sending them in the url you may declare a global javascript variable that will hold the url to call:
<script type="text/javascript">
var url = '<%= Url.Action("Run"), new { param1 = "value1", param2 = "value2" } %>';
$(function() {
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
});
</script>