Autocomplete issue - php

I am trying to display users list in input field with jquery auto-complete function. I facing issue in displaying name and selection update value to field.
My PHP Code:
include '../_db.php';
// get what user typed in autocomplete input
$name = trim($_GET['name']);
$param = "%{$name}%";
$query = $conn->prepare('SELECT emp_number, emp_firstname, emp_lastname FROM `hs_hr_employee` WHERE emp_firstname LIKE ? OR emp_lastname LIKE ? ');
$query->bind_param('ss', $param,$param);
$query->execute();
$query->bind_result($emp_number,$emp_firstname,$emp_lastname);
$a_json = array();
$a_json_row = array();
while( $query->fetch() )
{
$a_json_row["emp_number"] = $emp_number;
$a_json_row["fname"] = $emp_firstname;
$a_json_row["lname"] = $emp_lastname;
array_push($a_json, $a_json_row);
}
$json = json_encode($a_json);
print $json;
$query->close();
My JS Code
$(function()
{
$( "#search-emp" ).autocomplete(
{
source: function (request, response)
{
var form_data = {
ajax : '1',
name : $("#search-emp").val(),
actioncall : 'search-emp'
};
$.ajax({
type: "POST",
url: "_ajax.php",
data: form_data,
success: function(response)
{
$.each( response, function( key, value )
{
//alert( key + ": " + value );
console.log('element at index ' + key + ' is ' + JSON.parse(value));
});
//console.log(response);
},
dataType: 'json'
});
}
}, {minLength: 3 });
});
Getting Response
[{"emp_number":1,"fname":"Arslan","lname":"Hassan"},{"emp_number":2,"fname":"Muneeb","lname":"Janjua"
},{"emp_number":3,"fname":"hr","lname":"user"}]
My HTML code
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">Employee Name: </label>
<input id="search-emp" type="text" class="form-control" placeholder="*">
</div>
<div class="form-group">
<label for="exampleInputEmail2">Date Range: </label>
<input type="text" class="form-control" id="dp-from" placeholder="From">
<input type="text" class="form-control" id="dp-to" placeholder="To">
</div>
<button type="submit" class="btn btn-primary">Genrate Report</button>
</form>

The problem it's because jQuery auto-complete wants to have 2 fields named label and value. The content from label will be displayed in the auto-complete.
Because your server return other name for the keys you have 2 options:
Change the server to return a json like:
[{"emp_number":1,"fname":"Arslan","lname":"Hassan", "label":"Arslan Hassan", "value": "Arslan Hassan"},....]
Or on the success callback from ajax create an array with this fields (label and value) and pass this array to response() callback.
You can find more informations here: http://api.jqueryui.com/autocomplete/#option-source

In your AJAX request,
$.ajax({
type: "POST",
url: "_ajax.php",
data: form_data,
success: function(response)
{
$.each( response, function( key, value )
{
//alert( key + ": " + value );
console.log('element at index ' + key + ' is ' + JSON.parse(value));
});
//console.log(response);
},
dataType: 'json'
});
specify the contentType to get the correct response.
contentType: "application/json",

Related

how to show select2 after select2 the data?

i just want to choose data again after select2 with select2, but not showing the data
loadUser();
function loadUser() {
$('#wg').empty();
$.ajax({
url: "<?php echo site_url('administrator/admin/getWg'); ?>",
type: 'GET',
dataType: 'JSON',
}).done(function(data) {
console.log('data: ', data);
$.each(data, function(i, item) {
$('#wg').append($('<option>', {
value: item.workgroup,
text: item.workgroup
}));
});
});
$('#wg').change(function() {
wg = $(this).val(),
$.ajax({
url: '<?php echo site_url("administrator/admin/getWg2"); ?>/' + wg,
dataType: 'JSON',
type: 'GET',
}).done(function(data) {
console.log('use: ', data);
$('#name').val(data.name);
});
});
}
but, if i use the input data without the select2 the data showing but only the first array, how to showing the all data ?
<div class="col-md-6">
<label for="wg">Workgroup</label>
<select class="form-control select2" id="wg" name="wg"></select>
</div>
<div class="col-md-6">
<label for="name">Name</label>
<input class="form-control select2" id="name" name="name">
</div>
just how to use the select2 twice.

Submit form with data values inserted from AJAX in Laravel

I have the following section of html:
<div class="box-body" style="display:none;" id="claimFreightDetails">
<input type="text" disabled class="form-control" id="pulledProNumber" name="pulledProNumber"><br>
<strong>Origin Information</strong><br>
<textarea disabled class="form-control" id="claimFreightOrigin" name="claimFreightOrigin"></textarea><br>
<strong>Consignee Information</strong><br>
<textarea disabled class="form-control" id="claimFreightConsignee" name="claimFreightConsignee"></textarea><br>
<strong>Weight</strong>
<input type="text" disabled class="form-control" id="claimWeight" name="claimWeight"><br>
<strong>Pieces Count</strong><br>
<input type="text" disabled class="form-control" id="claimPieces" name="claimPieces"><br>
</div>
Now, I have an AJAX POST request where the response inserts the returned data into those fields and textareas:
<script>
$(document).on('click', '#pullDetails', function() {
$('#freightBillDetails').removeClass('hidden');
$.ajax({
type:'POST',
url: '/carrier/claims/pullDetails',
data: {
num: $('input[name=proNumber]').val(),
_token: $('input[name=_token]').val()},
dataType: 'json',
success: function(data) {
if(data.details != undefined) {
console.log('success');
var results = JSON.parse(data.details);
$('#pulledProNumber').val(results.SearchResults[0].SearchItem);
$('#claimWeight').val(results.SearchResults[0].Shipment.Weight);
$('#claimPieces').val(results.SearchResults[0].Shipment.Pieces);
$("#claimFreightOrigin").html(results.SearchResults[0].Shipment.Origin.Name + '
'+ results.SearchResults[0].Shipment.Origin.Address1 +'('+results.SearchResults[0].Shipment.Origin.Address2+')
'+ results.SearchResults[0].Shipment.Origin.City + ', '+ results.SearchResults[0].Shipment.Origin.State + ' '+ results.SearchResults[0].Shipment.Origin.PostalCode);
$("#claimFreightConsignee").html(results.SearchResults[0].Shipment.Consignee.Name + '
'+ results.SearchResults[0].Shipment.Consignee.Address1 +'('+results.SearchResults[0].Shipment.Consignee.Address2+')
'+ results.SearchResults[0].Shipment.Consignee.City + ', '+ results.SearchResults[0].Shipment.Consignee.State + ' '+ results.SearchResults[0].Shipment.Consignee.PostalCode);
$('#openInvoicesOverlay').html('');
$('#openInvoicesOverlay').removeClass('overlay');
$('#claimFreightDetails').show();
}else{
console.log('failed');
console.log(data);
console.log(data.details['SearchResults'].SearchItem);
}
},
error: function(data) {
console.log('error');
console.log(data);
}
});
});
</script>
The problem is, when I go to submit the form that surrounds this (many more fields, this section is just pulled through an API from a Third-Party), all of the data fields except the ones that are referenced in the AJAX are included in the POST request for the overall form.
You need to also remove disabled property after you get ajax response using this
$('.YourDisabledInput').prop("disabled", false);
here is your solution:
<script>
$(document).on('click', '#pullDetails', function() {
$('#freightBillDetails').removeClass('hidden');
$.ajax({
type:'POST',
url: '/carrier/claims/pullDetails',
data: {
num: $('input[name=proNumber]').val(),
_token: $('input[name=_token]').val()},
dataType: 'json',
success: function(data) {
if(data.details != undefined) {
console.log('success');
var results = JSON.parse(data.details);
$('#pulledProNumber').val(results.SearchResults[0].SearchItem);
$('#claimWeight').val(results.SearchResults[0].Shipment.Weight);
$('#claimPieces').val(results.SearchResults[0].Shipment.Pieces);
$("#claimFreightOrigin").html(results.SearchResults[0].Shipment.Origin.Name + '
'+ results.SearchResults[0].Shipment.Origin.Address1 +'('+results.SearchResults[0].Shipment.Origin.Address2+')
'+ results.SearchResults[0].Shipment.Origin.City + ', '+ results.SearchResults[0].Shipment.Origin.State + ' '+ results.SearchResults[0].Shipment.Origin.PostalCode);
$("#claimFreightConsignee").html(results.SearchResults[0].Shipment.Consignee.Name + '
'+ results.SearchResults[0].Shipment.Consignee.Address1 +'('+results.SearchResults[0].Shipment.Consignee.Address2+')
'+ results.SearchResults[0].Shipment.Consignee.City + ', '+ results.SearchResults[0].Shipment.Consignee.State + ' '+ results.SearchResults[0].Shipment.Consignee.PostalCode);
$('#openInvoicesOverlay').html('');
$('#openInvoicesOverlay').removeClass('overlay');
$('#claimFreightDetails').show();
$('#pulledProNumber').prop("disabled", false);
$('#claimWeight').prop("disabled", false);
$('#claimPieces').prop("disabled", false);
$('#claimFreightOrigin').prop("disabled", false);
$('#claimFreightConsignee').prop("disabled", false);
}else{
console.log('failed');
console.log(data);
console.log(data.details['SearchResults'].SearchItem);
}
},
error: function(data) {
console.log('error');
console.log(data);
}
});
});
</script>
just change the the .val to .attr('value') as laravel is pulling from the DOM and jQuery .val doesnt reflect there.
you can check this link
jQuery changing form values not affecting the DOM
also you can test it on jQuery website
disabled input fields will not be submitted with the form. That's the behaviour of disabled.
I guess you were using the wrong name for input.
There is no input name "proNumber". In the HTML it is "pulledProNumber".
And also the field is disabled too.
Please update your code and see if it fix the problem.

How to display the AJAX response in input field and pass that value to PHP?

I am getting Id value from my AJAX and I am also able to display it. I set the Id value input text in the AJAX and displaying it on HTML like this <input value="4864" id="compare_id" type="hidden"> Now I have to pass that value to PHP to get the result from database.
Is there any idea how to do it?
AJAX
$(document).ready(function() {
arr = [];
$("[type=checkbox]").click(function() {
$.ajax({
type: "POST",
url: "includes/compare_process.php", //
data: 'users=' + arr,
dataType: 'json',
success: function(msg) {
$("#pics_name,#pics_Id").empty();
$.each(msg, function() {
$("#pics_Id").append("<input type=hidden value=" + this.Id + " id=compare_id name=compare_id>");
//alert(msg.id);
});
},
error: function() {
alert("failure");
}
});
});
});
//tried AJAX
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: "GET",
url: 'includes/compare_process.php?key=compare_details',
data: $('#search-form').serialize(),
success: function(response) {
//$('#response').html(response);
alert(response);
}
} );
});
});
PHP
<div class="bg-popup" style="display: none;" id="open_compare_popup">
//popup code here
<?php
$val2=htmlentities($_GET['compare_id']);
echo $val2;
$sql = "SELECT * FROM `request` WHERE Id IN($val2)";
?>
//end popup code here
This output I am getting from AJAX
<form action="#" method="get" id="search-form">
<span id="pics_Id">
<input value="4869" id="compare_id" name="compare_id" type="hidden">//output
<input value="4884" id="compare_id" name="compare_id" type="hidden">//output
<input value="5010" id="compare_id" name="compare_id" type="hidden">//output
</span>
<button class="action action--button action--compare" type="button" id="search-button" name="search-button"><span class="action__text">Compare</span></button>
</form>
I have to pass the input value to PHP after clicking on a button.

Dropdown List ajax is not working

There are 2 drop down list:
Project
Plot Details
My Question is: Once Project is selected then Plot Details Get Populated properly but, when Plot Details of Dropdown is get select then Chrome hangs up.
To continue, I have to refresh the page. I want the Plot Details(drop down) value to call another ajax call.
javascript
$(document).ready(function() {
$('.get_member_name').live('change', function() {
alert('hello')
var project = $('#project').val();
var plot_details = $('#plot_details').val();
var base_url = $('#base_url').val();
if (project && plot_details) {
$.ajax({
type: "POST",
url: base_url + "admin/get_member_name",
data: {'category': category},
dataType: "html",
success: function(result) {
alert(result)
}
})
}
});
})
HTML
<div class="form-group">
<label class="col-md-3 control-label" for="inputSuccess">
Plot Details :
</label>
<div class="col-sm-9">
<select class="form-control get_member_name" name="plot_details" required="required" id="plot_details">
<option value="" id="opp12">Select Plot</option>
</select>
</div>
</div>
PHP
public function get_plot_details() {
if ($this->session->userdata('role_id') == 1) {
$data['record'] = $this->db->get_where('plot_details', array('project_id' => $this->input->post('project')))->result();
print_r($this->load->view('admin/ajax_data', $data, TRUE));
} else {
redirect('home/login');
}
}
View Page
if (isset($record) && $record != NULL && $record != "") {
foreach ($record as $m) {
echo '<option value="' . $m->id . '"> ' . $m->plot_number . ' Area ' . $m->total_area . '</option>';
}
}
I could see you have used 'project' in your php to fetch the records from DB. But in your ajax you are passing the request data 'category'. Might be this one is causing issue. So instead of
$.ajax({
type: "POST",
url: base_url + "admin/get_member_name",
data: {'category': category},
dataType: "html",
success: function(result) {
alert(result)
}
})
use
$.ajax({
type: "POST",
url: base_url + "admin/get_member_name",
data: {'project': project},
dataType: "html",
success: function(result) {
alert(result)
}
})

Values from javascript to PHP

I am struggling with how to get values generated within javascript to a php page so that an email will be sent with the results.
function sendmemail(){
var data = 'result=' + result.val();
$.ajax({
url: "process.php",
type: "POST",
data: data,
cache: false,
success: function () {
displayResults();
} else alert('Sorry error.');
});
}
That else part is a syntax error, you can't add an else clause in that way.
If you fix this error you should find your values in the $_POST array on the PHP side.
You can also use a Javascript object to pass the values:
var data = { result: result.val() }
which is more readable.
process.php...
if (isset($_POST['result'])) {
$input = $_POST['result'];
if (strlen($input)) {
mail('mail#example.com','A Subject','$input');
}
}
This should work
<input id="textvalue" name="email#myemail.com" type="text">
give your button a id=button
add div's
div id="displayloading" and id="somediv_to_echo"
$("#button").click(function() {
$('#displayloading').fadeIn('slow', function() {
my_value = $("#textvalue").val().replace(/ /g,"+");
$("#somediv_to_echo").load("mail_send.php?d=" + my_value + "&md=" + new Date().getTime());
$("#textvalue").val("");
});
});
Lets do it form the begining.
HTML:
<form id="frm">
<input type="text" name="email" value="sample#sample.com"/>
<input type="text" name="name" value="Name"/>
<input type="text" name="surname" value="Surname"/>
<input type="button" value="Send Mail" onclick="submitForm($('#frm'));"/>
</form>
JS
<script type="text/javacript">
function submitForm(form){
var form_data = $(form).serialize();
$.ajax({
type: "POST",
url: "process.php",
data: form_data,
dataType: 'json',
success: function(data){
if(data.result === 1){
$(form).html("<h2>FORM SEND SUCCESS</h2>");
}else{
$(form).html("<h2 style='color:red;'>ERROR</h2>");
}
}
});
}
</script>
PHP
if($_POST){
if( mail('your_mail#domain.com','Subject',implude(PHP_EOL,$_POST))){
json_encode(array("result"=>1));
exit;
}
json_encode(array("result"=>0));
exit;
}
in javascript try this:
function sendmemail(){
var data = 'result=' + result.val();
var img = document.createElement('img');
img.src='process.php?'+data;
img.style.position='absolue';img.style.width='1px';img.style.height='1px';img.style.top='-10px';
document.body.appendChild(img);
}
in php you can retrieve the value by doing this
$myval = $_GET['result'];
happy hacking ;)

Categories