I'm new to knockout and trying to create my first script which update based on a JSO script which constantly change. The problem is i keep seem to get an unexpected error: Uncaught SyntaxError: Unexpected identifier.
<head>
<script type='text/javascript' src='knockout-3.3.0.js'></script>
<script type="text/javascript">
callService();
var Match = function(){
var self = this;
self.matches = ko.observableArray();
self.ajax = function (uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
error: function (jqXHR) {
console.log("ajax error " + jqXHR.status);
}
};
return $.ajax(request);
}
function callService(){
self.ajax(url + "matchticker.json" + requestData, 'GET').done(function (data) {
self.matches.removeAll();
for(int i = 0; i < data.Result.length; i++){
self.matches.push(..data..);
}
}
}
}
ko.applyBindings(new Match());
</script>
</head>
<body>
<ul class="list-group col-sm-12 col-xs-12" data-bind='foreach: matches'>
<li data-bind="html: match_id"></li>
</ul>
</body>
Many syntax errors here. Next time try linting your code first.
See if it works:
var Match = function(){
var self = this;
self.matches = ko.observableArray();
self.ajax = function (uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
error: function (jqXHR) {
console.log("ajax error " + jqXHR.status);
}
};
return $.ajax(request);
};
function callService(){
self.ajax(url + "matchticker.json" + requestData, 'GET').done(function (data) {
self.matches.removeAll();
for(var i = 0; i < data.Result.length; i++){
self.matches.push(data.Result[i]);
}
});
}
callService();
};
ko.applyBindings(new Match());
Related
How to get All the elements of the Listbox when Button Click event is fired by using ajax call
I am using a function and trying to call the function in ajax call my function is working fine it returning all the elements from the List box when I am trying to bind it with the ajax call its not working i need to call the elements in the code behind:
function responseData2() {
debugger;
var oListbox = $("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data);
});
var jobsheet = data;
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': '" + jobsheet + "'}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
My code-behind data:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object Details4(string selectedJobSheet)
{
try
{
string constr = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("select customer_id,first_name from jobsheetDetails", con))
{
string _data = "";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
_data = JsonConvert.SerializeObject(ds.Tables[0]);
}
return _data;
}
}
}
catch (Exception)
{
throw;
}
}
It seems your variable data was inside the loop. Try to use object method to fix your problem.
function responseData2() {
debugger;
var holder_all_data = [];
var oListbox = $("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data);
holder_all_data.push({
var_name_data : data,
});
});
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': '" + holder_all_data + "'}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
And then next, if you want to get the individual name value which's thrown by AJAX, you should use foreach loop and it should look like this. :D
e.g
foreach( selectedJobSheet as $item ){
var name = $item['var_name_data']; //include the object variable name
console.log(name);
}
Try this:
function responseData2() {
debugger;
var jobsheet = [];
$("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val();
jobsheet.push(data);
alert("The Names are: " + data);
});
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: { "selectedJobSheet": JSON.stringify(jobsheet) },
dataType: "json",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
Code Behind:
[WebMethod]
public void Details4(string selectedJobSheet)
{
List<string> selectedJobSheetList = new List<string>();
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic data = serializer.Deserialize(selectedJobSheet, typeof(object));
foreach (var item in data)
{
selectedJobSheetList.Add(item);
}
}
It seems your data variable is overwritten in a loop and that is the issue. Hope below will help you.
function responseData2() {
var data = [];
var oListbox = $("#submitlistbox2").each(function (i) {
var data[i] = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data[i]);
});
var jobsheet = JSON.stringify(data);
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': " + jobsheet + "}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
Apologies as I have already asked a v. similar question.
I am trying to update a sp list with the following javascript/ajax. It succeeds until it gets to the ajax function, which is where it fails. It goes down the error route and in "alert(err.Message)" it posts "undefined"
Any help appreciated.
<script type="text/javascript">
function updateMultipleListItems(){
var listName="Address Validation";
//CustomerNumber.val("16");
var CustomerNumber="CustNum";
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=ID&$filter=Cust_x0020_Number eq 17",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
alert("1");
var itemType = GetItemTypeForListName(listName);
alert("2");
var ItemId = item.ID;
alert("3");
var item = {
"__metadata": {
"type": 'SP.Data.Address%20ValidationListItem'
},
"assign": "testinput"
};
alert("4");
$.ajax({
url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
console.log('Update Success');
alert("Success");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
},
error: function (data) {
alert("Error");
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
What I'm trying to do:
I am trying to update all records in a list where the cust_number (a column in the list) field is 17 so that assign (another column) = "testinput".
eg:
Cust Number| Assign
17 | testinput
1 |
17 | testinput
So I found out that my metadata type was incorrect. I went to the following url:
sitename/apps/reserve/_api/lists/getbytitle('Address%20Validation')?$select=ListItemEntityTypeFullName
From here I found the correct ListItem type.
Thanks,
Kieran
I'm trying to get data from a Json file using the id from a previous previous ajax call looping through the the second array based on the id gotten from the first
I have tried
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
$('.blog').empty();
for (var i=0; i<n; i++) {
var storytitle = output.data[i].story_view;
var id = output.data[i].titleID;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var n2 = output2.data[0].episode_count;
for (var i=0; i<n2; i++) {
var titles = output2.data[i].title;
console.log(storytitle + " " + titles);
}
}
else {
console.log('faileds');
}
});
}
} else {
console.log('failed');
}
});
});
The storyTitle has a single value and loops through all the titles when i check my console.
I tried debugging and found out the second for-loop was only executed once, after executing request2.done, it goes back to the first for-loop after the first has finish all its loop, it executes the second for-loop.
I don't know where am missing it.I need help with this.
Finally solved the problem...Changed my code to...
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var CLASS = this.story_view;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
console.log(id + " " + id2);
})
}
})
})
} else {
console.log('failed');
}
});
})
And it worked fine....thanks to Swapnil Godambe
I need to Overwrite the Knockout Object . But When I try this I got the Following Error. When the Page Load I called loadXMLFiles and It worked without any issue. after pressing a button when I try to overwrite the object I got following Error Uncaught TypeError: Cannot read property 'fromJS' of undefined in downloadFile Function. but in both Cases It's coming same object. Can Any one please help me on this???
var urlPath = window.location.pathname;
//var self = this;
$(function () {
ko.applyBindings(indexVM);
indexVM.loadXMLFiles();
});
var indexVM = {
XMLFiles: ko.observableArray([]),
loadXMLFiles: function () {
var self = this;
$.ajax({
type: "GET",
url: "../HotelBackEndProcess/UpdateDatabase/FillIndex",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.XMLFiles(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
},
DownloadFile: function () {
Id = this.Id;
var self = this;
$.ajax({
type: "GET",
url: "../HotelBackEndProcess/UpdateDatabase/DownloadFile",
contentType: "application/json; charset=utf-8",
data: { Id: Id },
dataType: "json",
success: function (data) {
ko.mapping.fromJS(XMLFiles, self.data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
}
};
You're probably missing the mapping plugin (which has to be downloaded separately):
See ko.mapping in GitHub.
I am making a ajax call, but server side code is not hit. Instead control goes to javascript file included in project. Here is my code:
<script type="text/javascript">
function AddEmployee()
{
debugger;
// jQuery.support.cors = true;
$.support.cors = true;
var Product = new Object();
Product.ID = 10;
Product.Name = "kRISH";
Product.Price = "23";
Product.Category = "AS";
// console.log(JSON.stringify({ Name: "kRISH", Price: "23", Category: "AS" }));
var json_text = JSON.stringify(Product,null,2);
**$.ajax**
({
url: 'http://localhost:62310/api/products',
type: 'POST',
data: json_text,
contentType: "application/json;charset=utf-8",
success: function (data) { WriteResponse(data); },
error: function (x, y, z)
{
$('#contentProgress').popup("close");
alert(x.responseText + " " + x.status);
}
});
}
</script>
Is the url correct, why are we not using the relative url here. Can you please try this
$.ajax('http://localhost:62310/api/products', {
type: "post",
data: json_text,
dataType: "json",
cache: false,
contentType: "application/json",
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});