Ive tried a couple out-of-the-box ways trying to get my value into my ajax but everytime I get js error's. Hopefully one of you can help.
I have the following JQuery Ajax:
$("#usertasklist").click(function () {
$('#basicModal4').modal('hide');
$.ajax({
type: "GET",
url: "/Home/GetAjaxUserTasksExecuted",
data: { filterdate: variable1 },
datatype: "html",
success: function (data) {
console.log("Succes!");
var $titleDiv = $('#Modal5Label');
$titleDiv.replaceWith("<h3><b>User Tasks Executed</b></h3>");
var $detailDiv = $('#superdatadivthing3');
$detailDiv.replaceWith(data);
},
error: function () {
console.log("Error!");
},
complete: function () {
$('#basicModal5').modal('show');
console.log("Complete!");
}
});
});
And a viewbag in my controller
Session["Usercode"];
How can I pass the value from my view bag to replace "variable1" in the data section of my ajax call?
How about getting the data from a container?
HTML-example
<table id="YOURDIVHERE">
<tr>
<td>
<span>data which i will use</span>
</td>
</tr>
</table>
Your Ajax-call
$("#usertasklist").click(function () {
$('#basicModal4').modal('hide');
var data = innerXHTML($('#YOURDIVHERE').attr('id'));
$.ajax({
type: "GET",
url: "/Home/GetAjaxUserTasksExecuted",
data: { filterdate: data },
datatype: "html",
success: function (data) {
console.log("Succes!");
var $titleDiv = $('#Modal5Label');
$titleDiv.replaceWith("<h3><b>User Tasks Executed</b></h3>");
var $detailDiv = $('#superdatadivthing3');
$detailDiv.replaceWith(data);
},
error: function () {
console.log("Error!");
},
complete: function () {
$('#basicModal5').modal('show');
console.log("Complete!");
}
});
});
Related
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);
},
});
}
I want to delete a row from the table, but the success part of ajax does not execute.
function fn_delete() {
$("a.delete").click(function () {
idProduct = $(this).parents("tr").find("td").eq(1).html();
$.ajax({
type: "POST",
url: "DeleteProduct",
data: { idProduct },
success: function () {
$(this).parents("tr").fadeOut("normal", function () {
$(this).remove();
}
});
});
};
this inside your success callback will not be the same as this in the code that makes the ajax call, unless you explicitly set the context:
$.ajax({
context: this,
data: ...
});
I don't think this is giving the value that you're expecting.
Try this:
function fn_delete() {
$("a.delete").click(function () {
idProduct = $(this).parents("tr").find("td").eq(1).html();
var myRow = $(this).parents("tr");
$.ajax({
type: "POST",
url: "DeleteProduct",
data: { idProduct },
success: function () {
$(this).parents("tr").fadeOut("normal", function () {
myRow.remove();
});
}
});
});
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"
Can anybody explain what's wrong in my code, I am new to knockout... So, initially I receive json data from database and it works. Than when I click 'Add some' I want to add(push) same data from database to my observable array. The code below obviously doesn't work. Thanks.
Error: Unable to process binding "text: function (){return AdId }"...
HTML:
<div data-bind="foreach: Ads">
<p data-bind="text: AdId"></p>
</div>
<div data-bind="click: addSome">Add some</div>
MODEL:
function AdListModel() {
var self = this;
self.Ads = ko.mapping.fromJS([]);
self.result = function (model) {
ko.mapping.fromJS(model, self.Ads);
}
self.InitialData = function () {
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.result(data); <---- works
}
});
}
self.addSome = function () {
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.Ads.push(data); <---- doesn't work
},
});
};
self.InitialData();
}
ko.applyBindings(new AdListModel());
I tried self.Ads.push(ko.mapping.fromJS(data)) - didn't work.
It seems from the error message, that your model does not have an AdId property.
Can you add a dump of the JSON model returned by your API?
Edit
Your Ads property should be an ko.observableArray() instead of ko.mapping.fromJS([]):
function AdListModel() {
var self = this;
self.Ads = ko.observableArray([]);
self.result = function (model) {
ko.mapping.fromJS(model, self.Ads);
}
Edit 2
And you have to map the data before pushing it:
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.Ads.push(ko.mapping.fromJS(data));
},
});
Edit 3
If your JSON looks like this:
[
{"AdId":1,"AdContent":"test1"},
{"AdId":2,"AdContent":"test2"}
]
Then it is an Array and you have to iterate over each entries:
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
data.forEach(function(d) {
self.Ads.push(ko.mapping.fromJS(d));
});
},
});
I have this script that adds elements with data by a get json function.
$(document).ready(function() {
ADD.Listitem.get();
});
It basicly adds a bunch of html tags with data etc. The problem I have is following:
$(document).ready(function() {
ADD.Listitem.get();
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
-
get: function(web) {
AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null, AST.Listitem.renderListitem);
},
renderListitem: function(data) {
$("#Listitem-template").tmpl(data["ListItemResults"]).prependTo(".ListItem-section-template");
}
and here is the json get:
ADD.Utils.JSON.get = function (url, data, onSuccess) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
success: onSuccess,
error: ADD.Utils.JSON.error,
converters: { "text json": ADD.Utils.JSON.deserialize }
});
}
The array each loop is not running beacuse the get method is not finished with rendering the Listitem-section-item-title selector so it cant find the selector.
Is there any good solutions for this?
You could change your functions to return the promise given by $.ajax :
ADD.Utils.JSON.get = function (url, data) {
return $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
converters: { "text json": ADD.Utils.JSON.deserialize }
}).fail(ADD.Utils.JSON.error);
}
get: function(web) {
return AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null).done(AST.Listitem.renderListitem);
},
So that you can do
$(document).ready(function() {
ADD.Listitems.get().done(function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Callback:
$(document).ready(function() {
ADD.Listitem.get(url,data,function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Without callback:
If you cant get the get method to take a callback or return a promise then I think the best way will be to check when its done.
$(document).ready(function() {
ADD.Listitem.get();
var timer = setInterval(function(){
if ($("#thingWhichShouldExist").length>0){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
clearInterval(timer);
}
},50);
});
Retrieve the values and on success, call a function which will push the values into the array.
Also, arr.push($(this.text())); should be arr.push($(this).text());.