How to add a body to the ajax request of select 2? - drop-down-menu

I would like to mimic a post to a URL with the body type of plain text (such as "select * from table") using a Select2 box, but where do i define the body that I want to post?
$("#sales_ids").select2({
placeholder: "Select your Partners",
multiple: 'multiple',
ajax: {
url: 'http://www.google.com/,
dataType: 'json',
type: 'post',
multiple: 'multiple',
allowclear: 'true',
processResults: function p(data){
var mapped = $.map(data, function(obj) {
obj.text = obj.text || obj.name;
obj.id = obj.id || obj.salesId;
return obj;
})
return {
results: mapped
}

$.ajax({
url: 'URL',
type: 'POST',
dataType: 'json',
async: false,
// Data Goes Here
data: 'select * from table'
contentType: 'test/plain'
success: function (data, textStatus, xhr) {
// Success Code
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Database');
}
});

Related

.NET 6 (Core) MVC application - problem with ajax call

.NET 6 (Core) MVC application. In view I have:
$("#mybtn").click(function () {
$.ajax({
type: "POST",
url: "/MyController/GetCustomer",
data: JSON.stringify({ 'id': 5 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response, textStatus, xhr) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
and in controller:
[HttpPost]
public JsonResult GetCustomer(int? id) {
if (id == null) {
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { msg = "Error in the request." });
}
var customer = _db.Customers.Find(id);
return Json(customer);
}
It gets to the action method in controller, but the id is always null...
What am I doing wrong?
It gets to the action method in controller, but the id is always
null... What am I doing wrong?
To begin with, you don't need to use JSON.stringify({ 'id': 5 }) as { 'id': 5 } already in json format. In addition, contentType: "application/json; charset=utf-8", is uncessary as well, Instead, you can do as following:
Correct Format:
$("#mybtn").click(function () {
$.ajax({
url: "/MyController/GetCustomer",
type: "POST",
data: { 'id': 5 },
dataType: "json",
success: function (response, textStatus, xhr) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
Note: You are getting null in your controller because of using contentType: "application/json; charset=utf-8", and additional, Json parsing here JSON.stringify() these are only valid when you are sending parameter as object fashion. Just get rid of those two part, you are done.
Output:

ASP.NET MVC AJAX POST ValidateAntiForgeryToken

With my code i get a internal Server error:
#using (Html.BeginForm("", "Manage", FormMethod.Post, new { role = "form"}))
{
#Html.AntiForgeryToken()
}
<script>
function Like(id) {
var requestData = {
profileId: id,
__RequestVerificationToken: $('[name=__RequestVerificationToken]').val(),
};
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: JSON.stringify(requestData),
dataType: "json",
contentType: 'application/json; charset=utf-8',
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Like(string profileId)
{ ... }
If i remove [ValidateAntiForgeryToken] everything works fine, but i lose the sercurity. How can i fix the internal server error?
I see in fiddler SyntaxView 2 requests:
/Manage/Like
{"profileId":13,"__RequestVerificationToken":"jH2ofYlcTiHl8lixW_ANEHOg5KgwRh5Xl43lQfGkDFh55jX-x5cmz4RfPtbDfu92oQsTM7zsop83ldfbxMdIIELYZ0kfByFcXjUp-5mwyKZcQzjXP2gy6qW0iQOtLsqaDjFSzoxnyqM2MD42CbItzw2"}
/Manage
__RequestVerificationToken=MNiKOJHZg7BGaTNccOjrR2Obf_nPhKfcwIPZVBUl53G368n5euzB4y1htH47VKg3V3mHfxkjYZDz6iPepQ7jpeXGARtlj6vV74B8zQbp4by9JR4Rcz4sHANm3WHb6WAXaLcsnFvWJth_8c98XKda5w2
Taking this from a sim. question here include antiforgerytoken in ajax post ASP.NET MVC
function Like(id) {
var form = $('form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: { __RequestVerificationToken: token, profileID: id },
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}

Simple jQuery / Ajax error

I have this code:
var custID = 1;
$.ajax({
url: 'php/viewCustomer.php',
type: 'GET',
data: '{custID: ' + custID + '}',
dataType: 'json',
cache: false,
beforeSend: function () {
$('#display').append('<div id="loader"> Lodaing ... </div>');
},
complete: function () {
$('#loader').remove();
},
success: function (data) {
//do something
},
error: function () {
alert('could not process');
}
});
there is an error and alerts the error message could not process, so I tried to debug it like this:
var custID = 1;
$.ajax({
url: 'php/viewCustomer.php',
type: 'GET',
data: '{custID: ' + custID + '}',
dataType: 'json',
cache: false,
beforeSend: function () {
$('#display').append('<div id="loader"> Lodaing ... </div>');
},
complete: function () {
$('#loader').remove();
},
success: function (data) {
//do something
},
error: function (jqXHR) {
alert('Error: ' + jqXHR.status + jqXHR.statusText);
}
});
which outputs:
200 OK
so if it is ok, why on earth is it executing the error: function. Confused, please help.
Your data string is incorrectly formatted, if you are intending it to be a JSON object. There was a previous question about this: Jquery passing data to ajax function
Instead, try:
data: JSON.stringify({custID: custID}),
The format is (key):(variable). My previous answer have placed quotes around the variable, which is not necessary.

display values returned by json

I have simple question to display data on html page. Following code displays array of json data on screen. but, I want to display it by each element such as "url", "img_url" and so on.
could you please let me know who to do it ?
ajax code
var dataString = 'url=' + pathname + '&img_name=' + img_name + "&tag=" + tag;
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
//handleError();
alert("error");
} else {
var data = xhr.responseText;
$('#tt').html("<div id='message'></div>");
$('#message').html(data);
}
}
});
json return
{"cid":"14","url":"http:\/\/localhost\/","img_url":"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg","img_name":"mat_173317134c.jpg","html":"<div id=\"hotspot-19\" class=\"hs-wrap hs-loading\">\r\n<img src=\"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg\">\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"95\" data-y=\"64\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nasdf\r\n<\/div>\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"168\" data-y=\"53\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nrere\r\n<\/div>\r\n<\/div>\r\n","jscript":""}
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
success: function (data) {
for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}
}
});
I hope this is what you need.

jquery tooltip Getting undefined value

I am getting value through post method when i am add it into variable it is showing the same value but when i accessing the value from the outside. it showing me undefined.
var Trends =this.$elm.data('title.poshytip');
var value;
var path = window.location.pathname;
var name = path.substring(path.lastIndexOf('/') + 1);
var dataToSend='{ID:"'+Trends+'"}';
$.ajax({
type: "POST",
url: "UnitedStatesTrends.aspx/serverside",
data: dataToSend,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function( data )
{
value = data.d;
},
error: function() {
alert('error');
}
})
//here
alert(value);
// here i am getting value=undefined in alert but my value is 'UnitedStates'
this.$inner.append(
typeof content == 'function' ?
content.call(this.$elm[0], function(newContent) {
self.update(newContent);
}) :
//here i am setting the value to tooltip
content == '[title]' ? value : content
);
Well I think, you are forgetting to put a semicolan ; after this
$.ajax({
type: "POST",
url: "UnitedStatesTrends.aspx/serverside",
data: dataToSend,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function( data )
{
value = data.d;
},
error: function() {
alert('error');
}
});

Resources