Send hidden input data using AJAX - javascript

I am using AJAX live search plugin.
It passes input data to backend-search.php
backend-search.php selects data from the database and return to the search page.
Now I want to pass one hidden input value with the search query.
Hidden Input
<input type="hidden" name="group" value="<?php echo $grp_id; ?>" />
Following is my html in search.php
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search..." />
<div class="result"></div>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var term = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(term.length){
$.get("backend-search.php", {query: term}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
How do I send the data of the hidden input field with above js?

You could use $.post instead of $.get like this:
$.post( "backend-search.php?query="+ term, { hidden_key: "hidden_value"})
.done(function(data) {
alert( "Data Loaded: " + data );
});
So, customizing it for your code,
if(term.length) {
// get value of hidden field
var hidden_value = $('[name="group"]').value();
// make a post request, but also pass query params
$.post("backend-search.php?query=" + term, { group: hidden_value})
.done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
}
Here, everything after the ? mark is passed as a query string (i.e. via get method) whereas the hidden field is passed by the Post method.
In your Php script, use print_r($_REQUEST) to verify that you get the 2 parameters as desired.
Also, you should encode URI parameters like this encodeURIComponent(term) to make sure your javascript does not break if the user enters special characters

Related

How do I pass Button Value as a variable in Ajax?

I have a problem. I want to exchange certain data using PHP, MySQL and Ajax.
To do this I always have to pass the ID of a field to my backend, so I can continue working with this ID.
How do I pass the value from my button to my URL in Ajax?
What do I have to consider?
row['id'] is my variable (PHP)
HTML Code:
<a class='commentSikayet'>
<button id='commentSikayet' name='commentSikayet' value='{$row['id']}'>
Şikayet et
</button>
</a>
Ajax:
$(document).ready(function () {
$("#commentSikayet").click(function () {
$.ajax({
url: 'report_comment.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('Erfolgreich gemeldet.');
}
});
});
});
Assuming there might be more than one data sets in your page I modified your example to the following snippet. Each buttons has a data-id attribute that identifies the current dataset (the id would be supplied through your PHP script as $row["id"]):
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let data={cmt_id: $(this).data("id"),
value: $(this).prev().val()}
$.post("https://jsonplaceholder.typicode.com/comments",data)
.done(function (result) {
console.log("Erfolgreich gemeldet:",result);
});
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div><input type="text" value="some text">
<button name="commentSikayet" data-id="123">Şikayet et</button></div>
<div><input type="text" value="some other text">
<button name="commentSikayet" data-id="124">Şikayet et</button></div>
<div><input type="text" value="more text">
<button name="commentSikayet" data-id="125">Şikayet et</button></div>
In your backend PHP script (taking the place of the above typicode-URL) you can pick up the values from the $_POST superglobal as
$_POST["cmt_id"]; // id value
$_POST["value"];. // actual text content
Since you're listening for the click event on the button, you can access it via this in your handler function.
Add the name / value pair to your AJAX data option
$("#commentSikayet").on("click", function (e) {
e.preventDefault();
$.post("report_comment.php", {
bar: $("#bar").val(),
[ this.name ]: this.value // add name / value in here
}).done(function (result) {
alert('Erfolgreich gemeldet.');
});
});
This will include commentSikayet=rowIdValue in the POST request body which you access on the PHP side via...
$rowId = $_POST["commentSikayet"];

access a specific input in an input array

<td><input type="text" name="product_code[]" id="product_code1" class="form-control input-sm" /></td>
I have been creating an invoice system ... how can I access a specific input to get its text ( product code ) and load the description from the database???
I know how to access all the elements but cannot access the specific one the user is typing text :(
using the below code trying to get the value returns all the values of the product code text inputs and only works for the first one
$('[name="product_code[]"]').keyup(function() {
var values = $("input[name='product_code[]']")
.map(function(){return $(this).val();}).get();
alert(values);
});
#AlexisGarcia lets say user types product code I want to access the db and retrieve product description for that product code ... how do I get through javascript or jquery the value of the specific input the user is typing???
You have to use AJAX to get that from Database.
First you need to get what the user has typed (input value), and then send it to AJAX. Here is an example:
$('#product_code1').keyup(function(){
var user_text = $(this).val();
$.ajax({
method: 'post',
url: 'link_to_your_controller',
data: {text: user_text},
dataType: 'json',
complete: function(data) {
//..DO SOMETHING WITH RESULT FROM DB
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td>
<input type="text" name="product_code[]" id="product_code1" class="form- control input-sm" />
</td>
You need to learn about AJAX to do what you need.
You can start by reading https://www.w3schools.com/xml/ajax_intro.asp
$('.input-sm').keyup(function() {
var values = $(this).val();
alert(values);
});
Try this code, you will get what you want

Jquery Autocomplete not working correctly

I'm using jquery autocomplete.In my case I have multiple autocomplete textbox and hidden field on my page.
e.g
<input class='myclass' type='text'> </input>
<input class='.emp_num_hidden' type='hidden'> </input>
<input class='myclass' type='text'> </input>
<input class='.emp_num_hidden' type='hidden'> </input>
and so on...
so when I fire change event on hidden field then it is raised multiple time
below is my code:
$(".myclass").each(function() {
var $empName= $(this);
var $empNumber = $empName.next('input:hidden');
//things to do
//Setting variable e.g url...
$empName.autocomplete(url,{
//code...
}).result(function(event,data,formatted)
{
$empNumber.val(formatted).change();
});
});
In above code $empNumber holds the hidden field which is used to store autocomplete value i.e in this case when
we select any text from autocomplete then that selected employees number will get store in hidden field.
Based on this hidden field value I want to do ajax call which will return full details of the employee based on his
employee number.
So I have written hanldler to change event of the hidden field as below.
$(.emp_num_hidden).on('change',function (
)};
here 'emp_num_hidden' is the class of the hidden field.
Please suggest how can I prevent multiple event on hidden field change.
This is done using the $(this) object. Since the change event has a target, it will only be effecting one element. The callback function is being executed on this element, this. For example:
$(".emp_num_hidden").on('change', function (e){
alert($(this).val());
});
What will happen is that an alert window will be shown when the hidden field is changed, containing the employee number from only that hidden field. You will also notices there are a few fixes to your code.
Personally, I would make use of both id and class attributes on your objects. This gives you wide scope and narrow scope to your selectors.
Example:
HTML
<input class='myclass' type='text' id='entry-txt-1' />
<input class='emp_num_hidden' type='hidden' id='hide-txt-1' />
<input class='myclass' type='text' id='entry-txt-2' />
<input class='emp_num_hidden' type='hidden' id='hide-txt-2' />
jQuery
$(function(){
var $empName, $empNumber;
$(".myclass").each(function(key, el) {
$empName= $(el);
$empNumber = $empName.next("input[type='hidden']");
// things to do
// Setting variable e.g url...
$empName.autocomplete(url, {
//code...
}).result(function(e, d, f){
$empNumber.val(f).change();
});
});
$(".emp_num_hidden").on('change', function(e){
var empId = $(this).attr("id");
var $employeeNumberField = $("#" + empId);
// Do the needful...
});
});
Taking this a bit further, you may want to consider making use of data attributes. You may also want to look at select event for Autocomplete. Something like:
$(function(){
$(".myclass").autocomplete({
source: url,
select: function(e, ui){
$(this).val(ui.item.label);
$(this).data("emp-number", ui.item.value);
$.post("employeedata.php", { n: ui.item.value }, function(data){
$("#empData").html(data);
});
return false;
}
});
});
This assumes that url returns an array objects with label and value properties. This would add the Employee Number as a data-emp-number attribute to the field that the user was making a selection from. The label being their Employee Name, and the value being their Employee Number. You could also use this callback to show all the other employee data based on Employee Number.
A working example: https://jsfiddle.net/Twisty/zmevd0r0/

Send selected data back to original window

I have a file called bpSearch. Inside bpSearch, I have a MODAL window, called addNewModal. Within addNewModal, I have 2 INPUT fields called partnerName and partnerCode. I have a button that once clicked, opens into another MODAL window, called searchPartnerModal.
Here is the a portion of the FORM inside addNewModal:
<form action="bpSearch.php" method="get">
<input type="text" readonly id="partnerName" name="partnerName" />
<input type="text" readonly id="partnerCode" name="partnerCode" />
Go
</form>
When the user clicks GO, it opens searchPartnerModal.
searchPartnerModal is where the user will enter either a code or a name (doesn't have to be both). But upon hitting SEARCH, I use an AJAX call that returns JSON that I parse and eventually return in a UL field called pNames. We're still inside searchPartnerModal.
Here is the FORM inside searchPartnerModal:
<form action="bpSearch.php" method="get">
<input type="text" id="pNameSearch" name="pNameSearch" />
<input type="text" id="pCodeSearch" name="pCodeSearch" />
<input type="button" class="btn" id="pSearch" name="pSearch" value="search" />
</form>
When the user enters a name, I use jquery to send it over to a PHP script that will then return the data in a UL tag.
Here is the jquery that will search if the user enters a name:
$('#pSearch').on('click', function()
{
var partnername = $('#pNameSearch').val();
if($.trim(partnername) != '')
{
$.post('api/pNameSearch.php', {partnername: partnername}, function(data)
{
var obj = JSON.parse(data);
$('#pNames').empty();
var htmlToInsert = obj.map(function (item)
{
return '<li><a id="getPInfo" href="javascript:;"
onclick="getPInfo()" data-selname="'+item.FULL_NAME+'"
data-selcode="'+item.PARTNER_CODE+'">'
+ item.FULL_NAME + ' - '
+ item.PARTNER_CODE + '</a></li>';
}).join('');
$('#pNames').html(htmlToInsert);
});
};
});
With this code, I am able to send the name to search the database table for a valid name. The data is returned via JSON and is parsed and displayed inside the UL tag (called pNames) as LI tags, each with an A tag with their own data-attributes, called data-selname and data-selcode.
Now what I need to do is once the user clicks on one of the returned data links inside pNames, I need to send it back to the previous modal window, addNewModal.
This is where I'm stuck.
If you look inside the Jquery above, after I parsed the JSON, you will see that I created another Javascript function inside the A tag of each returned piece of data, called getPInfo().
Here is what I got so far for the function getPInfo() :
function getPInfo()
{
var selname = ($('#getPInfo').attr('data-selname'));
var selcode = ($('#getPInfo').attr('data-selcode'));
}
At this point, I can alert both variables (selname and selcode) and get them to display in an alert window.
What I want to do is send both of those variables back to addNewModal in the respective INPUT fields, called partnerName and partnerCode.
So selname will go to partnerName and selcode will go to partnerCode.
I didn't display the PHP script that returned the data.
Change the anchor id=getPInfo to class=getPInfo since you have multiple anchors. Next, handle the click event of the anchor and extract the data attributes and set the corresponding form elements in the addNewModal form. Following should work based on the markup i see so far.
$(function(){
$('body').on('click', 'a.getPInfo', function (e) {
var $a = $(e.srcElement || e.target);
$('#partnerName').val($a.attr('data-selname'));
$('#partnerCode').val($a.attr('data-selcode'));
$('#searchPartnerModal').modal('hide'); //assuming bootstrap modal
});
});

Pass two values of input fields to script and combine for searching

In my current project, i have two text fields in which user will input requirement and area respectively. Grabbing those values, i have to do an ajax call and fetch the necessary data from the database and return it. The ajax call has to be made as and when the input exceeds 4 characters in any of the text fields. As long as there was only one text field i didn't have any problem.
<input type="text" value="requirement" onkeyup="function1(this.value)" />
<input type="text" value="area" onkeyup="function2(this.value)" />
<script>
function function1(valuetosearch)
{
//make the ajax call
}
</script>
<script>
function function2(valuetosearch2)
{
//make the ajax call
}
</script>
How can i combine the two scripts and pass the data in ajax as an array? P.S The main reason for scripting is to do a search combining the two input fields. For example if someone enters house, vehicle in requirement field and place1,place2 in area field. The result search should display the result for the following1) place1 house2) place1 vehicle3) place2 house4) place2 vehicle
you can set id for each elemnt and get the other's value using
document.getElementById("id1").value
and then make the ajax request
http://jsfiddle.net/JMpgU/
$("input").keyup( function () {
var str = $(this).val() + " " + $(this).siblings().val();
alert(str);
//make the ajax call
});
with any number of inputs:
http://jsfiddle.net/JMpgU/2/
$("input").keyup( function () {
var strings = $(this).
siblings().
addBack().
map(function () {
return $(this).
val();
}).
toArray();
//make the ajax call
});
Try this
<input type="text" value="requirement" onkeyup="functionABC()" id="First" />
<input type="text" value="area" onkeyup="functionABC()" id="Second" />
<script>
function functionABC()
{
var searchString=$("#First").val()+" "+$("#Second").val();
//make the ajax call
}
</script>
Pass "searchString" as a param.

Categories