jQuery/XML: synchronizing data and representations using DOM-Mutation-Events - javascript

I'm creating a web application which uses jQuery to modify and HTML to represent the data. There can be several representations in the document related to a single data node. The user can dynamically create them.
For example, data will be represented and can be modified in tables. Additionally the user has the opinion to extend a "quick-overview-panel" to access specific data quickly.
If one user-control triggers an event => data must be modified => other user-controls related to the same data need to be refreshed.
<html>
<head>
<title>synchronize</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//handling data
$.ajax({url: "./data/config.xml", cache: false, async: false, success: init});
var data;
function init(d) {
data = d;
$(".bottle", data).bind("DOMAttrModified", notifyRep);
}
function notifyRep(e) {
if(e.relatedNode.nodeName == "content")
$(this).trigger("changeContent");
}
//handling representation-sync
$(".bottle", data).bind("changeContent", function() {
$("#bottleRep1").val($(this).attr("content"));
});
$(".bottle", data).bind("changeContent", function() {
$("#bottleRep2").val($(this).attr("content"));
});
//handling modification
$("#bottleRep1").bind("change", function() {
$(".bottle", data).attr("content", $(this).val());
});
$("#bottleRep2").bind("change", function() {
$(".bottle", data).attr("content", $(this).val());
});
});
</script>
</head>
<body>
<div id="app">
<span>bottle-content:<input id="bottleRep1" type="text" value="test" /></span>
<span>bottle-content:<input id="bottleRep2" type="text" /></span>
</div>
</body>
The actual problem is that each user-control handles its own modification. The change-content handler needs to know the data-modifier, so it can skip the representation-update.
Is there an existing general solution for this kind of problem?
If not, can you make suggestions for a good solution?

you can try to create a custom function that will handle the perform some action when trigger for refresh
$('body').bind('foo', function(e, param1, param2) {
alert(param1 + ': ' + param2); });
then you can call the above created function on chnage of dta so the function get trigger and perform refresh like this
$('body').trigger('foo', [ 'bar', 'bam' ]); // alerts 'bar: bam'

Related

How to get data from jquery form builder if there are multiple form initialized on the same page

I have a code like this:
<html>
<head>
<title>Example formBuilder</title>
</head>
<body>
<div class="build-wrap"></div>
<div class="build-wrap"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<script>
jQuery(function($) {
$(document.getElementsByClassName('build-wrap')).formBuilder();
});
</script>
</body>
</html>
If it was initialized by id, then I could have get data with something like this:
var fbEditor = document.getElementById('build-wrap');
var formBuilder = $(fbEditor).formBuilder();
document.getElementById('getJSON').addEventListener('click', function() {
alert(formBuilder.actions.getData('json'));
});
However, I am using classname to initialize form builder. Is there any way, when click on save, get the respective form-builder data? I am using https://formbuilder.online/
Here is jsfiddle: https://jsfiddle.net/xycvbj3r/3/
#PS: there could be numerous form builder inside php loop.
You can try this:
formBuilder.actions.getData('json');
Or:
formBuilder.actions.getData();
The live demo is here: http://jsfiddle.net/dreambold/q0tfp4yd/10/
I was facing the same issue too. This worked for me
var list = ['#ins1', '#ins2', '#ins3'];
var instances = [];
var init = function(i) {
if (i < list.length) {
var options = JSON.parse(JSON.stringify([]));
$(list[i]).formBuilder(options).promise.then(function(res){
console.log(res, i);
instances.push(res);
i++;
init(i);
});
} else {
return;
}
};
init(0);
And to get data, you can use instances[key].actions.getData()
I am not sure how you are planning to save this data, but to help with your problem of getting form data for a particular form you can use something like this
var formBuilder = $(document.getElementsByClassName('build-wrap')).first().data('formBuilder').actions.getData()
Or to use it over a jQuery Collection then
$(document.getElementsByClassName('build-wrap')).each(function () {
var formBuilder = $(this).data('formBuilder').actions.getData()
})
There is a callback mentioned in the documentation, onsave which runs on editor save. So, when clicking on any form builder's save button, the respected form's data can be received.
Here is the code-
<html>
<head>
<title>Example formBuilder</title>
</head>
<body>
<div class="build-wrap"></div>
<div class="build-wrap"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<script>
jQuery(function($) {
var options = {
onSave: function(evt, formData) {
// This is the respected form's data
console.log('MY DATA_________', formData)
},
};
$(document.getElementsByClassName('build-wrap')).formBuilder(options);
});
</script>
</body>
</html>
Here is the fiddle (couldn't create a working snippet due to not working CDNs.
)- https://jsfiddle.net/nehasoni988/rpo1jnuk/1/#&togetherjs=Mka9TJ4cex

How to convert form data into JSON data using AJAX?

I am a coding beginner, and I am currently learning how to code in javascript. I am stuck on a practice problem, where I must utilize AJAX in order to retrieve data from a form, convert the data into JSON and then append a message that uses the JSON data that was created. When I click the submit button, the success function doesn't seem to be working. I am also using JQUERY. My main question is, must I create a separate JSON file, or will the JSON data be produced on it's own when I submit the form.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="tour" data-daily-price="357">
<h2>Paris, France Tour</h2>
<p>$<span id="total">2,499</span> for <span id="nights-count">7</span> Nights</p>
<form method="POST">
<p>
<label for="nights">Number of Nights</label>
</p>
<p>
<input type="number" name="nights" id="nights" value="7">
</p>
<input type="submit" value="book">
</form>
</div>
<script type="text/javascript" src="jquery-2.2.3.min copy 4.js"></script>
<script type="text/javascript" src="json.js"></script>
</body>
</html>
$(document).ready(function() {
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax("http://localhost:8888/json.html", {
type: 'POST',
data: $("form").serialize(),
dataType: 'json',
contentType: "application/json",
success: function(data) {
var msg = $('<p></p>');
msg.append("Trip booked for " + data.nights+" nights.");
$(".tour").append(msg);
}
});
});
});
My main question is, must I create a separate JSON file
No. If you want to send JSON then you have to construct a string of JSON, but you don't need to make it a file.
or will the JSON data be produced on it's own when I submit the form.
No. You have to create the JSON yourself.
$("form").serialize() converts data into the application/x-www-form-urlencoded format. Don't use it if you want to send JSON.
There is no standard for encoding form data into JSON so you must loop over all the form controls (or the data in serializeArray) to build the data structure you want and then pass it though JSON.stringify.
Expanding on what Quentin said, you'll need to parse the fields and values out of the form yourself and put them in a JSON object. I've been using the following function (found on another stack overflow answer but I don't have the reference) which will iterate the form looking for named fields and then put that into a JSON object.
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
This function is added to the JQuery operator $ so can be called like
var data = $(this).serializeFormJSON();
And you can then use that directly in the AJAX call or stringify it first if necessary.
EDIT; meant to add that you should only call this inside of a form.submit callback as it will use the form as the this parameter.

Calling Rest API from Javascript File: Data Return Issue

Hi i have created a javascript file where i make a call to rest api and get data.
I want to return the data to the calling function from html page but the way the call works, i am not been able to.
HTML:
<html>
<head>
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js" />
<script src="jquery-G5API-1.0.0.js" />
<script type="text/javascript">
function JSFile() {
var result = GetStatus(123456);
alert('HTML: '+ result);
}
</script>
</head>
<body>
<input id="Button1" type="button" value="JSFile" onclick="JSFile()" />
</body>
</html>
query-G5API-1.0.0.js:
function GetStatus(token) {
var url = 'some/url';
var result = '';
$.getJSON(url,function(data)
{
//alert(JSON.stringify(data));
})
.always(function(xhr, status) {
alert( "finished: " + JSON.stringify(xhr));
result = JSON.stringify(xhr);
});
alert('Returning result: ' + result);
return result;
}
The sequence in which alerts are being called:
Returning result: empty_string
HTML: empty_string
Finished: json_data
Any suggestions on how to return json data from .js file to calling function in html file will be highly appreciated.
You'll need to resolve the promise to get your expected result. Check out the
jQuery deferred object api and observe the (simplified) following...
function GetG5Status3(token) {
return $.getJSON('some/url')
}
function JSFile() {
GetG5Status(123456).done(function(response) {
console.log(response);
});
}
JSFiddle Link - simplified demo
Also, I am not seeing any usage of token

Ajax call to dynamically populate dropdown works in FF, but not in Chrome and IE

I really don't know why my code works perfectly in Firefox, but when I test it in Chrome or IE, it doesn't populate a dynamic dropdown. I read some similar posts, but most of them said it's because of an unclosed div which I don't have!
Here is the code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"/>
</head>
<body>
<input type="textbox" name= "tag" id="tags">
<p>
<select id="movieImdbId" name="movieImdbId[]" multiple="multiple" width="200px" size="10px" style=display:none;>
</select>
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php", //php file which fetch actors name from DB
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val();
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags.
$("#movieImdbId").html(response).show();
});
}
});
});
</script>
</body>
</html>
Try to Explicitly Map your response here's an example from my code change to be applicable
From your post request return a json object, with two values, the label, what you want to display from the autocomplete and the value, what value you want to associate with that label, in this example I saved the value in a property (.url) as the value because I wanted my autocomplete to sync to a url.
The response function binds your results to the control. It takes in the $.map a jquery delegate which maps the array to the required structure (label is mapped to templab item.label (a property I serialized in json from the post))
(value is mapped to the item.url).
I'm not sure if this will solve your porblem but now you will be explicitly binding your data
success: function (data) {
response($.map(data, function (item) {
// this line below is a hack to get out the html encoded entities (> <...)
var templab = $('#searchhtmlconverter').html(item.label).text();
return { label: templab, value: item.url };
}))
Thanks to this post, I could finally solved my problem by just using autocompletechange event, instead of change event.
So This is the code worked for me:
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
$("#tags").on('autocompletechange change', function (){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
$.post("actions.php", {q: selectedVal}, function (response){
$("#movieName").html(response).show();
});
}).change();
}
});
});

Go to URL if input val == something

So, I've found this JSFiddle example. In JSFiddle works well, the problem is that, even if I search any != from "advogados" (just testing), the browser goes to: http://www.site.com/index.html?procura=teste
No jQuery conflict, no html issue.
Here's JS
$("#procura").on("submit", function(event){
// prevent form from being truely submitted
event.preventDefault();
// get value of text box
name = $("#procura_texto").val();
// compare lower case, as you don't know what they will enter into the field.
if (name.toLowerCase() == "advogados")
{
//redirect the user..
window.location.href = "http://jornalexemplo.com.br/lista%20online/advogados.html";
}
else
{
alert("no redirect..(entered: " + name + ")");
}
});
If your javascript is somewhere in your HTML before your <form> your $("#procura") will be an empty set, so the submit-action won't be bound to anything. Try following code:
<html>
<head>
<script type="text/javascript" src="/path/to/your/jquery.js"></script>
<script type="text/javascript">
$(function() {
// This code will be run if your document is completely
// parsed by the browser, thus all below elements are
// accessible
$('#procura').on('submit', ....);
});
</script>
</head>
<body>
<form id="procura">...</form>
</body>
</html>
$(function() {}) is also known as $(document).ready(function() {}), (documentation)
You aren't defining the variable name. http://jsfiddle.net/zwbRa/59/
var name = $("#procura_texto").val();

Categories