Jquery autocomplete with Ajax from PHP not working - javascript

The following ajax call
var whatever = [];
$.ajax({
url: "myScript.php",
success: function (response) {
whatever = response.split(",");
}
});
is generating:
"ABC,DEF,GHI,JKL,"
Which are the values I want to use in JQuery autocomplete:
$('#conta').autocomplete({
source:whatever
});
However, nothing is displayed in the autocomplete popup.
If I type the values directly in JS, it works perfectly:
var whatever=[
"ABC",
"DEF","GHI","JKL"
];
But why isn't it working when generated by PHP?

try put $('#conta').autocomplete({
source:whatever
});
in the success callback function

In your source your php array needs to have rows with a "label" key like this:
foreach($rows as $key)
{
$results[] = array('label' => ($key['nome']));
}
echo json_encode($results);
Also if your database rows are not encoded in utf8 you need to encode them otherwise it will be "null":
$results[] = array('label' => utf8_encode($key['nome']));
UPDATE:
myScript.php:
...
foreach($rows as $key)
{
$results[] = array('label' => ($key['nome']));
}
echo json_encode($results);
Javascript:
$(function(){
$('#conta').autocomplete({
source:"myScript.php"
});
});

Related

Can I send filtered data with Ajax back to PHP file and write them again on page?

I implemented my Custom Post Type and content is listed on my page in while loop in that way:
$args = array('post_type' => 'studien', 'order' => 'ASC', 'posts_per_page' => 4 );
$loop = new WP_Query($args);
if($loop->have_posts()):
while($loop->have_posts()) : $loop->the_post();?>
<div class="col-md-6">
// data are listed here
</div>
<?php endwhile;
endif;
?>
And on my submit I try to filter data according to some custom taxonomies:
$ = jQuery;
var search = $("#search-studien");
var searchForm = search.find("studien");
$(document).ready(function () {
$('#studien').submit(function (evt) {
event.preventDefault();
var data = {
action: "studien_search",
type: $("#taxonomy-market-type").val(),
};
var html;
$.ajax({
url: ajaxurl,
data: data,
success: function (response) {
if(response)
{
// probably here I need to send filtered data back to PHP file and write them again
}
}
});
})
});
I use custom shortcode and callback() function:
function search_callback()
{
header('Content-Type: application/json;charset=utf-8');
$type = "";
$type = $_GET['type'];
$args = array(
"post_type" => "studien",
"post_per_page" => -1,
"relation" => "AND"
);
if($type != "") {
$args['tax_query'][] = array(
'taxonomy' => 'market',
'field' => 'slug',
'terms' => $type
);
$search_query = new WP_Query($args);
// echo json_encode($search_query);
}
else{
$search_query = new WP_Query( $args );
}
if ( $search_query->have_posts() ) {
$result = array();
while ($search_query->have_posts()) {
$search_query->the_post();
$result[] = array(
"id" => get_the_ID(),
"title" => get_the_title(),
"permalink" => get_permalink(),
);
};
wp_reset_query();
echo json_encode($search_query);
}
else {
// nothing
}
wp_die(); global $argsAjaxFilter;
$argsAjaxFilter = $search_query;
}
As you can see, $search_query represents my filtered data. This is method according to tutorial, but I can`t use response array() ... and best way for me is to send $search_query in some way to PHP file, where I can write my new Custom Post Type data again. Please, someone has advice for me? Is that good proposal?
So the main problem is to be able to send the rendered html to the browser. For that, we're going to need a template so we can reuse it in various places.
// your-theme/studien.php
<div class="studien-wrapper">
<?php
if($wp_query->have_posts()):
while($wp_query->have_posts()) : $wp_query->the_post();
// Do the thing
endwhile;
endif;
?>
</div>
Next, we need to load it whenever is needed. We can do it by using get_template_part. This function will pass some global variables automatically (such as $wp_query) to the template, you can have a look at the source code to learn more. When using it in "ajax mode" we need to capture the output, not send it to the browser (although we could) so we use output buffering. For "normal pages" just omit those calls.
// Set up query args
global $wp_query = new WP_Query($args);
ob_start(); // Capture the output.
get_template_part('studien');
$html_result = ob_get_clean();
And now is a matter of composing the response:
$result['html'] = $html_result;
if (!is_array($type)) {
$type = array($type);
}
$result['query_terms'] = $type;
$json = wp_json_encode($result);
echo $json;
wp_die();
You could also keep track of the search terms on the client side and avoid the last part. Depends on what you need.
To update the page you can do the following in your ajax call:
$.ajax({
url: ajaxurl,
data: data,
success: function (response) {
$('.studien-wrapper').replaceWith(response.html);
// Update search terms, etc
}
});

CakePHP can't get ajax GET working

I can't seem to get AJAX POST or GET working with my CAKEPHP site. I am trying to create autocomplete but can't seem to submit or fetch the data using ajax. I can get auto complete working using tags but I cannot display the data from my table. I am not sure what is going wrong if i'm not using the right url or some other problem.
Here is my search.ctp
<?php use Cake\Routing\Router; ?>
<?php echo $this->Form->input('id', ['type' => 'text']); ?>
<script>
$.ajax({
type: "POST",
url: "<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>",
success: function(response) {
$("#id").autocomplete({ source: response });
}
});
</script>
Here is my search function in my InvoicesController.
public function search()
{
$this->loadComponent('RequestHandler');
if ($this->request->is('ajax'))
{
$name = $this->request->query['term'];
$resultArr = $this->Invoices
->find()
->where(
['Invoices.id LIKE' => ($name . '%')],
['Invoices.id' => 'string']
);
$resultsArr = [];
foreach ($resultArr as $result)
{
$resultsArr[] = (strval($result['id']));
}
$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', ['resultsArr']);
}
}
This is the error that is produced when I try to type in an ID.
This is what i want to produce which I have been able to do by using an array in search.ctp
and here is my table I am trying to fetch the IDs from.
There are two methods.
$this->request->query('term');
$_REQUEST['term'];

How to read javascript array values php

Here i am passing the javascript array values to php using the jquery ajax.now i want to recive the data in php script. how should i do it?
php:
<?php
$list = array
(
//here i want to get the ajax array data
);
$t = time();
$file = fopen("xls/$t-userinput-input.csv","w");
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file); ?>
Jquery:
function arrayPush(val1,val2) {
uservalues.push(val1,val2);
passvalues()
}
function passvalues(){
$.ajax({
type: "POST",
data: {info:uservalues},
url: "write.php",
success: function(msg){
alert("Thankyou")
}
});
}
Because you're POSTing the data, just try with:
$list = $_POST['info'];
First of all, read it from PHP POST variable:
$jsonRawData = $_POST['info']
Next, decode it to have php array - http://php.net/manual/en/function.json-decode.php
$decoded = json_decode($jsonRawData);
You can always peek what's inside PHP variable with var_dump.

Codeigniter Form Validation pass value instead field name

I'm using Codeigniter and I have a dynamically created form with lots of input fields. I'm using jQuery and AJAX to submit form and I'm passing all the data from form as an object. This is my jQuery code:
$('body').on("submit", "#app-options-form", function(evnt){
// Show loader while AJAX is loading
$('.response-container').html('<img class="response-loader" src="<?php echo base_url();?>/img/loader.gif" >');
// Prevent form submission
evnt.preventDefault();
// Get all form inputs
var inputs = $('#app-options-form :input[type="text"]');
// Put them in object as name=>value
var data = {};
for(i=0; i<inputs.length; i++) {
data[inputs[i]["name"]] = inputs[i]["value"];
}
// Generate POST request
$.post("<?php echo site_url("admin/ajax_app_options"); ?>",
{"edit_form_submited" : true, "data" : data},
function (data) {
$('.response-container').html(data.result);
}, "json");
});
I'm having difficulties with validation of that form. If I put a field name as a parameter for set_rules(), it won't work because it will look for $_POST['field_name'] but this doesn't exist. The value of this field is passed as $_POST['data']['field_name'], because I'm passing all inputs as an object called "data".
So, is there any way to validate this form?
EDIT:
My PHP code:
// Get received data, here are all the input fields as $field_name=>$field_value
$data = $this->input->post('data');
// Try no. 1 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($key, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
// Try no. 2 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($value, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
// Try no. 3 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($this->input->post('data')['$key'], 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
These are my tries to set the rules, but none of them works
I have not tested this but it should work!
$("body").on("submit", "#app-options-form", function() {
// Prevent form submission
evnt.preventDefault();
// Show loader while AJAX is loading
$('.response-container').html('<img class="response-loader" src="<?php echo base_url();?>/img/loader.gif" >');
var form = $(this).serializeArray();
var data = {data: form};
$.post("<?php echo site_url('admin/ajax_app_options'); ?>", data, function(response) {
$('.response-container').html(response.result);
}, "json");
});
When you send a serialized string using $.post it come through as an array at the other end :)
Hope this helps!
After you edit
remove var data = {data: form}; from the above
Then with php do:
foreach ($this->input->post() as $key => $value) {
$this->form_validation->set_rules($key, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
The reason you code wouldn't work is because Form_validation will be looking for the key in the $_POST array but it would need to look inside $_POST['data'].
The other option (which would be quite pointless, but follows using the data array) would be:
$data = $this->input->post('data');
foreach ($data as $key => $value) {
$this->form_validation->set_rules("data[$key]", 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
I can't say this will definitely work though.

My AJAX function works correctly, but sometimes I get a JSON object undefined

i am building the next interface:
as you can see, this interface has two links shown as buttons, one to add products and the other one to rest products.
when i click in the link "addProduct" then it calculates the new total which is shown in the following interface:
The code involved in this operation, involves 2 files:
JQuery Ajax File:
$.ajax({
async:true,
type:"POST",
url: "masProducto.php",
datatype:"JSON",
data: {
tecantidad: tecantidad.val(),
valorId:id
},
success:function (jsonStr) {
var cantidad=jsonStr.cantidad;
var fila=$("#ticket_"+jsonStr.id);
var tetotal=fila.find(".precioTotal");
var teprecio=parseFloat(fila.find("input[type=hidden]").val());
var teCosteTotal=$("#importeTotal");
teCosteTotal.text(jsonStr.total+"€");
tetotal.text(teprecio*cantidad+"€");
var resumenTotal=$("#resumenTicket td:nth-child(3)");
resumenTotal.text(jsonStr.total+"€");
var resumenNumProductos=$("#resumenTicket td:nth-child(1)");
resumenNumProductos.text(jsonStr.numTotalProductos+" Items en la cesta");
},
error:function(err){
alert(err);
},
timeout:4000
});
The file masProducto.php where the JSON object is built:
<?php
include 'functions.php';
include('./ShoppingCart.php');
include('./Item.php');
sec_session_start(); //Nuestra manera personalizada segura de iniciar sesión php.
if (!isset($_SESSION['cesta'])){
header('Location: ./login.php?error=1');
}
else {
$cesta=new ShoppingCart();
$cesta=unserialize($_SESSION['cesta']);
}
header('Content-Type: application/json');
$listaItems=$cesta->getItems();
$numEltos=$cesta->count();
$tecantidad=$_POST['tecantidad'];
$id=$_POST['valorId'];
foreach ($listaItems as $celda){
if($id===$celda['item']->getId()){
$cesta->updateItem($celda['item'],$tecantidad);
}
}
$_SESSION['cesta']=serialize($cesta);
if(isset($id)){
$data = array(
"cantidad" => $tecantidad,
"id" => $id,
"total" => $cesta->calcularTotal(),
"numTotalProductos" => $numEltos
);
echo json_encode($data);
}
?>
I am using PHP OOP, and i use to objects for my shopping basket which are the "Soppingcart" and "Item".
My problem is that this code works right, but when i click fast to the plus (or rest button), it gives me back an undefined object.
I would apreciate if some could help me, because i dont even know how to look for the solution for this problem.
for more details you can enter in this website www.galeonweb.es/Index.php, where if you loggin with "test#example.com" and password "123456" you can see what is my problem better.
Thank you in advance
First off this line is pretty bad practice
if (!isset($_SESSION['cesta'])){
header('Location: ./login.php?error=1');
}
You should rather have something like
if (!isset($_SESSION['cesta'])){
echo json_encode(array(code => 2, message => 'Session invalid'));
}
And redirect the user to the login page from jQuery.
You would then need to modify the rest accordingly
if(isset($id)){
$data = array(
"code" => 0,
"message" => "Success",
"data" => array(
"cantidad" => $tecantidad,
"id" => $id,
"total" => $cesta->calcularTotal(),
"numTotalProductos" => $numEltos
)
);
echo json_encode($data);
}
I would also add the following to that
else {
echo json_encode(array('code' => 1, 'message' => 'Item not found' ));
}
Furthermore rather than test if an id is passed at the very end I would do
if(isset($id)){
$found = false;
foreach ($listaItems as $celda){
if($id===$celda['item']->getId()){
$cesta->updateItem($celda['item'],$tecantidad);
$found = true;
}
}
}
else
{
echo json_encode(array(code => 1, message => 'Fatal error, id not set'));
}
And replace
if(isset($id)){
$data = array(
With
if($found === true){
$data = array(
You'll of course have to adapt your javascript accordingly to parse the response.
Those changes should give you a better idea of what is going wrong. But, as I said in my comment, using a debug tool like Firebug will also go a long way.
Have you tried non async?
$.ajax({
async:false,
type:"POST",
url: "masProducto.php",
datatype:"JSON",
...

Categories