how to display the json array value in html input - javascript

I am using the following jquery
<script type="text/javascript">
$(document).ready(function(){
$("#serviceId").change(function(){
var service_id=$("#serviceId").val();
$.ajax({
type:"post",
url:"<?php echo base_url();?>index.php/pranasInventory/get_service_amount",
data:{service_id:service_id},
success:function(data)
{
$('#amount').append(data);
},
});
});
});
</script>
I got the follwing responce in html input field
<input type="number" name="amount" id="amount" class="form-control" placeholder="Amount">[{"service_amount":"2000000"}]</input>
I want to display the service_amount in input value field.
please help me

Just try with:
$('#amount').val( data[0].service_amount );

Instead of append the data object to input control, you should assign value to input control. You can try any one code
$('#amount').val(data[0].service_amount );
or
$('#amount').val(data[0]["service_amount"]);

Related

How to load data to specific input value in javascript?

I am having this piece of code, to load data form PHP after users click on link.
Then I am displaying received data to div id="vies":
<script>
$(document).ready(function(){
$("#data-received").hide();
$("#click_me").click(function(){
$("#data-received").show();
$("#vies").load('127.0.0.1/get_data/', {VATID : $("#vat_id").val()});
});
});
</script>
<label>VATID</label>
<input type="text" id="vat_id" name="vat_id" value="">
Check VATID
<div id="data-received">
<label>Data received from PHP</label>
<div id="vies">.. checking ..
<input type="text" name="put-here" id="put-here" value="test-value"/>
</div>
</div>
The question is how to load data and insert as a input value here:
<input type="text" name="put-here" id="put-here" value="test-value"/>
instead to whole div.
<script>
$(document).ready(function(){
$("#data-received").hide();
$("#click_me").click(function(){
$("#data-received").show();
$.post('http://127.0.0.1/get_data/', {
VATID : $("#vat_id").val()
}, function(data) {
$('#put-here').val(data);
});
});
});
</script>
load() is a convenience function which does an ajax request and then replaces the target element with the data returned. When you don't want to replace the whole element, use jquery.ajax() to do the request. In the success callback you can set your value to the returned data using .val().
$.ajax({
url: "127.0.0.1/get_data/",
data: {VATID : $("#vat_id").val()}
}).done(function(data) {
$( '#put-here' ).val(data);
});

how to fill the values in form, data generated from jquery

how to fill textfield with the data which i'm getting via ajax in the textfield, what code i worte is doing this, it's not replacling the value already enterend by the user, suppose user wants to write "autocomplete" and he wrote "au" now the html will show hint as "autocomplete" now when user clicks my textfield looks like this "au,autocomplete" but it should show "autocomplete" how to resolve this?
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#sku').keyup(function(){
var len = $('#sku').val().length;
if(len >= 2)
{
var value = $('#sku').val();
$.post(
'<?php echo base_url();?>index.php/testing/autocomplete',
{sku:value},
function(data){
$('#feedback').html(data);
}
);
}
});
$(document).on('click','p',function(){
$('#sku').val(this.id+',');
});
});
</script>
<input type="text" name="sku" placeholder="SKU1,SKU2,SKU3" id="sku"/>
<div id="feedback"></div>
If I understand this correctly in you should set textfield that you are typing into.
function(data){
$('#sku').text(data);
}
assuming that data returned is string.

jQuery: How to submit an array in a form

I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?
Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});
Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);
Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>

Get value of each on blur() event

I have a page which contain a bunch of text area generated by a PHP script. There is a hidden input type that contains an id of a variable. Basically what I want to do is to call the .ajax() JQuery method on .blur() on any of the text areas and pass the value of the textarea + the id from the hidden input.
All of my text areas are named like this: tr1,tr2,tr3,etc. And the hidden fields:tr_id1,tr_id2,etc
So how can I get the value from both elements so I can use them somewhere else?
This may give you an idea
HTML
<textarea name="tr1"></textarea>
<input type="hidden" name="tr_id1" value="1" />
<br />
<textarea name="tr2"></textarea>
<input type="hidden" name="tr_id2" value="2"/>
​
JS
​$(function(){
$('textarea').on('blur', function(e){
var txtAval=$(this).val();
var txtId=$(this).prop('name').replace('tr','');
var txtHval=$('input:hidden[name="tr_id'+txtId+'"]').val();
// txtAval contains textarea's value and txtHval contains text input's value
$.ajax({
type: "POST",
url: "some_url",
data: {txtarea:txtAval, txthidden:txtId}
//or
//data: "txtarea="+txtAval+"&txthidden="+txtId
}).done(function(msg) {
// ...
});
});
});​
jQuery ajax reference: Here.
See the values on the console here.

How to pass multiple checkboxes using jQuery ajax post

How to pass multiple checkboxes using jQuery ajax post
this is the ajax function
function submit_form(){
$.post("ajax.php", {
selectedcheckboxes:user_ids,
confirm:"true"
},
function(data){
$("#lightbox").html(data);
});
}
and this is my form
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
From the jquery docs for POST (3rd example):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)
Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.
var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
data.push($(this).val());
});
Here's a more flexible way.
let's say this is your form.
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
And this is your jquery ajax below...
// Don't get confused at this portion right here
// cuz "var data" will get all the values that the form
// has submitted in the $_POST. It doesn't matter if you
// try to pass a text or password or select form element.
// Remember that the "form" is not a name attribute
// of the form, but the "form element" itself that submitted
// the current post method
var data = $("form").serialize();
$.ajax({
url: "link/of/your/ajax.php", // link of your "whatever" php
type: "POST",
async: true,
cache: false,
data: data, // all data will be passed here
success: function(data){
alert(data) // The data that is echoed from the ajax.php
}
});
And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.
<?php
print_r($_POST); // this will be echoed back to you upon success.
echo "This one too, will be echoed back to you";
Hope that is clear enough.
This would be better and easy
var arr = $('input[name="user_ids[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The following from Paul Tarjan worked for me,
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,
var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just change name_of_your_form to the name of your form.
I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,
<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>
This way if no boxes are checked, it will still set the array with a value of "none".
function hbsval(arg) {
// $.each($("input[name='Hobbies']:checked"), function (cobj) {
var hbs = new Array();
$('input[name="Hobbies"]:checked').each(function () {
debugger
hbs.push($(this).val())
});
alert("No. of selected hbs: " + hbs.length + "\n" + "And, they are: " + hbs[0] + hbs[1]);
}

Categories

Resources