How to go trough JavaScript array? - javascript

I have this output from ajax call:
"total":"3",
"data":[{ "id":"4242",
"title":"Yeah Lets Go!",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah"
}]
So there is three that kind of items in that array and I would need to go that through and print actual html out of it. So on page it would be:
Yeah Lets Go! (which is a link to http:www.domain.com/yeah)
Created: 2010-07-24 13:19:24
I'm clueles with this one.
Edit 1:
Also atm I get that raw output after clicking link. How can I get it to show on page load? Or it does that ajax call when I click link atm.
Edit 2:
I got it to output everything at once. But still I have a prolem with putting it actual html. The output atm is:
"total":"3",
"data":[{
"id":"4242",
"title":"Yeah Lets Go!",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah"
}
{
"id":"4242",
"title":"Yeah Lets Go!222",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah222"
}
{
"id":"4242",
"title":"Yeah Lets Go!333",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah333"
}
]}
I would like to get that into list with title and link and creation day.
Edit 3 after answer from Luca Matteis:
Hmm, now im even more confused.
That JSON string comes out of this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true',
null,
function(data, status, xhr) {
$('#contentCell').html(data);
}
);
So I would need to do for that is something like:
var html = eval(data);
and then I would do what Luca Matteis suggest?

First off, that's a JSON string, you need to un-serialize the string into a real JavaScript object (look at json.org for this).
Once you have the native JavaScript data, something like this should work:
var html = '';
for(var i=0; i < obj.data.length; i++) {
html += ''+obj.data[i].title+'<br>';
html += 'Created: '+ obj.data[i].created;
}

Hmm, now im even more confused.
That JSON string comes out of this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', null, function(data, status, xhr) {
$('#contentCell').html(data);
});
So I would need to do for that is something like:
var html = eval(data);
and then I would do what Luca Matteis suggest?

Related

How do I add a value from a callback into a new element with setAttribute?

I need to add the value of a callback into my setAttribute. How do I do that?
This value is necessary to get data out of a table at a later moment.
This is the code:
row.forEach(function(row) {
var subchapname = document.createElement("div");
subchapname.setAttribute("id", "subchaptertitle");
subchapname.setAttribute("subid", '"+row+"');
subchapname.setAttribute("onclick","{ alert('You are not going to believe this!') } ");
subchapname.textContent = row.subname;
rows.appendChild(subchapname);
Basically, this means:
callback = row
This callback needs to be added to subchapname.setAttribute("subid", '"+row+"');
Is this possible?
This is the actual result:
<div id="subchaptertitle" subid=""+row+"" onclick="{ alert('You are not going to believe this!') } ">bos in brand</div>```
subid is not attribute to store data in it, so you can not add a attribute like this to a html-tag and fill it with a value (Of course writing a string into it, would work, but is this what you need?). But you can add datasets if you use html5. So use this solution to store your rows-value in the dataset-property of subid.
If row is a object and you want to see the the stringified value of the Object use JSON.stringify before storing it in the dataset
row.forEach(function(row) {
var subchapname = document.createElement("div");
subchapname.setAttribute("id", "subchaptertitle");
subchapname.dataset.subid = row;
// subchapname.dataset.subid = JSON.stringify(row);
subchapname.setAttribute("onclick","{ alert('You are not going to believe this!') } ");
subchapname.textContent = row.subname;
rows.appendChild(subchapname);
});
Your Element should now look like this:
<div id="subchaptertitle" onclick="{ alert('You are not going to believe this!') } " data-subid="[object Object]"></div>
Or if you used JSON.stringify:
<div id="subchaptertitle" onclick="{ alert('You are not going to believe this!') } " data-subid="what ever row is as a string"></div>
To log the value to the console, (after you added the tag to the DOM) do something like this:
console.log(document.getElementById('subchaptertitle').dataset.subid);
In case you used JSON.stringify, now use something like this:
console.log(JSON.parse(document.getElementById('subchaptertitle').dataset.subid));

How do I populate a list field in a model from javascript?

I have a Kendo.MVC project. The view has a model with a field of type List<>. I want to populate the List from a Javascript function. I've tried several ways, but can't get it working. Can someone explain what I'm doing wrong?
So here is my model:
public class Dashboard
{
public List<Note> ListNotes { get; set; }
}
I use the ListNotes on the view like this:
foreach (Note note in Model.ListNotes)
{
#Html.Raw(note.NoteText)
}
This works if I populate Model.ListNotes in the controller when the view starts...
public ActionResult DashBoard(string xsr, string vst)
{
var notes = rep.GetNotesByCompanyID(user.ResID, 7, 7);
List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();
Dashboard employee = new Dashboard
{
ResID = intUser,
Type = intType,
FirstName = user.FirstName,
LastName = user.LastName,
ListNotes = listNotes
};
return View(employee);
}
... but I need to populate ListNotes in a Javascript after a user action.
Here is my javascript to make an ajax call to populate ListNotes:
function getReminders(e)
{
var userID = '#ViewBag.CurrUser';
$.ajax({
url: "/api/WoApi/GetReminders/" + userID,
dataType: "json",
type: "GET",
success: function (notes)
{
// Need to assign notes to Model.ListNotes here
}
});
}
Here's the method it calls with the ajax call. I've confirmed ListNotes does have the values I want; it is not empty.
public List<Koorsen.Models.Note> GetReminders(int id)
{
var notes = rep.GetNotesByCompanyID(id, 7, 7);
List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();
foreach (Koorsen.OpenAccess.Note note in notes)
{
Koorsen.Models.Note newNote = new Koorsen.Models.Note()
{
NoteID = note.NoteID,
CompanyID = note.CompanyID,
LocationID = note.LocationID,
NoteText = note.NoteText,
NoteType = note.NoteType,
InternalNote = note.InternalNote,
NoteDate = note.NoteDate,
Active = note.Active,
AddBy = note.AddBy,
AddDate = note.AddDate,
ModBy = note.ModBy,
ModDate = note.ModDate
};
listNotes.Add(newNote);
}
return listNotes;
}
If ListNotes was a string, I would have added a hidden field and populated it in Javascript. But that didn't work for ListNotes. I didn't get an error, but the text on the screen didn't change.
#Html.HiddenFor(x => x.ListNotes)
...
...
$("#ListNotes").val(notes);
I also tried
#Model.ListNotes = notes; // This threw an unterminated template literal error
document.getElementById('ListNotes').value = notes;
I've even tried refreshing the page after assigning the value:
window.location.reload();
and refreshing the panel bar the code is in
var panelBar = $("#IntroPanelBar").data("kendoPanelBar");
panelBar.reload();
Can someone explain how to get this to work?
I don't know if this will cloud the issue, but the reason I need to populate the model in javascript with an ajax call is because Model.ListNotes is being used in a Kendo Panel Bar control and I don't want Model.ListNotes to have a value until the user expands the panel bar.
Here's the code for the panel bar:
#{
#(Html.Kendo().PanelBar().Name("IntroPanelBar")
.Items(items =>
{
items
.Add()
.Text("View Important Notes and Messages")
.Expanded(false)
.Content(
#<text>
#RenderReminders()
</text>
);
}
)
.Events(e => e
.Expand("getReminders")
)
)
}
Here's the helper than renders the contents:
#helper RenderReminders()
{
if (Model.ListNotes.Count <= 0)
{
#Html.Raw("No Current Messages");
}
else
{
foreach (Note note in Model.ListNotes)
{
#Html.Raw(note.NoteText)
<br />
}
}
}
The panel bar and the helpers work fine if I populate Model.ListNotes in the controller and pass Model to the view. I just can't get it to populate in the javascript after the user expands the panel bar.
Perhaps this will do it for you. I will provide a small working example I believe you can easily extend to meet your needs. I would recommend writing the html by hand instead of using the helper methods such as #html.raw since #html.raw is just a tool to generate html in the end anyways. You can write html manually accomplish what the helper methods do anyway and I think it will be easier for you in this situation. If you write the html correctly it should bind to the model correctly (which means it won't be empty on your post request model) So if you modify that html using javascript correctly, it will bind to your model correctly as well.
Take a look at some of these examples to get a better idea of what I am talking about:
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
So to answer your question...
You could build a hidden container to hold your list values like this (make sure this container is inside the form):
<div id="ListValues" style="display:none">
</div>
Then put the results your ajax post into a javascript variable (not shown).
Then in javascript do something like this:
$('form').off('submit'); //i do this to prevent duplicate bindings depending on how this page may be rendered futuristically as a safety precaution.
$('form').on('submit', function (e) { //on submit, modify the form data to include the information you want inside of your ListNotes
var data = getAjaxResults(); //data represents your ajax results. You can acquire and format that how you'd like I will use the following as an example format for how you could save the results as JSON data: [{NoteID ="1",CompanyID ="2"}]
let listLength = data.length;
for (let i = 0; i < listLength; i++) {
$('#ListValues').append('<input type="text" name="ListNotes['+i+'].NoteID " value="' + data.NoteID +'" />')
$('#ListValues').append('<input type="text" name="ListNotes['+i+'].CompanyID " value="' + data.CompanyID +'" />')
//for your ajax results, do this for each field on the note object
}
})
That should do it! After you submit your form, it should automatically model bind to you ListNotes! You will be able to inpsect this in your debugger on your post controller action.

Retrieving xml namespace child element value using jquery

Folks.
I am new to jquery and I checked out alot of the postings here when it comes to parsing namespace formatting .xml using jquery. After going over my code and looking at the examples I am struggling grabbing a value from a nested child element. Below is my xml snippet:
<offers:offer-bundle>
<cash:offer lang="EN" offer-type="Cash">
<cash:cash>
<cash:cannot-be-combined-with></cash:cannot-be-combined-with>
<cash:cash-amount>1000</cash:cash-amount>
<cash:requires-tfs-financing>false</cash:requires-tfs-financing>
<cash:stackable-with-apr>false</cash:stackable-with-apr>
<cash:stackable-with-lease>false</cash:stackable-with-lease>
<cash:sub-type-labels>Cash Back</cash:sub-type-labels>
</cash:cash>
<cash:tfs-calculator>false</cash:tfs-calculator>
<cash:offer-label>Cash Back</cash:offer-label>
<cash:offer-label-num>7</cash:offer-label-num>
<cash:series-list></cash:series-list>
<cash:offer-id>cash_1433205220095</cash:offer-id>
<cash:start-date>2015-06-02</cash:start-date>
<cash:end-date>2015-07-06</cash:end-date>
<cash:title>2015 Cash Back Offer</cash:title>
<cash:use-for-email>false</cash:use-for-email>
<cash:description>I can get this value</cash:description>
<cash:offer-image/>
<cash:offer-image-alt/>
<cash:offer-image-disclaimer/>
<cash:offer-card>...</cash:offer-card>
<cash:bullets>...</cash:bullets>
<cash:disclaimers>
<cash:disclaimer>
**I NEED TO GET THIS CHILD ELEMENT VALUE.**
</cash:disclaimer>
</cash:disclaimers>
</offers:offer-bundle>
I am able to get the value of <cash:offer-card>, <cash:offer-id> etc. since it does not have any nested children. I am struggling with getting the child node of <cash:disclaimers>.
Here is what I've written so far:
$.ajax({
type : "GET",
url : webServiceURL,
dataType : "xml",
success : function (xml) {
$(xml).find('offers\\:offer-bundle, offer-bundle').each(function(index, value) {
var $incentive;
var $offer;
var $offerDescription;
var $offerDisclaimer;
//Do Cash: Condition code is executing, incentive is hard coded to 'cash'
if (incentive == 'cash') {
$incentive = $(this);
$offer = $incentive.find('cash\\:offer, offer');
$offerDescription = $offer.find('cash\\:description, description').text();
$offer.find('cash\\:disclaimers, disclaimers').each(function (i, v) {
console.log ("here executing" + $(i).find('cash\\:disclaimer, disclaimer').text() );
My console window prints out a blue little circle with the number 2 in it along with "here executing" and no value. Even if I use
$(this).find('cash\:disclaimers, disclaimers').each(function (i, v) { }) versus $offer.find('cash\:disclaimers, disclaimers').each(function (i, v) {
I get the same results in my console window. Any ideas or knowledge sharing would be greatly appreciate it.

Simple quiz - how to get clicked values and send it to php

I have to write a simple quiz app. As I picked it after someone this is what I have.
There are 10 questions with 3 answers each. All question are loaded at once and only one visible. After clicking the answer next question shows up etc.
However as javascript is kinda magic to me I have no clue how to get all answers and send it to php to check if user chose correct.
The code looks something like this:
<form action="result.php">
<div class=“quiz>
<div class=“question”> Some question ?
<ul>
<li><a href=“#”>Answer A</a></li>
<li><a href=“#”>Answer B</a></li>
<li><a href=“#”>Answer C</a></li>
</ul>
</div>
[… more question here …]
<div class="question">Last question ?
<ul>
<li>Answer A</li>
<li>Answer B</li>
<li>Answer C</li>
</ul>
</div>
</div>
<input type=“hidden” name=“answers” value=“answers[]>
</form>
So basically user click on answer, next question pop up and at the end I need to populate all answer and send it to result.php where somehow I would get results within array with chosen answers like {1,3,2,1,2,3,1,2,3,1} or something like that.
There are many ways to accomplish this. Here's an easy one:
add a
<input type="hidden" name="questions[]" value="" />
inside each .question DIV
update the value of this input when one of the links are clicked:
$('.question a').on('click', function(){
var answer = $(this).text();
$(this).parents('.question').find('input').val(answer);
});
put a request method on your form, let's say POST
Then in your PHP script you'll get a numerically indexed array with the selected answer for each question, $_POST['questions'].
I do not know how your design looks like, but it may be possible to achieve this without any javascript, using hidden radio inputs and labels (I'm assuming here you're using links because of styling limitations on input fields).
Normally, you would create an HTTP request to your verification back-end. jQuery, for one, makes this quite easy. Also, I would try to generate the questions HTML, so that you're ready to generate quizzes with other sets of questions without having to re-type your html.
I'm trying to create a quizz-like app myself, currently, and would be glad to hear your feedback. A brief snipped of what I mean is on this fiddle: http://jsfiddle.net/xtofl/2SMPd/
Basically something like:
function verify(answers) {
jQuery.ajax("http://yoursite/verify.php?answers="+answers,
{ async: true,
complete: function(response, status){
// e.g.
alert(response.text);
}
};
};
This request would be sent when all answers are completed. I would try to create the questions on-the-fly using javascript and the DOM, something like:
function retrieveQuestions() {
//TODO: get them from a json-request like http://yourquizz/quizz1/questions
return [{ text: "what if Zoo went to Blohom in a Flurk?",
options: { a: "he frunts and vloghses",
b: "the Blohom doesn't snorf anymore" }
},
{ text: "how many this and that",
options: { a: "1", b: "2", c: "14" }
}
];
};
// retrieve and create the questions elements
var questions = retrieveQuestions();
questions.forEach(function(question, index){
jQuery("#questions").append(createQuestionElement(question));
});
// what does a question element look like:
function createQuestionElement(question){
var li=document.createElement("li");
var options = [];
Object.keys(question.options).forEach(function(key){
var o = document.createElement("div");
jQuery(o).on('click', function(){question.answer=jQuery(o).val();});
li.appendChild(o);
});
return li;
}
Your php backend verify.php script will check the arguments and return the result in json format, e.g.:
$correct = ($answers[ $_GET["question"] ] == $_GET["answer"]);
print("{ 'correct': '$correct' }");
(provided your answers are stored in an array $answers.
Yet another solution to the problem:
jsFiddle
We use event handlers, to check if an answer was clicked, then add the index of the answer to an array. When the last answer was submitted, we send the data to a php page, where you can process it using the $_POST array.
$('.question a').on('click', function (e) {
e.preventDefault();
var self = $(this);
var ans = self.parent().index() + 1;
answers.push(ans);
var hasNext = nextQuestion();
if (!hasNext) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"answers": answers
}
}).done(function (response) {
response = 'Stuff you output with PHP';
$('body').append('<p> Result: ' + response + '</p>');
});
}
});

Dynamically updating html.listBox in MVC 1.0?

The client will choose an item from a dropDown list, this newly selected value will then be used to find assets linked to that selected item, these assets will then be loaded into the listBox.
This sounds simple enough, and I'm aware I could use a partial View but it seems overkill for just updating one component on a form.
Any
I've done this in MVC 1.0 myself. I used an onchange on the first drop down which called an action using the value selected. That action returned a JSON result. The jQuery script which called that action then used the JSON to fill the second drop down list.
Is that enough explanation, or would you like help writing the javascript, the action, or both?
Inside your view:
<%= this.Select("DDLName").Attr("onchange", "NameOfJavascriptFunction();") %>
<%= this.MultiSelect("ListBoxName") %>
The javascript will look like this:
function NameOfJavascriptFunction() {
var ddlValue = $("DDLName").val();
jQuery.ajax({
type: 'GET',
datatype: 'json',
url: '/Controller/Action/' + dValue,
success: updateMultiSelect
});
}
function updateMultiSelect(data, status) {
$("#ListBoxName").html("");
for(var d in data) {
$("<option value=\"" + data[d].Value + "\">" + data[d].Name + "</option>">).appendTo("#ListBoxName");
}
}
Finally, the action is something like this (put this in the controller and action from the first javascript):
public ActionResult Action(int id) //use string if the value of your ddl is not an integer
{
var data = new List<object>();
var result = new JsonResult();
this.SomeLogic.ReturnAnEnumerable(id).ToList().ForEach(foo => data.Add(new { Value = foo.ValueProperty, Name = foo.NameProperty }));
result.Data = data;
return result;
}
Feel free to ask follow up questions if you need any more explanation.

Categories