I have the following knockout's viewModel :
var viewModel={
businessName: "",
....
}
I also tried to identify the field like this: businessName: ko.observable("")
Then, I have a load method that requests for a JSon with a newly populated data
And this is how I'm trying to apply the new data:
$.ajax({
//
url: "#Html.Raw(#Url.Action("Load"))",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
//OPTION 1:
viewModel.businessName = result.vm.BusinessName;
//OPTION 2:
var viewModel2 = ko.mapping.fromJS(result.vm);
console.log(viewModel2.businessName);
}
});//ajax
As a result:
if I use Option1, I get the new data but it does not get updated on the page.
If I use Option2, it writes "undefined"
Please advise how can I update the new data on the page?
I checked the similar topics but there is no answer that helps
PS
It seems I resolved OPTION 1. But still don't understand why OPTION 2 does not work
ko.observable is a function, not a property. So you get it's value like this:
var whatsTheValue = myVM.MyObservable();
and you set it like this:
myVM.MyObservable(newValue);
This is all in the docs.
Note, however, when using the data-bind syntax in your HTML, you don't need to explicitly unwrap your observable by using the parenthesis because KO is smart enough to do it automatically:
<span data-bind="text: MyObservable"></span>
You have to use ko.observable in the ViewModel and access/write it accordingly.
var myViewModel = {
businessName = ko.observable('')
};
...
$.ajax({
...
success: function(result) {
myViewModel.businessName(result.vm.BusinessName);
},
...
});
Otherwise your view won't have any clue you changed businessName. In the implementation ko.observable, besides actually storing the new value, broadcasts some events to your view, letting it know the stored value changed.
Related
I'm confused... What's wrong with this?
Couldn't post without changing the title... I seriously don't know what's wrong
$(document).ready(function(){
$("#fmob").click(function(){
var mobname = $(this).attr("data-value");
console.log(mobname);
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {mobname: 1},
dataType: "json",
success: function(data){
if(data.response === true){
$("#fresponse").html(data.result);
}else{
$("#fresponse").html(data.result);
}
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
});
I looked up here Unexpected end of JSON input from an ajax call
but somehow not what I expected... What's wrong? Thanks.
Try this approach:
$(document).ready(function(){
$("#fmob").click(function(){
var mobname = $(this).attr("data-value");
console.log(mobname);
var data = {}; // setup a data object
data[mobname] = 1; // add the property with the key of the value of the "mobname" variable, with the data of 1 (per question)
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: data, // pass the data object as the POST data instead of defining an object inline
dataType: "json",
success: function(data){
if(data.response === true){
$("#fresponse").html(data.result);
}else{
$("#fresponse").html(data.result);
}
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
});
Note the lines with comments, above.
In this approach, we setup a data object and specify a property using the value of the "mobname" variable, instead of defining the property inline. This allows us to use the dynamic value of the variable as the key for the property.
I guess the problem is with the line: data: {mobname: 1}
As you can't assign a variable name as object property like that... it should be inside a square brackets like this data: {[mobname]: 1}
EDIT: if you aren't using browser supported by ES 2015 you could even do
data: JSON.parse('{"'+mobname+'":1}')
EDIT 1 if you want to send the json data as string and convert that on php side you could simply do data: '{"'+mobname+'":1}'
This might cause your ajax call to fail, and might not return a JSON as you're expecting (using the line dattype:JSON);
So removing datatype:JSON can also help you by showing what you're doing wrong
JSON objects are differentiated from standard JavaScript objects by using double quoted in both the key and the value - unless either is an integer.
It is explained in the relevant W3Schools site.
Therefore, in your AJAX request, you have to send a properly formatted JSON object:
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {"mobname": 1}, //here's the change
dataType: "json",
/* rest of the code */
You can of course pass a variable as well:
var JSON_obj = {"mobname": 1, "othermob": 2, /*rest of the JSON */ };
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: JSON_obj, //here's the change
dataType: "json",
/* rest of the code */
Again, with properly formatted JSON objects (and with properly included JS script if it's in another file), this should work.
Good day! I need to render a model's attributes to JSON so I can pass them into a template.
Model:
var UserInfo = Backbone.Model.extend({
url: appConfig.baseURL + "users/",
});
Template:
<script type="text/html" class="template" id="profile-form">
<h2 class="ui-li-heading"><%= username %></h2>
<p class="ui-li-desc"><strong><%= phone %></strong></p>
</script>
View:
var ProfilePageView = Backbone.View.extend({
events: {
'click #edit': "edit"
},
initialize: function () {
this.template = $.tpl['profile-form'];
var user = new UserInfo()
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
console.log(user) //returns correct object with attrs
console.log(user.toJSON()) //returns empty object
},
render: function (eventName) {
$(this.el).html(this.template());
},
edit: function () {
window.workspace.navigate('#account/edit', { trigger: true});
}
});
When i put in console something like this, user.toJSON() returns correct data
var user = new UserInfo();
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
But when i put it to my view, its returns Object {}.
Where is a mistake or tell me how can differently pass to the template data received from the server in json format? Thanks!
You appear to have two problems. fetch is asyncronous, so you need to use a callback to use the information. But first, an explanation about toJSON. .toJSON() doesn't actually return a JSON string, it returns an object that is what you want JSON to stringify. This allows you to modify the toJSON method to customize what attributes will be taken from your model or collection and added to the JSON string representation of your model. Here is a quotation from the Backbone.js docs:
toJSON collection.toJSON([options])
Return a shallow copy of the model's attributes for JSON
stringification. This can be used for persistence, serialization, or
for augmentation before being sent to the server. The name of this
method is a bit confusing, as it doesn't actually return a JSON string
— but I'm afraid that it's the way that the JavaScript API for
JSON.stringify works.
So you should replace this line in your code
console.log(user.toJSON())
with this one
console.log(JSON.stringify(user))
The object that you saw was returned by toJSON will then be turned into JSON.
Now, even after you do that, it won't work properly, because you will execute the console.log before you get the data for your model from fetch. fetch is asynchronous, so you need to call any code you want to be executed after the fetch is done in the success callback:
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST',
success: function(){
console.log(user);
console.log(JSON.stringify(user));
}
});
Currently, the following code works as intended but if I add an echo such as "LANG: en" anywhere in the code (let's say in the bootstrap), the following code won't work anymore and I get this ajax request response :
<br/>LANG : en{"response":true,"id":13}
(the ajax response contains the echo + json array ) and therefore I'm not able to print the id (it will print : undefined when i will try to access to data.id).
My question is : How can I print my debug info and still manage to perform ajax requests ?
Here is my code in the controller :
public function init()
{
$this->_helper->ajaxContext->addActionContext('retrievecategories', 'json')->initContext();
}
public function retrievecategoriesAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isXmlHttpRequest()) {
if (isset($_POST['id']))
$id = $_POST['id'];
$id+=1;
echo json_encode(array('response' => true, 'id' => $id));
}
}
My js code :
jQuery(function(){
var obj = {"id":12};
jQuery.ajax({
url: '/search/retrievecategories?json',
type: 'post',
data: obj,
dataType: 'json',
success: function(data){
var id = data.id;
alert(id);
},
error: function(data){
var id = data.id;
alert(id);
}
});
});
I hope I was clear enough. Thank you for your time !
If you echo anything but the JSON object, the JQuery parser will fail because the response is no longer a valid JSON. you could make a custom parser which interprets the response text and takes away the debug info leaving the JSON object, or you can include the debug info in the array you encode.
json_encode(array('data'=>'data','debug'=>'debug info'))
Then you detect if the debug field is present and after a console.log() or alert() you delete it form the object.
I would strongly recommend that you read about firePHP. It uses the same console that Firebug uses to display debug information from your php code. It is really simple to use with the Zend_Log.
as described in the title, I'm trying to call a WebService method via JSON/Ajax in JavaScript with several String parameters and 2 lists or arrays.
For now everything worked fine with single parameters in this format:
var WSParameters = "{pParam1: 'abc', pParam2: 'def'}"
$.ajax({
type: "POST",
url: "WebService.asmx/" + webMethod,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: WSParameters,
success: function (result) {
// stuff to be done on if request was successful
},
error: function (message) { alert('Error loading data! ' + message.responseText); }
});
But now I need to provide the web service method a list/array of values. The web service method looks like this:
[WebMethod(true)]
public void editExistingSystem(System.Collections.Generic.List<String> pFirstList,
System.Collections.Generic.List<String> pSecondList,
String pParam1,
String pParam2)
{
// Stuff
}
I guess it should be something like this, but obviously this didn't work:
var WSParameters = "{pFirstList: 15,4,13, pSecondList: 'gr00001_96594737', pParam1: 'abc', pParam2: 'def'}"
Could you please help me with finding the correct syntax to define a list in this parameter list?
Thanks a lot in davance
Br
vm370
As so often, I found the solution almost right after asking the question...
Sorry guys for bothering you. The correct paramter string to the example in my starting post would be:
var WSParameters = "{pfirstList: ['15','4','13'], pSecondList: ['gr00001_96594737'], pParam1: 'abc', pParam2: 'def'}"
Thanks and best regards
vm370
I am using Jquery Ajax for calling the methods in controller, but i am always getting invalid json primitive error.
Below is the Code.
Client side Code
$("#something >li").each(function () {
widgetsobj.push({
WidgetId: $(this).attr("dbid"),
ColumnNumber: 2,
RowNumber: 3,
WidgetType: "Graph",
WidgetName: "ddd",
PageName : "Page1"
});
});
$.ajax({
url: "/Home/ABC",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) },
success: function (data) {
alert("ss");
},
error: function (data) {
debugger;
}
});
at controller
[HttpPost, ValidateInput(false)]
public JsonResult ABC(string pagename1, List<XYZ> widgetsobj1)
{
// do something
}
Note XYZ is object with below properties.
WidgetId
ColumnNumber
RowNumber
WidgetType
WidgetName
PageName
So please let me know where i am wrong.
The thing about ajax is that it is very picky about what you send through. You need to make absolutely sure that everything is in the correct format.
i.e. you are using double quotations (") rather than single (') and so on.
The best thing to do, would be to use Firebug or a similar console to view the POST as it is executed or to use alert() to view the POST data before it is sent off. That way you can identify where the problem is.
Remember, when you use json.stringify() it is going to turn whatever you feed it into what it believes will be an acceptable JSON string and because it is just a string there could be syntax errors at any point!
From what I can see here, there may be an issue at:
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) }
You may want to try:
data: { "pagename1": pagename, "widgetsobj1": JSON.stringify(widgetsobj) }
I got the same error. My solution was to add:
dataType: 'json',
to the ajax call. Looks like you already had that in in your ajax call. But Hope this helps someone else.