Import json to html input fields with jquery - javascript

I have a json like this from a url. (Example: http//www.somedomain.com/controller/json)
[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]
I would like to import these values to an html file's form input fields with jQuery. The form is like this:
<input id="id" type="text" value="12">
<input id="event" type="text value="LOGOUT SUCCESS">
...
Is there any simple solution for this?

Since the id of each input field is the same as the name in each name/value pair, a for..in loop can do this very easily.
$.getJSON("http//www.somedomain.com/controller/json", function(json) {
json = json[0]; //the object is in the first element of the wrapping array
for (name in json)
$("form").append('<input id="'+name+'" type="text" value="'+json[name]+'"/>');
});
If you wish to just set the values of an already existing form:
$.getJSON("http//www.somedomain.com/controller/json", function(json) {
json = json[0];
for (name in json)
$("#"+name).val(json[name]);
});

You can unserialize your json :
json_string = "[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]";
var arr_from_json = JSON.parse( json_string );
And then loop on the attributes :
$.each( arr_from_json, function(i, n){
$("#"+i).attr("value",n);
});

Parse the JSON to an object. You can then iterate through it and create or set the input elements. Although you asked for it in the question, this is so trivial that there is little point in using jQuery for it (You Might Not Need jQuery).
If you wish to create the inputs:
var json = '[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]',
data = JSON.parse(json)[0];
for (var key in data) {
if (data.hasOwnProperty(key)) {
var i = document.createElement("input");
i.setAttribute('type',"text");
i.setAttribute('name',key);
i.setAttribute('value',data[key]);
document.body.appendChild(i);
}
}
If you just wish to set the values:
var json = '[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]',
data = JSON.parse(json)[0];
for (var key in data) {
if (data.hasOwnProperty(key)) {
document.getElementsByName(key)[0].value = data[key];
//or document.getElementsById("#"+key)[0].value = data[key];
}
}
<input type="text" name="id" value="" />
<input type="text" name="event" value="" />
<input type="text" name="ip" value="" />
<input type="text" name="date" value="" />

Related

How do i get submitted form (inputs like name="array[key]") type data as array/object in js to use in submit callback

I have form in which i am submitting multiple inputs containing name attributes as array like name="array[key]"
<form onsubmit="callback($(this));">
<input type="text" name="stock[quantity]">
<input type="text" name="stock[old]">
<input type="text" name="form[mrp]">
<input type="text" name="form[price]">
</form>
I have tried new formData($("form")[0]) and jQuery $("form").serializeArray() both returning name="array[key]" as string.
I want this data as multidimensional object like we got this in php when submit this form like.
<script>
function callback($form){
/*
here i want form data in js object like
{
stock : {quantity : ... , old : ....},
form : {mrp : ... , price : ....}
}
or something like this
*/
}
</script>
I am using JS, jQuery, and Vue.js in this project, actually i want to put this form data to indexedDB after successful save on server. i have different tables/objectStore for stock and form
Try this..
function callback($form) {
let result = {};
let formData = $form.serializeArray();
formData.forEach(obj => {
let inputValue = obj.name.split('[');
if (!result[inputValue[0]]) {
result[inputValue[0]] = {};
}
let innerText = inputValue[1].replace(']','');
result[inputValue[0]][innerText] = obj.value;
});
console.log(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="callback($(this)); return false;">
<input type="text" name="stock[quantity]">
<input type="text" name="stock[old]">
<input type="text" name="form[mrp]">
<input type="text" name="form[price]">
<input type="submit" value="submit">
</form>

How to fix empty array from form-control w/o mySql (PHP, AJAX, JQuery, JS)

I'm trying to create a PHP form to a nonprofit organization and would like to send an email via SMTP using PHPMailer.
My problem is that the form contains a dynamic table, where I want to store/send data to a .php file via Ajax and JSON, but it doesn't fill the array with values (even if I type $(tr).find('td:eq(0)').val(). The Ajax data also contains two addition values.
Also if I try to json_decode on the code below, the PHP breaks.
I tried getting the data by variable, and it works.
I tried to collect them in a single string which was converted to JSON, it didn't work.(The PHP doesn't send anything nor error feedbacks)
Right now I'm trying to create multiple arrays from rows. But like 2. it doesn't work
The HTML body:
<html>....
<input id="name" class="form-control" required>
<input type="email" id="email"class="form-control" required>
<table id="dynamic_field">
<tr>
<td>
<textarea id="value1" class="form-control" required></textarea></td>
<td>
<textarea id="value2" class="form-control" required></textarea></td>
.....
</tr></table>
<input type="button" onclick="sendEmail()" value="Send &arr" class="btn btn-primary">
The Script:
function sendEmail() {
var name = $("#name");
var email = $("#email");
var value1 = $("#value1");
var value2 = $("#value2");
....
var TableData;
TableData = JSON.stringify(storeTblValues());
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
value1: value1.val(),
value2: value2.val(),
TableData: TableData
}, success:...
function storeTblValues(){
var TableData = new Array();
$("#dynamic_field tr").each(function (row, tr) {
TableData[row] = {"value1": $(tr).find('td:eq(0)').text() , "value2": $(tr).find('td:eq(1)').text() , ......}
;});return TableData;
;}
I expect the output of the array TableData to be [{"value1":"Whatever in Value 1","value2":"Whatever in Value 2 ",....}]
, but what I read from this string is [{"value1":"\n ","value2":"\n ",...}]
Use $('form').serializeArray()
Example:
$('button').click(function () {
var formData = $('form').serializeArray();
console.log(formData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="your-name" placeholder="name">
<textarea name="your-text" placeholder="text"></textarea>
<button type="button">Submit</button>
</form>
Also you cant convert this array:
var searchParams = new URLSearchParams("your-name=value1&your-text=value2");
var result = {};
// Display the key/value pairs
for(var pair of searchParams.entries()) {
result[pair[0]] = pair[1]
}
console.log(result);

Jquery selector for laravel array Validation errors

I tried to display the Laravel 5.5 Ajax error Validation using jQuery automatically,
When for single field it was work, to use following code:
$.each(response.errors, function (key, value) {
el.find('input[name="'+key+'"] , select[name="'+key+'"] , textarea[name="'+key+'"]').parent().append('<div class="error right-align pink-text text-mute">'+value+'</div>');
});
The code above will append an error message to each element based on selector.
But if I use array field, for example <input type="text" name="start_date[]" />
Then I got following error validation:
{"message":"The given data was invalid.","errors":{"start_date.0":["The start_date.0 field is required when availability is 0."],"start_date.1":["The start_date.1 field is required."],"end_date.0":["The end_date.0 field is required."],"end_date.1":["The end_date.1 field is required."]}}
So my javascript couldn't find the elements start_date.0
How to select the element using jQuery with that response ? (start_date.0 , start_date.1)
thanks for all the answer, I end this problem by using id attribute, so my html tag should be like this <input type="text" id="start_date.0" name="start_date[]" />
Since jquery doesn't allow dot "." pattern in selector, My selector should be like this
el.find('input[id="select_date.0"]')
So My code should be:
$.each(response.errors, function (key, value) {
el.find('input[id="'+key+'"],input[name="'+key+'"] , select[name="'+key+'"] , textarea[name="'+key+'"]').parent().append('<div class="error right-align pink-text text-mute">'+value+'</div>');
});
Use errors['start_date.0'] instead errors.start_date.0
var myObj = {"message":"The given data was invalid.","errors":{"start_date.0":["The start_date.0 field is required when availability is 0."],"start_date.1":["The start_date.1 field is required."],"end_date.0":["The end_date.0 field is required."],"end_date.1":["The end_date.1 field is required."]}};
console.log(myObj.errors['start_date.0']);
Using start_date.0 it tries to get element 0 in object start_date, but you have this start_date.0 as element of errors so use bracket [ ] to treat start_date.0 as element of errors
var response = {"message":"The given data was invalid.","errors":{"start_date.0":["The start_date.0 field is required when availability is 0."],"start_date.1":["The start_date.1 field is required."],"end_date.0":["The end_date.0 field is required."],"end_date.1":["The end_date.1 field is required."],"dob":["Date of birth is required."]}};
$.each(response.errors, function (key, value) {
var name = $("input[name='"+key+"']");
if(key.indexOf(".") != -1){
var arr = key.split(".");
name = $("input[name='"+arr[0]+"[]']:eq("+arr[1]+")");
}
name.parent().append('<div class="error right-align pink-text text-mute">'+value[0]+'</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input type="text" name="start_date[]" value=""></div>
<div><input type="text" name="start_date[]" value=""></div>
<div><input type="text" name="end_date[]" value=""></div>
<div><input type="text" name="end_date[]" value=""></div>
<div><input type="text" name="dob" value=""></div>
error: function(data){
var response = JSON.parse(data.responseText);
var errorString = '<ul style="list-style: none;">';
$.each( response.errors, function( key, value) {
errorString += '<li><small>' + value + '</small></li>';
});
errorString += '</ul>';
$("#errors").html(errorString);
}

Value of set of input tags in a JS array

I have a set of input tags
<input name= "keys[]" type="text">
<input name= "keys[]" type="text">
<input name= "keys[]" type="text">
<input name= "keys[]" type="text">
<input name= "keys[]" type="text">
Is it possible to get all the input of type text values in an array using the name keys[]
I tried this
$('input[name="keys[]"]').val()
But I got the value of the first input tag only.
I wanted to get a array of the values of these input tags. Is it possible without going thru an iteration?
Thanks
Try serializeArray() it will return an array of objects with name and value.
$('input[name="keys[]"]').serializeArray()
You can use map:
$('input[name="keys[]"]').map(function(key, input) { return input.value; });
You can try something like
var array= new Array();
$('input[name="keys[]"]').each(function(index){
array[index] = $(this).val();
});
Hope I help!
http://jsfiddle.net/Gh6Z9/4/
var values = new Array();
$.each( $('input[name="keys[]"]'), function() {
values.push($(this).val());
});
console.log(values);

Associative array passing as empty string

I am trying to pass an array to PHP via Ajax, but the array is being passed as an empty string. This is my code when creating the array:
var params = new Array();
var inputs = new Array();
inputs = $(":input");
$.each(inputs, function(key, value) {
params[value.id] = value.value;
});
alert(params);
Before that there are around 20 inputs that look like this:
<input name="first_name" id="first_name" type="text" class="medium"/>
<input name="last_name" id="last_name" type="text" class="medium"/>
The alert(params) is just giving me an empty string. However, alert(params['first_name']) actually gives me the first_name input value.
Why isn't the array going through?
Can you try this -
$(document).ready(function() {
var params = new Array();
var inputs = $(":input");
$.each(inputs, function(key, value) {
//I guess the problem was that params is array and your id's were strings
//array's elements are arr[0], arr[1],
//not like arr[firstname], arr[lastname], ...
params[value.id] = value.value;
});
alert(params);
});
//moved everything inside $(document).ready
with this -
<input name="first_name" id="0" value="1" type="text" class="medium"/>
<input name="last_name" id="1" value="2" type="text" class="medium"/>
<!-- Changed id's from string to numbers. -->
Update:
Also, try this it might help you understand whats going on -
$(document).ready(function() {
var params = {}; //use object instead of array
var inputs = $(":input");
$.each(inputs, function(key, value) {
params[value.id] = value.value;
});
for(var prop in params) {
alert(prop + " = " + params[prop]);
}
});
Notice: params is an object now not an array.
With this -
<input name="first_name" id="firstname" value="Your first name." type="text" class="medium"/>
<input name="last_name" id="lastname" value="Your last name." type="text" class="medium"/>
You can't simply pass a variable to the server, you need to serialize it into name, value pairs, or use JSON.
I'm slightly unsure what you're trying to accomplish by creating an array in Javascript like this.
Your best bet is probably to use the JQuery command serialize then grab the data using $_GET

Categories