I'm working on a web application which was not developed by me and I have the following autocomplete code which works with an AJAXcall:
$("#tags").autocomplete({
minLength: 2,
source: function (request, response) {
$.ajax({
url: "http://lainz.softwebsrl.it/ajax/autocompletecibo",
dataType: "json",
crossDomain: true,
type : 'post',
data:{
valore: request.term,
},
success: function (data) {
response(data);
console.log(data);
}
});
}
and below in the file I have:
<div class="div1" style="float: left">
<strong>Cerca Prodotto</strong><br/><br/>
<form class="form">
<div>
<input type="text" id="tags" value="">
</div>
<div>
<img class="btnaggiungi" src="http://lainz.softwebsrl.it/img/carrello.jpg" alt="Aggiungi" id="add_newProduct"/>
</div>
</form>
</div>
The problem is that I don't understand how to access the received JSON from PHP. PHP queries MySQL and in the end performs this:
$ris2 = array();
foreach($ris as $single)
{
$value = $single["cibo"];
$category = $single["categoria"];
$id = $single["id"];
$ris2[] = array(
"value" => $value,
"id" => $id,
"category" => $category
);
}
$valuesJson = Zend_Json::encode($ris2);
echo $valuesJson;
Where in $ris contains the result of the query with fetchAll(). How can I access value, id, category when the AJAX terminates? Where are they?
Check 'data' value in a callback function, success.
success: function (data) {
response(data);
console.log(data);
}
If type of data value is object,
console.log(typeof data, data.id, data.value);
If data is not expected value, check on a XHR response data of Chrome development networks tabs.
Related
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>
How to take multiple value when autocomplete with ajax in codeignator
view
<input type="text" class="form-control" name="" id="search">
<div id="result"></div>
ajax
$(document).ready(function() {
$("#search").autocomplete({
minLength: 1,
source: function(request, response) {
$.ajax({
url: "<?php echo base_url(); ?>index.php/Admin/ajaxPro",
dataType: 'json',
crossOrigin: true,
type: 'POST',
data: {
search: request.term
},
success: function(data) {
response(data);
}
});
},
select: function(event, ui) {
$("#result").append(
"<div>" + ui.item.value + "</div>"
);
},
});
});
controller
public function ajaxPro()
{
$term = $this->input->get('term');
// var_dump($term);
$this->db->like('business_name', $term);
$resultSet = $this->db->get("user_table")->result();
$data = [];
foreach($resultSet as $rs){
$data[] = $rs->business_name;
}
header('Content-Type: application/json');
echo json_encode($data);
}
When I retrieve data using autocomplete, the only business_name is attached to the select: function Only the business name is available in the item .value, how do you get the corresponding value of the business name?
Please check the database
Now if I select the business name, how do I append the Email and rating in the result?
In WordPress I have a load more button that makes an AJAX request to get more posts. This works by detecting a click event on the button and then making a request to a PHP script that runs a query like $query = new WP_Query();.
I want to use this same function with a few different post types, what would be the best way to expose the post type to my AJAX function?
$.ajax({
type: "POST",
dataType: "json",
url: ajax_get_posts_object.ajax_url,
data: {
action: "ajax_get_posts",
security: ajax_get_posts_object.ajax_nonce,
current_page: next_page,
categories: $selectedCategories,
tags: $selectedTags,
},
beforeSend: function(xhr) {
load_more.text("Fetching...");
},
success: function(response) {
if (response) {
console.log(response);
// An array to store new items added via AJAX
var new_items = [];
// Run through JSON
$.each(response.posts, function(key, value) {
var $new_item = $(`<div class="grid-item article-post-card ${value.category["slug"]} ${value.tags ? value.tags[0]["slug"] : ''}">
<a class="article-post-card__anchor" href=" ${value.permalink}" alt="${value.title}">
<div class="article-post-card__featured-image-container">
<div class="article-post-card__overlay"></div>
<div class="article-post-card__featured-image">${value.thumbnail}</div>
<div class="article-post-card__category-label">${value.category["name"]}</div>
</div>
<div class="article-post-card__content-wrapper">
<div class="article-post-card__publish-date">
<time class="updated" datetime="${value.post_time}">${value.date}</time>
</div>
<div class="article-post-card__title">${value.title}</div>
<div class="article-post-card__excerpt">${value.introduction}</div>
</div>
</a>
</div>`);
new_items.push($new_item[0]);
});
next_page >= response.pages ? disableLoadMore(true) : disableLoadMore(false);
rebuildGrid($grid, new_items, '*');
updateFilterCount(response.post_count);
// Update boolean so that page count is not reset
load_more_has_run = true;
next_page++;
// If the AJAX function returned no data
} else {
load_more.remove();
}
},
error: function(xhr, status, error) {
console.log("There was an error", error);
}
});
});
You can simply add in the data:{} object a post_type element
$.ajax({
type: "POST",
dataType: "json",
url: ajax_get_posts_object.ajax_url,
data: {
action: "ajax_get_posts",
security: ajax_get_posts_object.ajax_nonce,
current_page: next_page,
categories: $selectedCategories,
tags: $selectedTags,
post_type: 'your_post_type'
},
...
});
and then use it in your WP_Query()
$post_type = key_exists('post_type', $_POST) ? $_POST['post_type'] : 'post';
$query = new WP_Query(
'post_type' => $_POST['post_type'],
...
);
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',
I am using Ajax to post my data, while using inspect elemet, I can see the post data from all other fields, but text area field comes empty, so the data fails to be saved to the database.
function addblog() {
save_method = 'add';
url = "<?php echo site_url('index.php/blog/post_new_blog')?>";
$.ajax({
url: url,
type: "POST",
data: $('#addblog').serialize(),
dataType: "json",
success: function (data) {
alert('Saved');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
}
HTML:
<div id="editor-one" class="editor-wrapper"></div>
<textarea id="descr" class="text" name="desc" style="display:none;"></textarea>
PHP:
public function post_new_blog()
{
$data = array(
'blog_title' => $this->input->post('title', true),
'blog_content' => $this->input->post('desc', true),
'blog_tags' => $this->input->post('tags', true),
);
$insert = $this->main_model->save_new_posts($data);
echo json_encode(array("status" => TRUE));
}
You are sending data as follows:
data: $('#addblog').serialize(),
does your
<textarea id="descr" class="text" name="desc" style="display:none;"></textarea>
inside html element with id addblog?
Meanwhile, i didn't understand why you set display to none for textarea?