How to serialize dynamic form data to keep maximum UI flexibility? - javascript

Due to the nature of my current project, I often find myself having to create HTML <form> elements which must support dynamic add/remove functionality of items for posting collections to the server.
My issue is that I find myself constrained by the name attribute of the form elements because I have to keep track of indices, ex.: Room[1].Tourists[0].Name. This is giving me hard times when I would like, for example, to remove an existing input element from the beginning.
I am currently building these dynamic forms with react.js which is enabling great flexibility, but I was wondering if there was some way that I could collect form data on submit event and just serialize it to match the expected model in the controller's action and post it?

Okay so you just want to solution about this i think you were stuck somewhere in your code that's why i am asking about the sample code no worry back to this try this:
<script type="text/javascript">
$(document).ready(function () {
$("#btn_submit").on('click', function () {
$.ajax({
type: "POST",
url: "Give URL here",
async: false,
data: $("#FormID").serialize(),
success: function (result) {
//Do what you want
},
error: function (response) {
//Do what you want
}
});
});
});
</script>

Related

Form not rendering on Second Submit AJAX

I have an HTML form that is trigged with AJAX to submit using a Rails backend. However, after submitting the first time, the form stops submitting. From reading other posts, I realize part of the problem is that the issue is related to including $(document) and not the form submit handler in the JQUERY call, but changing it to something like $('.new_todo form').submit will return the page as a JSON object instead of just the instantiated object {} response that I get with using $(document) in the Jquery.
I'm essentially trying to create an object and then to keep appending it to the index page, which works on the first submit, but as noted not on subsequent ones.
I'd really appreciate any insight because I've been staring at this for hours and while tons of answers address similar challenges (unbinding etc), nothing I found successfully addresses this use case.
The current AJAX call is:
$(document).on('submit', '.new_todo', (e) => {
e.preventDefault()
$.ajax({
type: "POST",
url: "/todos",
data: {
'authenticity_token': $("input[name='authenticity_token']").val(),
'todo': {
'name': $("#todo_name").val()
}
},
success: function(response) {
$("#todo_name").val("")
$("#todo_location").html("")
$("#todo_date").html("")
let newTodo = new Todo(response)
let todoHtml = newTodo.formatIndex()
$('.todo-list').append(todoHtml)
}
})
})
The controller action for my create is:
def create
#todo = Todo.new(todo_params)
#todo.save
render json: #todo
end
Thank you!!

Updating values on page without refreshing in Node.js

I am trying to update values on my page when I user selects what they want to filter but I do not want to refresh the webpage constantly. As an example, think of a real estate website where you filter based on location and the types of housing come back with the number (e.g., apartment [4] townhouse [0] studio [5]). The types of housing will always be there but its the numbers I am interested in updating. When ever you change the filter, new numbers are popping up. What I am doing is filtering questions based on topic, subject etc.
Is there anyway to use this in node.js? What I have working so far requires the page to refresh.
$.ajax({
type="POST",
url: "/user/calculatequestions",
data: {
filter date here... },
success: function () { },
error: function () { }
});
The '/user/calculatequestions' goes through an app.post and renders a new page with new variables.
Thanks in advance,
S
You can get the values of the filter through Java Script and send data filter through Ajax.
Example of input:
<input id="field" name="field1" type="text" >
Java Script function (together Ajax stack):
var data = {};
data.fielter_data1 = document.getElementById('field');
$.ajax({
type="POST",
url: "/user/calculatequestions",
data: data,
success: function () { },
error: function () { }
});
Then, in the function node called /user/calculatequestion you can get the parameters filter with:
var filter_data = req.body.fielter_data1;
The success callback returns the data after note proccess, then you update the components (inputs, tables, lists and etc) in the front-end.
See this question please: How to refresh table data using Ajax, Json and Node.js

Updating webpage with real-time database value using AJAX+PHP response

I’m creating a Javascript game and I’m currently trying to write some code that will show the player’s “Gold Balance” in real time on a html webpage.
The Gold amount is contained in my SQL database, so I’m using setInterval with a Javascript function that contains an AJAX call which calls a PHP script that grabs the current balance amount for the player and sends it back as “response”.
I’m able to have this amount appear as a Javascript alert, however I need to have the response appear as text on the webpage inside a <div> instead.
This is my current code:
<script>
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
</script>
I have this in my html source code, I would like to place the function in a separate file and call it from there, but when I tried this I wasn't able to send the response back to the html page correctly.
I was wondering if anyone knows how to have this response appear as text on the page inside <div> </div>?
Also, I was wondering if this method will really update the div in real time (ie, will it auto-refresh the div part of the webpage, showing an up to date value (every 5000 milliseconds)?
Thanks in advance!
Since you are using jQuery, you can use text() to alter the contents of an existing div (which id is "yourDiv"):
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
$('div#yourDiv').text(response);
}
});
};
You have two questions here, so I will try to address both
1) How to append to the DOM using jQuery, instead of an alert:
in the success callback function, instead of alerting the response, you can simply call
$('body').append("<div>"+response+"</div>")
2) "Real time" Gold Balance
You should use websockets. Racthet is a good websocket PHP library to help you with this: http://socketo.me/

Using JSON to store multiple form entries

I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.

how to use JSON for an error class

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")

Categories