Convert li input values data to JSON - javascript

Hello I need to save multi values and update database using ajax.. I'm working on Yii framework..
in the first I need to send data using ajax as json but I have wrong on results.
Live code:
http://jsfiddle.net/kxJwp/2/
My javascript code is:
$("#save").live('click', function(){
var showtimes = [];
var values = {};
$('li inputs').each(function() {
values[$(this).attr('name')] = $(this).val();
});
$('li').each(function(i) {
showtimes[i]=values;
});
alert(JSON.stringify(showtimes));
});
Javascript output:
It's output last one li values x number of li
inputs:
<li>
<input name="show_id" class="show_id att" type="hidden" value="" />
<input name="movie_id" class="movie_id att" type="hidden" value="" />
<input name="cinema_id" class="cinema_id att" type="hidden" value="" />
<input name="status" class="status att" type="hidden" value="" />
<input name="times" class="timesArray att" type="hidden" value="" />
<li>
<li>
<input name="show_id" class="show_id att" type="hidden" value="" />
<input name="movie_id" class="movie_id att" type="hidden" value="" />
<input name="cinema_id" class="cinema_id att" type="hidden" value="" />
<input name="status" class="status att" type="hidden" value="" />
<input name="times" class="timesArray att" type="hidden" value="" />
<li>

You are seeing only one row because you have only one object, whereas you need an array of objects, so declare an array first, and then keep adding the objects to it. Something like this:
$("#save").live('click', function(){
var showtimes = []; // Create empty javascript array
var objec={};
$("li").find("input").each(function(index) { // Iterate over inputs
objec=new Object; // to create a new object for every matched element
objec[$(this).attr('name')]=$(this).val()+'avla';
showtimes[index]=objec; // Add object to array
});
var json = JSON.stringify(showtimes);
alert(json);
});
Code explanation:
Use the inbuilt index of each(), by passing the index to the function like: function(index){...}.
Edit: objec=new Object; is needed to avoid getting repeated values, because each time the same object was getting added to the array, but with new, a new object is created each time and that is added to the array.
Update: A better way to select the lis would be using a selector such as : $("li:has(input)") and then cycle through the children:
$("#save").live('click', function(){
var showtimes = [];
var values = {};
$("li:has(input)").each(function(i){
values = new Object;
$(this).children().each(function(){
values[$(this).attr('name')]=$(this).val();
});
showtimes.push(values);
});
alert(JSON.stringify(showtimes));
});
Edit: The output(arrays formed) in both the above samples is different.
Output for code sample 1:
json=[{"show_id":"1avla"},{"movie_id":"2avla"},{"cinema_id":"3avla"},{"status":"4avla"},{"times":"5avla"},{"show_id":"6avla"},{"movie_id":"7avla"},{"cinema_id":"8avla"},{"status":"9avla"},{"times":"0avla"}]
Output for code sample 2:
json=[{"show_id":"1","movie_id":"2","cinema_id":"3","status":"4","times":"5"},{"show_id":"6","movie_id":"7","cinema_id":"8","status":"9","times":"0"}]

Your original js code shows
$("tr").find("input.att").each(function() {
however your view code shows you are using an <li> instead of <tr>
So shouldn't it be $("ul") or $("li")

You can use another alternate method. The changes you should made is place the the lis and input's under a form ad submit the form via ajax. Also you should change the names of the input according to this ie add square brackets so that you can retrieve it as arrays in PHP. No jSON needed
So
<form id="myform" action="action.php">
.....
<li>
<input name="show_id[]" class="show_id att" type="hidden" value="" />
<input name="movie_id[]" class="movie_id att" type="hidden" value="" />
<input name="cinema_id[]" class="cinema_id att" type="hidden" value="" />
<input name="status[]" class="status att" type="hidden" value="" />
<input name="times[]" class="timesArray att" type="hidden" value="" />
<li>
<li>
<input name="show_id[]" class="show_id att" type="hidden" value="" />
<input name="movie_id[]" class="movie_id att" type="hidden" value="" />
<input name="cinema_id[]" class="cinema_id att" type="hidden" value="" />
<input name="status[]" class="status att" type="hidden" value="" />
<input name="times[]" class="timesArray att" type="hidden" value="" />
<li>
....
</form>
and the javascript for ajax
$("#save").live('click', function(){
var form = $('#myform');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
} );
});
then in your controller you will get the submitted data as array
print_r($_POST['show_id']);
print_r($_POST['movie_id']);
etc etc

Related

Can't pass extra form data with radio button data to php via ajax

I have a simple form I have a radio button and 2 hidden fields. I want to pass the radio button value and the hidden fields value via ajax to a php page. The radio button value passes fine but not the hidden fields do not. I have hard coded the the values for table and id in the php page to make sure the value of the radio button is being passed for testing.
<input type="radio" name="contract" value="0" class="custom-switch-input">
<input type="radio" name="contract" value="1" class="custom-switch-input">
<input type="radio" name="contract" value="2" class="custom-switch-input">
<input type="hidden" name="table" value="timber_sales">
<input type="hidden" name="id" value="177">
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var contract = $(this).val();
$.ajax({
url:"edit_do.php",
method:"POST",
data:{contract:contract,id:id,table:table},
});
});
});
You're setting the value of contract in your event listener, but not id or table.
To get this to work, the way you currently have it, you'll need to search the dom for the value of your hidden fields as well.
var contract = $(this).val();
var id = $('input[name="id"]').val();
var table = $('input[name="table"]').val();
You need to get the values from the hidden fields first. Just like you did with $(this).val() for the value of the radio button. So:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var contract = $(this).val();
var id = $('input[name=id]').val();
var table = $('input[name=table]').val();
$.ajax({
url:"edit_do.php",
method:"POST",
data:{
contract: contract,
id:id,
table:table
},
});
});
});
It is probably better to give the hidden fields an unique ID attribute and get them through $('#myuniqueid').val(), but at least the above work as long as you don't have any other fields named ID or table.
Your jquery event does not know about hidden fields. Try this:
<form id="form1">
<input type="radio" name="contract" value="0" class="custom-switch-input">
<input type="radio" name="contract" value="1" class="custom-switch-input">
<input type="radio" name="contract" value="2" class="custom-switch-input">
<input type="hidden" name="table" value="timber_sales">
<input type="hidden" name="id" value="177">
</form>
<form id="form2">
<input type="radio" name="contract" value="0" class="custom-switch-input">
<input type="radio" name="contract" value="1" class="custom-switch-input">
<input type="radio" name="contract" value="2" class="custom-switch-input">
<input type="hidden" name="table" value="timber_sales">
<input type="hidden" name="id" value="177">
</form>
$(document).ready(function(){
$('form').change(function(){
event.preventDefault();
var send = $(this).data();
$.ajax({
url:"edit_do.php",
method:"POST",
data:send,
});
});
});

javascript jquery find multiple hidden input without specific attribute

Can javascript or jquery create an array of values from multiple hidden inputs with randomly created ids (in other words, no specific attribute to search for)? The code below only results in the alert of the first hidden input, 'abc'...
Thanks
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
<script>
//create hidden fields array
var hiddenFields = [];
//for each table row
$('html').each(function()
{
//get hidden field
if (hiddenField != $(this).find("input[type='hidden']").val()){
var hiddenField = $(this).find("input[type='hidden']").val();
}
//if not empty push to array
if(hiddenField!='undefined'&& hiddenField !=null )
hiddenFields.push(hiddenField);
});
alert(hiddenFields);
</script>
Maybe try this:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
JS
var tags = document.getElementsByTagName("input");
for(var i = 0; i < tags.length; i++){
if(tags[i].getAttribute("hidden") == null){
console.log(tags[i].value);
}
}
Codepen - https://codepen.io/anon/pen/jxRVMb?editors=1010
You're only calling .val once after you .find, so it only returns the value of the first element in the jQuery collection. ($('html').each will only iterate once, because there's only one html tag in the document)
You can try something like this instead, no jQuery needed:
const hiddenFields = [...document.querySelectorAll('input[type="hidden"]')]
.map(input => input.value);
console.log(hiddenFields);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
You should also try to fix the HTML so that there are no duplicated IDs; that's invalid.
If you wanted to use jQuery iteration:
const hiddenFields = $.map($('input[type="hidden"]'), input => $(input).val());
console.log(hiddenFields);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
Can use a combination of filter() and map()
var results = $("input[type='hidden']").filter(function() {
return this.value // only return elements that have value
}).map(function() {
return this.value // pass the value to array
}).get()
console.log(results)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
Grab all hidden inputs and then you can fetch value by iterating on it using forEach loop
const hiddenInputs = document.querySelectorAll('input[type="hidden"]');
const hiddenInputValues = [];
hiddenInputs.forEach((ele) => {
hiddenInputValues.push(ele.value);
});
console.log(hiddenInputValues);
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />

How to get html input in JavaScript?

I am using the code below in a html form:
<input type="text" name="cars[]" required>'
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
I would like to get the answers from all the inputs in JavaScript.
How can this be done?
I have the following WRONG code for this:
var element = document.getInput("cars[]");
for (i = 0; i < element.length; i++) {
alert(element[i].value);
}
You have to use document.getElementsByName() like this:
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
alert(element[i].value);
}
<input type="text" name="cars[]" value="a" required>
<input type="text" name="cars[]" value="b" required>
<input type="text" name="cars[]" value="c" required>
These two things in pure JavaScript net approximately the same result. The first is using the HTML form element to find all of the input elements attached to it. However, the syntax for finding the array called "cars[]" is troublesome and in my opinion a tad annoying. If I was going to do something in pure JavaScript I'd probably prefer the second way, using document.querySelectorAll.
window.addEventListener('load', function() {
var form = document.getElementById('thing');
form.elements['cars[]'].forEach(function(el, i) {
console.log("value is ", el.value)
}); //Form.elements[] array has been available since Chrome 7 or so. It should be available for use in just about any browser available.
var items = document.querySelectorAll('[name="cars[]"]');
items.forEach(function(el, i) {
console.log("Item Value is ", el.value)
});
});
<form id="thing">
<input type="text" name="cars[]" value="1" />
<br />
<input type="text" name="cars[]" value="2" />
<br />
<input type="text" name="cars[]" value="3" />
<br />
<input type="text" name="cars[]" value="4" />
<br />
<input type="submit" value="submit" />
</form>
You write
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
In HTML, you can have many inputs in the same form with the same name, regardless of that name having a [] suffix or not. This has always been used for, say, checkboxes. Most server-side libraries will then return the values for those inputs as an array.
An example of gathering all values for inputs with a given name could be the following:
document.querySelector("#b").addEventListener("click", () => {
const values = [];
document.querySelectorAll("input[name='color']").forEach(e => values.push(e.value));
console.log(values); // outputs ["foo", "bar", "baz"] if values unchanged
});
input { display: block; margin: 5px; }
<label>Enter your favorite colors
<input type="text" name="color" value="foo"/>
<input type="text" name="color" value="bar"/>
<input type="text" name="color" value="baz"/>
</label>
<label>
Enter your favorite food
<input type="text" name="food" value="flub"/>
</label>
<button id="b">Click me to output favorite colors</button>
You can give same id to all inputs like
<input type="text" id="inputId" name="cars[]" required>'
In Javascript iterate the element to get the value
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
console.log(element[i].value);
}

Copy multiple input fields to other matching input fields with jQuery/Javascript

I have a dummy form and the actual form in which at some point I want to copy all the input values from the dummy form across to the real form.
The dummy fields will have the same names as the real form (so I can match them up).
So in dummy form:
<input name="item1" value="field1" />
<input name="item2" value="field1" />
<input name="item3" value="field1" />
and in real form:
<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />
I assume I'll need to iterate over each input in dummy form (using jQuery .each() ?) while collecting the name and value in an JS object.
Then iterate over each input in the real form, matching the name as the selector and setting the value (perhaps this can be done in the one .each() function ???)
I've started with the following code which only grabs the values (and index) into an array, but because I need two values (name and value, and index is irrelevant) I assume I'll need an object not an array, but really not sure where to begin with that.
var inputValues = [];
$("#dummyForm input").each(function() {
inputValues.push($(this).val());
});
Any help or advice much appreciated.
Map them like
$('#DummyForm [name]').each(function() {
var name = $(this).attr('name');
$('#RealForm [name="' + name + '"]').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form id="DummyForm">
<input name="item1" value="field1" />
<input name="item2" value="field2" />
<input name="item3" value="field3" />
</form>
<form id="RealForm">
<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />
</form>
You could do something like below:
$('#dummy input').each(function(){
if($('#real input[name='+$(this).prop('name')+']').length == 1)
$('#real input[name='+$(this).prop('name')+']').val($('#dummy input[name='+$(this).prop('name')+']').val())
});
Here is my Fiddle...

Particular div to refresh onsumbit using ajax or jquery

I want a particular div on a page that contains database field to refresh itself to bring out the currenty entry onsubmit of a form. the div that contains the record is called #new_entry
<div id="new_entry"></div>
<script>
$(document).ready(function(){
$("#form3").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "../calls/insert_call_love.asp",
data: data
}).success(function() {
$("#feedback").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your have loved this photo </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>
this is what i'm posting to the insert_call_love.asp
<form action="<%=MM_editAction%>" method="post" name="form3" id="form2">
<input name="comment" type="text" id="comment" size="50" />
<input name="imageField3" type="image" id="imageField3" src="../imgs/buttons/comment.png" align="bottom" />
<input name="wardrobe" type="hidden" id="wardrobe" value="1" />
<input name="comme" type="hidden" id="comme" value="2" />
<input name="comfn" type="hidden" id="comfn" value="3" />
<input name="photo_id" type="hidden" id="photo_id" value="4" />
<input name="ctype" type="hidden" id="ctype" value="picture" />
<input name="resp_email" type="hidden" id="resp_email" value="5" />
<input name="MM_insert" type="hidden" id="MM_insert" value="form2" />
</form>
In your code, you have to add a variable to success(function()) function
success(function(msg)
**"msg"**will contain data which you want to return from below url:-
url: "../calls/insert_call_love.asp",
then you can assign this data to any div
}).success(function(msg) {
$('#new_entry').html(msg);
}
Note: variable "msg" will contain all the data which you have printed on the page "insert_call_love.asp"
Well depending on what you are doing on the server side with this post...You would need to query the DB and retrieve the latest item, and send it back/echo it out as JSON.
So in pseudocode steps...
Process posted variables...
Query DB for latest entry..
Echo out as JSON...
Then do something like ...
.success(function(data) {
$('#new_entry').html(data);

Categories

Resources