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

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.

Related

How to submit form when any value selected from populated textbox using javascript or jQuery without clicking submit button

search.php
In this form, when we type something in textbox, matching words are fetched from api_search.php page and displayed as seen in attached screenshot.
<form role="form" id="frm_search" name="frm_search" method="POST" action="./api_search_p.php" enctype="multipart/form-data" >
<script type="text/javascript">
$(function()
{
$( "#txt_itemname" ).autocomplete({
source: '../user/api_search.php'
});
});
</script>
<input type="text" id="txt_itemname" name="txt_itemname" class="form-control" required data-validation-required-message="Please enter something here">
<button type="submit" class="btn btn-warning"><i class='fas fa-search'></i> </button></span>
</form>
api_search.php
Textbox on search.php is populated from API result data from this page.
-- API data are coming using curl in $result array --
$json = json_decode($result, true);
$arr_searchTerm = array();
if (is_array($json) && !empty($json))
{
foreach ($json as $key1 => $level1)
{
if (is_array($level1) && !empty($level1))
{
foreach ($level1 as $key2 => $level2)
{
array_push($arr_searchTerm, $level2['TITLE']);
}
}
}
}
echo json_encode($arr_searchTerm);
Currently need to click submit button to submit the form. But I want to do so when any word from fetched result is selected / clicked then form should be submitted immediately without clicking submit button.
I tried onselect="this.form.submit()" & onchange="this.form.submit()" with textbox but form is not submitted on any of javascript events.
Please let me know how can I make this working as expected.
Screenshot
You can use select function in your code
$( "#txt_itemname" ).autocomplete({
source: '../user/api_search.php',
select: function(e, ui){
this.value = ui.item.value;
this.form.submit();
}
});
You can try this way. in this case, you can make your API call every time someone inserts something. This means every single letter will make a call
document.querySelector("#txt_itemname").addEventListener('input',(e)=>{
...
})
and additionally, if you do it as an API try to look at this too http_responses with PHP

how to display the json array value in html input

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"]);

Calculate input of html text fields with php

At the moment, I try to create a survey in a webpage. At the end of the survey, users are able to fill two text fields with values. With these values, my plan is to calculate an output, displayed for them at the same page. So:
Input: a
Input: b
Result: ab+b-ab (do not concentrate this please, its just an example)
My plan is that the user is able to fill the two input fields and by a buttonclick, a php function is calculating the result field (by my own algorithm depending on input - this is already working) and fills this field. Do i have to link to another webpage for this purpose?
And how is it possible to grab the two input values and give it to my php function?
And as last thing, how is it possible to start a php function either embedded in html or in an own file?
I tried your solution and some others as well (fetching inputA and inputB from the DOM with document.getElementById does not work. Below is my code
<form>
InputA:<br>
<input type="text" id="inputA"/></br>
InputB:<br>
<input type="text" id="inputB"/></br>
Output:<br>
<input type="text" id="output"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js" ></script>
<script type="text/javascript">
$("#calculate").click(function(){
$.get( "submit.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
</script>
submit.php:
<?php
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
$output = $value1 + $value2;
echo($output);
}
?>
When I check with firebug the error, i get a: no element found exception in both (html and php) files. Seems like the problem is, that with: value1: $("#inputA").val(); no value is givent to the server or it can not be handled there.
If i grab the value from the DOM, I can "bring" the value inside the .click function but there is still a "no element found exception" by calling the submit.php.
I have no idea what i am doing wrong, any suggestions? Do i need to install/bind anything in for using JQuery?
After some additional changes, it finally worked (one thing was the header line in the submit.php file):
<form>
WorkerID:<br>
<input type="text" id="workerId"/></br>
CampaignId:<br>
<input type="text" id="campaignId"/></br>
Payment Code:<br>
<input type="text" id="payCode"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript">
$("#calculate").click(function(){
$.get( 'submit.php', { wId: $('#workerId').val(), cId: $('#campaignId').val()} )
.done(function( data ) {
$('#payCode').val(data.payCode);
});
});
and submit.php:
<?php
header('Content-Type: text/json');
$workerId = $_GET['wId'];
$campaignId = $_GET['cId'];
$payCode = $campaignId . $workerId;
$result = array("status" => "success",
"payCode" => $payCode);
echo json_encode($result);
?>
To simplify, i am using jQuery, doing this in vanilla JS is a real pain in the a** in my opinion.
You can use .get(), which is the GET shorthand for .ajax().
With that code, you bind a handler on your submit button and make a AJAX request to your PHP and fill the result your PHP gives into your result field asynchronously.
$("#calculate").click(function(){
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
Also change your submit to something like this:
<input name="go" type="button" value="Calculate" id="calculate" >
Like that, your button won't submit a form and therefore synchronously load your PHP.
Since you seem new to JavaScript and you had this comment
my button, but here i got redirected to submit, no idea how i can go back to page before with filled textfield
in your question, i'll tell you, JavaScript works while the DOM (Document Object Model) is loaded, means you can access your elements when already loaded and alter them.
Getting the value of a input is as easy as that in jQuery:
$("#inputA").val();
With the AJAX you get what your php will return in data.
// the { value1: $("#inputA").val(), value2: $("#inputB").val() } object
// is what you send to your PHP and process it
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
// data is what your php function returned
});
Using JS you can now change your elements as just said, effectively meaning to change the value of your output here:
$("#output").val(data);
"Working" Example: JSFiddle (There is no PHP to access to, so it will not do anything actively)

JQuery: Post variable to the second file, and when the enter key pressed, the web will direct me to the first search result page

I created an instant search similar to google search using JQuery.
Q1.
The post to search.php using search function searchq() then print out the returned result works fine, but the createq() function doesn't work at all, it didn't triggered when I using alert() to test, any ideas on how to fix it so the variable txt could be post to create_object.php (which has been post successfully to search.php).
Q2
I want to create a function that allow the user to direct to the first search result(which is anchored with an url) when the enter is pressed, any idea how to achieve this? I tried something but it messed up.
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<input type="submit" value=">>">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose
alert("hi");
$.post( "create_object.php",{creatVal:txt} );
}
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Two questions in one!
Q1: The problem appears to be a misspelling in the onclick function:
onclick=\"creatq()\"
should be
onclick=\"createq()\"
Q2: Pressing enter will submit the form, so you use the submit handler to catch the enter press then redirect:
$(function() { //shorthand document.ready function
$('form ').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
$url = $('#search_output div:first a').attr('href'); // find first link
window.location.href = $url; // redirect
});
});
(credit to this answer for most of the work)

How to dynamicaly change data in dropdown on change of text box Jquery

I have a text box and dropdown. Text box contains the province name and the dropdown contains the the cities. I want to chnage the province of the text box and dynamically change the dropdown related to the text in the textbox. I am using codeigniter framework. My view is as follows and I get the data from the database. I think there is a problem with the onchange or that kind of event of the text box (this code worked for change event for another dropdown. But it is not working for the taxt box- so the other logic is ok but I cant figure out the event of the textbox. What is the right event for the text box ? My code
<script> .........................<script>
$(document).ready(function(){
$('#provincial').on('input',function()
{
var id_provincia = $('#provincial').val();
$.ajax(
{
type: "POST",
dataType: "json", // I ADDED THIS LINE
url:"tenda/get_comuni/"+id_provincia,
success: function(comuni)
{
$('#comuni').empty();
$.each(comuni,function(id_comune, nome_comune)
{
var opt = $('<option />');
opt.val(id_comune);
opt.text(nome_comune);
$('#comuni').append(opt);
});
}
});
});
});
</script>
</head>
<body>
<?php $comuni['#'] = 'seleziona'; ?>
<div id="tenda">
<label for="provincia">provincia: </label><?php echo form_dropdown('id_provincia', $provincie, '#', 'id="provincia"'); ?>
<?php echo form_input('id_provincial','', '#', 'id="provincial"'); ?>
<label for="comune">comune: </label><?php echo form_dropdown('id_comune', $comuni, '#', 'id="comuni"'); ?><br />
</div>
For a textbox you can use keyup or onchange (fired when element loses focus) events.
$('#provincial').keyup(function(event){...});
If you want to sent POST request when you press enter button, you can handle it using this code snippet:
if (event.which == 13) {
event.preventDefault();
.. // DO POST Request
}

Categories

Resources