ajax success response change as #html.raw - javascript

I have following jquery code in my Razor viewpage
$(document).ready(function () {
var grouplistvalues = #Html.Raw(Json.Encode(Session["grouplist"]));
$("#nsline").click(function () {
alert(grouplistvalues)
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
alert(response)
},
error: function ()
{
}
});
});
$("#ewline").click(function () {
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
},
error: function ()
{
}
});
});
in above grouplistvalues its taking session as html raw
when I alert it on #nsline click function I can see it,
in above function I'm calling to ajax function and above grouplistvalues value updating
once I alert it on #nsline click function success response I can see a alert like folllowing
since this(grouplistvalues value) 1,2,.. changing as [1,2..] I cannot call to other ajax function in #ewline click function since parameter difference,
this is the above common ajax call
[HttpPost]
public JsonResult SetupGroups(long[] grouplist)
{
Session["grouplist"] = null;
List<long> groupList = new List<long>();
foreach (var groupitem in grouplist)
{
groupList.Add(groupitem);
}
long[] grouparray = groupList.ToArray();
Session["grouplist"] = grouparray;
return Json(grouparray);
}
}
Though I have two click functions its work with only the first click(ewline or nsline only the first time)
How to solve this

It was the dataType in your ajax request. It should be json:
dataType: "json"

Related

Display error on ajax response from php function

I have some ajax call like this
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
alert(data);
},
});
}
And php function like this
function export_database(){
return $response;
}
The problem is in that response I have something like this
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3fa58ee1-48bf0cb9f60bfa25."
}
I want to alert only title, but when i try data.title , i got undefine
Do I must encode or decode something, thanks?
This is what you need. Just access the object by data.title and it will show in the alert()
You need to define dataType as json in your request.
If its does not work then use JSON.parse(data) like this:
var response = JSON.parse(data)
alert(response.title)
Try below:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: 'json'
data: data,
beforeSend: function () {},
success: function (data) {
alert(data.title);
},
error: function(error){
//Error
alert(error.title)
}
});
}
Hope this helps.
Try Below:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
var parsedData = jQuery.parseJSON(data)
alert(parsedData.title);
},
});
}
You have to use JSON.parse() for accessing data objects Like this:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
var res = JSON.parse(data)
alert(res.title);
},
});
}

Removing response from AJAX call

I'm currently getting a response from an AJAX call, the response is added to the inner HTML of an ID, is it possible to create a function which only removes this response?
function get_chat(name){
var name = name;
$.ajax({
type: 'post',
url: 'getchat.php',
data: {
name_id:name
},
success: function (response) {
messenger.innerHTML = response;}
});
}
I see your setting the innerHTML attribute. In that case, you just have to reset it like this:
function get_chat(name){
var name = name;
$.ajax({
type: 'post',
url: 'getchat.php',
data: {
name_id:name
},
success: function (response) {
messenger.innerHTML = response;}
});
}
function remove_chat() {
messenger.innerHTML = "";
}

Can't call the webmethod using user control

I'm creating a modal when I click I will pass the id and action to the serverside to save a logs.
Here is my sample code but can't get it to work. I'm using a usercontrol.
$("a.modal_show2").click(function () {
$(this).each(function () {
if ($(this)) {
var storecheckid = $(this).attr("id");
$.ajax({
type: "POST",
url: "TalkTalk.aspx/saveLogs",
data: {
action: 'video_tag',
clickedlinktag: storecheckid
},
dataType: "text",
success: function (response) {
console.log(response);
}
});
}
});
});
[System.Web.Services.WebMethod]
public static string saveLogs(string action, string clickedlinktag)
{
DataHelper.InsertLogs("TalkTalk", Convert.ToInt16(clickedlinktag), Convert.ToInt16(TwwId));
return clickedlinktag;
}
Thanks
data: JSON.stringify({ action: 'video_tag', clickedlinktag: storecheckid })
// response is a wrapper for your data. your data is in `d`.
success: function (response) {
console.log(response.d);
}

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

500 error coming when I run my ajax function

I am new to MVC and trying out the ajax functionality on my website. Whenever, I run my ajax function it returns 500 in alert.
This is my controller code
[HttpPost]
public ActionResult JsonNewsfeed(int id)
{
var db = new dekhosaleEntities1();
sale s = db.sales.First(m => m.sale_id == id);
List<sale> sale1 = db.sales.ToList();
saleviewmodel model = new saleviewmodel
{
currentsale = s,
Sales = sale1
};
return Json(model);
}
This is my Jquery ajax function
$('.b1').click(function () {
$.ajax({
type: "POST",
dataType: 'json',
url: '#Url.Action("JsonNewsfeed", "Home")',
data:"{ id: 5}",
success: function (data) {
alert(data);
},
error: function (response) {
alert(response.status);
}
});
});
public ActionResult JsonNewsfeed(int id)
{
try
{
....logic here....
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//TODO: log exception
return new HttpStatusCodeResult(401, ex.Message);
}
}
you could also return like this instead:
return Content(jsonObject.ToString(), "application/json");
or
return Content("Your message",...
Then in your ajax call change the success to:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/someDir/someAjaxControllerMethod",
data: jStr,
success: function (json) {
...do something...
var s = JSON.stringify(json);
alert(s);
},
error: function (event) {
alert(event.statusText);
}
});
Try to correct you ajax request ...
like URL...(url: 'Url.Action("JsonNewsfeed", "Home")')
data (data: {id:id}) (if needed check that too)
here is the reference..
Documentation: http://api.jquery.com/jquery.ajax/

Categories

Resources