I am trying to input some text on a input field and on click the button it should display data from mysql on another input field name autofiller.
$(function () {
$('#button').on('click', function () {
var text = $('#fromInput');
$.ajax({
url:"serv.php",
method: "GET",
data: {
"id": text
},
success: function(data) {
var name=JSON.parse(data);
document.getElementsByClassName("autofiller").value=name.name;
}
});
});
});
HTML form
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="button" value="button" id="button">
This is my back-end php script-->
<?php
$link=mysqli_connect("localhost","root","","employee");
$data=$_GET["id"];
$result = mysqli_query($link,"SELECT * FROM user where userid='$data'");
header('Content-type:application/json');
exit(json_encode($result));
?>
I hope this would help you to solve
$(function () {
$('#button').on('click', function () {
var text = $('#fromInput');
$.ajax({
url:"serv.php",
method: "GET",
data: {
"id": text
},
success: function(data) {
var name=JSON.parse(data);
$(".autofiller").val(name.name);// Try this
}
});
});
});
document.getElementsByClassName("autofiller")[0].value=name.name;
You should use getElementById() to get the single element reference because getElementByClassName() will return an array of reference of elements with that class name.
try this
document.getElementById("autofiller").value=name.name;
where autofiller should be the "id" instead of class
in HTML
<input type="text" id="autofiller"/>
Maybe you should try this:
var text = $('#fromInput').val();
Update
There are many bugs in your code, as below:
In Backend
$result = mysqli_query($link,"SELECT * FROM user where userid='$data'");
This does not return the data as you expect, you have to use mysql_fetch_array to fetch the data from the result which can be something like this:
$sql = "SELECT * FROM users where id='$data'";
$result = mysqli_fetch_array(mysqli_query($link,$sql));
In frontend
You don't need to parse the data to JSON as you are already sending the response with a JSON data:
var name=JSON.parse(data);
Instead you can do something like this:
document.getElementById("autofiller").value=data.name;
Notice here, Using id instead of class is a better approach, as you would want to set the value to a specific input, not a group of inputs, so you might have to add an id to autofiller like this
<input type="text" class="autofiller" id="autofiller"/>
Related
I want to check the value of the input field in the database and put the text of the second column of this value to another field using laravel.
html code
<input type="text" name="ccode[]" id="target" class="td-size" autocomplete="off" >
<input type="text" name="cname[]" id="codename" class="td-size">
javascript code
<script type="text/javascript">
$(document).ready(function(){
$('#target').change(function(){
var code = $('#target').val();
if(code !== null){
$.ajax({
type: "POST",
url: "{{ route('getcodename') }}",
data: {code:code},
success:function(data){
alert(data);
}
});
}else{
alert("no");
}
});
});
</script>
controller:
public function getcodename(Request $request)
{
$codename = DB::table("communitydata")
->where("code",$request->code)
->pluck("c_name","cd_id");
return response()->json($codename);
}
web Route
Route::get('getcodename',[DropdownController::class, 'getcodename'])->name('getcodename');
database screenshot:
Form Screenshot
You can try this,
$(this).closest('#codename').val(data);
It will find closest element with id codename and change its value.
Jquery closest
I have a simple HTML form that includes an input field and a submit button.
How can I use JQuery to get the text from the input field live and then send that data to a PHP file that evaluates the data?
Form:
<form action='file_that_will_process_data.php' method='POST'>
<input id='text' type='text' name='txt'>
<button type='submit'>Submit</button>
</form>
Edit: here's what I want it to look like
echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>';
echo "<script>$(function() {
$('button').on('click', function() {
var txt = $('#txt').val();
sendTextTo_file_that_will_process_data_AndReturnTheValueThat_file_that_will_process_dataReturns(txt)
})</script>";
Your current code doesn't need jquery to get the text from the input field in PHP.
When the user clicks on the Submit button, you can retrieve the text from the input with this code that you've to put in the file_that_will_process_data.php file
<?php
if (isset($_POST['txt'])) {
var_dump($_POST['txt']); // $_POST['txt'] contains the text from the input field
// TODO: make your treatment here...
}
But if what you're looking for is to allow users to make something like a live search, you don't need the submit anymore. Then you can do something like this using jquery:
$(function() {
$('input[name="txt"').on('keyup', function() {
const $form = $(this).closest('form');
$.ajax({
type: "POST",
url: $form.attr('action'),
data: {
txt: $(this).val()
},
success: function (data) {
// data contains the result of your treatment in the file_that_will_process_data.php file. Do whatever you want with it here
}
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action='file_that_will_process_data.php' method='POST'>
<input type='text' name='txt'>
<button type='submit'>Submit</button>
</form>
I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}
I have tried other answers but none have worked. The javascript code is supposed to submit a list of product id's to a php page. When products are selected, the submit button triggers the submit function.
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
console.log(ids);
//send the ids to api
bundle = [];
$('.bundle-list').empty();
$('.total').html('No item in bundle');
$('.submit').addClass('hide');
}
I have tried inserting this line in the function
document.getElementByID("test").value = bundle;
and a hidden tag within the form but can't get the var to submit to PHP
<input type="hidden" id="test" name="test" visibility="hidden"></input>
Where should the position of the hidden element be relative to the JS code? and any other methods of retrieving the ID's?
Either by $.post or $.get variable you can send data to PHP file, but i think you want to save pids in hidden field, but you are not update its value on submit. like
$('#test').html('YOUR DATA')
Try this..
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
$.ajax({
url: 'YOUR_URL HERE',
type: 'POST',
data: { qry: ids },
success: function(data) {
///WHEN SUCCESS
}
},
error: function(e) {
}
});
}
I have a javascript var that returns the value of a input text ID "ven_prod", with the value of "ven_prod" I need to make a search in my database without submiting the page.
I can't use a javascript var in the java code, so i've setted the value in a hidden input text ID "prod_hidden", but I need to submit it to get the value with the java code and make the search...How do I do it ?
<input id="ven_prod" type="text" placeHolder="Código de Barras" autofocus>
<input id="prod_hidden" type="text" value="">
<script>
$('#ven_prod').keypress(function (e)
{
if(e.keyCode==13)
{
var table = document.getElementById('tbprodutos');
var tblBody = table.tBodies[0];
var newRow = tblBody.insertRow(-1);
var prod = document.getElementById('ven_prod').value;
var qtd = document.getElementById('ven_qtd');
var barra = prod.substring(0, 12);
var num = prod.substring(14, 16);
document.getElementById('prod_hidden').value = barra;
var ref = <%=pd.getProdutosBarra(request.getParameter("prod_hidden")).getPro_referencia()%>;
OR
var ref = <%=pd.getProdutosBarra(JS VAR 'barras HERE).getPro_referencia()%>;
if(prod.length==16) {
var newCell0 = newRow.insertCell(0);
newCell0.innerHTML = '<td>'+ref+'</td>';
var newCell1 = newRow.insertCell(1);
newCell1.innerHTML = '<td>'+num+'</td>';
var newCell2 = newRow.insertCell(2);
newCell2.innerHTML = '<td>'+qtd.value+'</td>';
var newCell3 = newRow.insertCell(3);
newCell3.innerHTML = '<td>R$ '+valor+'</td>';
var newCell4 = newRow.insertCell(4);
newCell4.innerHTML = '<td>'+barra+'</td>';
document.getElementById('ref').value = '6755';
document.getElementById('imgsrc').src = './?acao=Img&pro_id=1';
document.getElementById('valortotal').value = 'Testando novo valor';
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
} else {
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
alert("Código de barras inválido!");
}
return false;
}
});
</script>
you can make ajax call using jQuery as follows. will submit your form data as well along with hidden elements.
var form = jQuery("#YourFormID");
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(), // serializes the form's elements.
success: function(data) {
console.log(data);
}
});
value of a input text named "pro_barras"
Are you sure? Look at this:
<input type="hidden" id="pro_barras">
its not the name of the input, its the ID. You can try using this:
<input type="hidden" name="pro_barras">
And now, you can use $.ajax to send the request to a new page, where you will request the data from the database. And then you'll write the response, and take it back on the first page.
What it will do depends on how you use it. I will try to ask you to simply use serialize() method by jQuery API, this will let you to create a simple URL param with the data from the form, use it as:
$.ajax({
var data = $('#formid').serialize(); // serialize the form..
url: "link/to/file.cshtml",
data: data,
success: function (datares) {
$('#resultid').html(datares); // write the result in the element
}
})
If you want to get only the value from that field you can use
var data = $('input[name=pro_barras]').val();
without submiting the page.
Your page will have to be submitted when you click on input type="submit" button. To prevent that you can use
$('#idofsubmitbutton').click(function () {
return false; // stop execution and stay on page..
}
Then the ajax will continue, other method is to remove the input type="submit" and use <button></button> which won't cause any submission.
get the value with the java code
This isn't java :) Its JavaScript, they are totally different. :)
a) You can use like that:
$("#pro_barras").bind("change paste keyup", function() {
//$('.someClass').submit();
$('#it_is_form_id').submit(); // it call form's submit function
});
The piece of code detected when input text change. To more info see also here If you want to customize form submit function
$('#it_is_form_id').bind("submit", function(){
//alert("submit");
// make here simple ajax query
return false; //<-- it is used so that default submit function doesn't work after above code.
});
Don't forget, all code will be inside
<script>
$(function() {
// your code must be here
});
</script>
b) If you don't want to use form, you can do like that:
<script>
$(function() {
$("#pro_barras").bind("change paste keyup", function() {
var text = $("#pro_barras").val();
$.ajax({
type: "POST",
url: "yourUrl",
data: text,
success: function(res){
console.log(res);
},
error: function(err){
console.log(err);
}
});
});
});
</script>
Making simple ajax query:
Using Jquery post method
https://stackoverflow.com/a/8567149/1746258
Pass entire form as data in jQuery Ajax function
You could also add a custom attribute to your input element (in Jquery):
<input type='text' id='pro_barras' customattr='myCustomInfo'/>
<script>
var customValue = $('#pro_barras').attr('mycustomvar');
alert(customValue);
</script>
Fiddle