auto-complete field wordpress with ajax - php

I'm doing a project on WordPress and I'm having some trouble with the auto-complete field on my form. No input is shown and no error in console. I created a small database on one of the WordPress database. I'm not very familiar with AJAX so please be kind :)
jQuery(document).ready(function($) {
jQuery('#dish').autoComplete({
source: function(name, response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
});
This is my jQuery code and I added the admin-ajax in the same folder as I was thinking it didn't find it (it's my_serach.js)
function ajax_listings() {
global $wpdb; //get access to the WordPress database object variable
//get names of all businesse
$name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$sql = "select name
from $wpdb->global
where name like %s
and post_type='portfolio' and post_status='publish'";
$sql = $wpdb->prepare($sql, $name);
$results = $wpdb->get_results($sql);
//copy the business titles to a simple array
$titles = array();
foreach( $results as $r )
$titles[] = addslashes($r->name );
echo json_encode($titles); //encode into JSON format and output
die(); //stop "0" from being output
i add this code on the functions.php on the theme i'm working on
<form method = "POST">
<div id = "container">
<div><label class="plate_label">Dish:</label><input type="text" name="dish_name[]" id="dish" class="dish" placeholder="Enter plate name" />
<label class="quantity_label">Quantity:</label><input type="text" name="dish_quantity[]" class="quantity" placeholder="Enter gram or pieces/slices" /></div>
</div>
and last the form where it should show the suggestions from the database.

Try this code.
jQuery(document).ready(function($) {
jQuery('#dish').autoComplete({
source: function(name, response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'http://caloriless.com/wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
});
change ajax url url: 'wp-admin/admin-ajax.php', or url: 'http://caloriless.com/wp-admin/admin-ajax.php',

Related

Posting the input value with tag in the background

I want it to be posted as an id in the field that users see, but when posting.
https://prnt.sc/z5Hw61LuKoGy -> the area the user sees
https://prnt.sc/plR-s1eb4OGE -> Id data sent with value tag in background
When I post like this, I see it as 0 in my database.
https://prnt.sc/XjPHKrthej2M
Why not 4?
Can you help me?
I am using jQuery UI Autocomplete.
MY JQUERY CODE
$("#urun_olustur .col-10 input").autocomplete({
source: function(request,response){
$.ajax({
url: 'ajax.php',
type: 'post',
dataType: 'json',
data: {
search: request.term
},
success: function(data){
response(data);
}
});
},
select: function(event,ui){
$(this).val(ui.item.label);
$(this).attr("value",ui.item.value);
return false;
}
});
MY AJAX.PHP CODE
if (isset($_POST["search"])) {
$search = $_POST["search"];
$query = $db->query("SELECT * FROM test WHERE test_name LIKE '%".$search."%'");
$response = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$response[] = array(
"value" => $row["id"],
"label" => $row["test_name"]
);
}
echo json_encode($response);
exit;
}
You can get like this I have add following snippet please check.
I have take the change event you can use any other required event as per your convenience
$("#ac_text_id").on('autocompletechange change', function() {
$('#ac_text_op').html('You selected: ' + this.value);
}).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control ui-autocomplete-input" name="ac_text" id="ac_text_id" autocomplete="off" value="4">
<div id="ac_text_op"></div>

Update div in html using Ajax function failed

I'm trying to display the search result of my page under the the search area. So I used AJAX to display the result in a div. but I could'nt get it work.
I have three main pieces, the div, the searchResult page and the ajax function
<input type="text" name="studentName">
<button type="submit" name="searchByName" onclick='get_info();'>بحث</button>
<div id="searchResult"><b></b></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function get_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "NameSearchResult.php", // Name of the php files
data: {name: <?php echo $_POST['studentName']; ?>},
success: function(html)
{
$("#searchResult").html(html);
}
});
}
and my search Page:
<?php
include_once 'dbConfigBDO.php';
$studentName = $_POST["name"];
$counter=0;
$emptyString = "لايوجد";
$sql = "SELECT * FROM Student";
$result = $conn->query($sql);
$row_count = $result->rowCount();
if ($row_count > 0){
.......... }
Now when I search nothing appears, although it works when I put all the code in one page (which would be messy in term of the appearance of the result!).
From function return the output as per below:
return json_encode($result);
In ajax call use dataType:"json" and show your html
Example ajax call:
$.ajax({
type: "POST",
dataType:"json",
url: "NameSearchResult.php", // Name of the php files
data: {name: $("#studentName").val()},
success: function(html)
change code like this
<input type="text" name="studentName" id="studentName">
<button type="submit" name="searchByName" onclick='get_info();'>بحث</button>
<div id="searchResult"><b></b></div>
<script>
$.ajax({
type: "POST",
url: "NameSearchResult.php", // Name of the php files
data: {name: $("#studentName").val()},
success: function(html)
{
$("#searchResult").html(html);
}
});
}
</script>
inside ajax success method try catch what you are getting
success: function(html)
{
console.log(html);
}
if you getting something then your code must be work.

pass array values from AJAx to PHP

I am facing some issues. I am trying to insert array in MYSQL using AJAX and PHP but its not working following is my code:
HTML:
<input type="text" class="form-control" name="invoice" id="invoice" placeholder="piece">
<input type="text" class="form-control" name="pieces[]" id="pieces" placeholder="Qty">
I want to pass fields from ajax to php. I am using following code in ajax.
var inv = $("#invoice").val();
var pieces = $("#pieces").val();
$.ajax({
type: "POST",
url: "query.php",
data: "piece="+pieces+"&inv="+inv,
success: function(data){
$("#result").html(data);
}
});
following is the PHP code:
<?php
$piece = $_POST[piece];
foreach ($piece as $key => $value) {
$query = mysql_query(insert into items values('$value', '$_POST[inv]');
}
?>
Try this code
jQuery
var inv = $("#invoice").val();
var pieces = $("#pieces").val();
$.ajax({
type: "POST",
url: "query.php",
data: {'in':inv,'pi':pieces},
success: function(data){
$("#result").html(data);
}
});
php
<?php
$pieces = $_POST[piece];
foreach($pieces as $piece){
{
$query = mysql_query(insert into items values ('$piece','$_POST[inv]');
}
?>
Try this:
JQuery:
var inv = $("#invoice").val();
var pieces = $("#pieces").val();
$.ajax({
type: "POST",
url: "query.php",
data: {'in':inv,'pi':pieces},
success: function(data){
$("#result").html(data);
}
});
Php code :
<?php
$inv = $_POST['in'];
$piece = $_POST['pi'];
$query = mysql_query(insert into items values '$piece','$_POST[inv]');
?>
This is the simple example, please use mysql encapsulation to get value for preventing sql injection.

Typeahead input field and query passed to PHP with AJAX

I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call

getting the rest of the row in a database using JQuery

Ok, so I have this search box in which people typein a food item. When they press the button I need that input to be send to a .php file. That php file will look op the calories of that food item (thats in my database) and output the food item name and calories. All this need to be done without reloading the page so I started figuring out how JQuery works.
However I am stuck, I don't know what to put in the data field of the jquery function and how I can 'catch' that data in the .php file. Can someone give me an idea? thanks a lot! (see the ??????'s for things i don't understand). Also, the data that comes back needs not to be in an alert box in the end, but update some table on my page, how can i do this? which JSON (?) Jquery function do I need?
what I have up until now:
in head:
<script type="text/javascript">
function contentDisp()
{
$.ajax({
type: 'POST',
url: 'getFood.php',
data: '????????',
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
and in body:
<form autocomplete="off">
<p>
Product:
<input type="text" name="food" id="food" class="food_name_textbox" onmouseover="javascript: this.className='food_name_textbox_mouseover';" onmouseout="javascript: this.className='food_name_textbox';" / >
</p>
<button id="zoek" type="button" onClick="contentDisp();">Zoek</button>
</form>
and in getFood.php:
<?php
require_once "config.php";
$id = "??????"
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>
$.ajax({
type: 'POST',
url: 'getFood.php',
data: {'foodnametextbox' : $('#food').val() },
datatype: "json",
success: function(data){
$('#table').html(data);
}
});
<?php
require_once "config.php";
$id = $_POST['foodnametextbox']; //escape and validate this input before using it in a query
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>
<script type="text/javascript">
function contentDisp()
{
var textSearch = $("#myText").text();
$.ajax({
type: 'POST',
url: 'getFood.php',
data: textSearch,
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
PHP:
$id = $_POST['textSearch'];

Categories