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'];
Related
So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support
I have a function in a compare.php that takes a parameter $data and uses that data to find certain things from web and extracts data and returns an array.
function populateTableA($data);
So to fill array I do this
$arrayTableA = populateTableA($name);
now this array is then used to iterate tables..
<table id="tableA">
<input type="text" name="search"/><input type="submit"/>
<?php foreach($arrayTableA as $row) { ?>
<tr>
<td><?php echo $row['name']?></td>
<td><?php echo $row['place']?></td>
</tr>
</table>
Now what I want to do is to enter some data on input and then through jquery ajax
function populateTableA($data);
should be called and $array should be refilled with new contents and then populated on tableA without refreshing the page.
I wrote this jquery but no results.
$(document).on('submit',function(e) {
e.preventDefault(); // Add it here
$.ajax({ url: 'compare.php',
var name = ('search').val();
data: {action: 'populateTableA(name)'},
type: 'post',
success: function(output) {
$array = output;
}
});
});
I have been doing web scraping and the above was to understand how to implement that strategy... original function in my php file is below
function homeshoppingExtractor($homeshoppingSearch)
{
$homeshoppinghtml = file_get_contents('https://homeshopping.pk/search.php?category%5B%5D=&search_query='.$homeshoppingSearch);
$homeshoppingDoc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($homeshoppinghtml)){
$homeshoppingDoc->loadHTML($homeshoppinghtml);
libxml_clear_errors();
$homeshoppingXPath = new DOMXPath($homeshoppingDoc);
//HomeShopping
$hsrow = $homeshoppingXPath->query('//a[#class=""]');
$hsrow2 = $homeshoppingXPath->query('//a[#class="price"]');
$hsrow3 = $homeshoppingXPath->query('(//a[#class="price"])//#href');
$hsrow4 = $homeshoppingXPath->query('(//img[#class="img-responsive imgcent"])//#src');
//HomeShopping
if($hsrow->length > 0){
$rowarray = array();
foreach($hsrow as $row){
$rowarray[]= $row->nodeValue;
// echo $row->nodeValue . "<br/>";
}
}
if($hsrow2->length > 0){
$row2array = array();
foreach($hsrow2 as $row2){
$row2array[]=$row2->nodeValue;
// echo $row2->nodeValue . "<br/>";
}
}
if($hsrow3->length > 0){
$row3array = array();
foreach($hsrow3 as $row3){
$row3array[]=$row3->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
if($hsrow4->length > 0){
$row4array = array();
foreach($hsrow4 as $row4){
$row4array[]=$row4->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
$hschecker = count($rowarray);
if($hschecker != 0) {
$homeshopping = array();
for($i=0; $i < count($rowarray); $i++){
$homeshopping[$i] = [
'name'=>$rowarray[$i],
'price'=>$row2array[$i],
'link'=>$row3array[$i],
'image'=>$row4array[$i]
];
}
}
else{
echo "no result found at homeshopping";
}
}
return $homeshopping;
}
As mentioned in the comments PHP is a server side language so you will be unable to run your PHP function from javascript.
However if you want to update tableA (without refreshing the whole page) you could create a new PHP page that will only create tableA and nothing else. Then you could use this ajax call (or something similar) -
$(document).on('submit','#formReviews',function(e) {
e.preventDefault();
$.ajax({
url: 'getTableA.php', //or whatever you choose to call your new page
data: {
name: $('search').val()
},
type: 'post',
success: function(output) {
$('#tableA').replaceWith(output); //replace "tableA" with the id of the table
},
error: function() {
//report that an error occurred
}
});
});
Hi You are doing it in wrong way.You must change your response to html table and overwrite older one.
success: function(output) {
$("#tableA").html(output);
}
});
In your ajax page create a table with your result array
You are in a very wrong direction my friend.
First of all there are some syntax error in your JS code.
So use JavaScript Debugging
to find where you went wrong.
After that Basic PHP with AJAX
to get a reference how ajax and PHP work together
Then at your code
Create a PHP file where you have to print the table part which you want to refresh.
Write an AJAX which will hit that PHP file and get the table structure from the server. So all the processing of data will be done by server AJAX is only used for request for the data and get the response from the server.
Put the result in your html code using JS.
Hope this will help
I know that there are so many to find on the internet, however, I have been trying this for hours now, and still not working, Maybe the community could help me out:)
http://jsfiddle.net/dkk2nqyg/14/
I've got a little explanation in the jsfiddle, else, you can take a look in my previous question, JavaScript array splice
Basicly, I want the values from selected ( 3 picked up cards )
in php, because I want to mail those values;)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {data : selected},
success: function(data) {
alert("worked");
}
});
in the data.php :
<?php
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
?>
I would like that I don't even need that data.php but just 1 page, so in the index.php, is that even possible?
Edit: Please, link a JsFiddle, would really help!
First the ajax request should be within the click handler
$('#mail').click(function () {
console.log($('#dvDest .flipper').get())
var selected = $('#dvDest .flipper').map(function () {
return $(this).data('src')
}).get();
alert(selected)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {
data: selected
},
success: function (data) {
alert("worked");
}
});
})
then in server side loop through the array like(Not sure about the PHP syntax)
<?php
foreach($_POST['data'] as $d){
echo $d;
}
?>
you can write a condition as if request object have post values then
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
else your homepage display code
So,index.php is enough
For using a single page, eg: index.php
at the top of index.php you do:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your code goes here
exit();
}
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",
...
I'm trying to achieve something relatively straightforward - allow users to make comments on a view page, update the database and display the new content dynamically on the page without the whole page refreshing.
My efforts so far have been unsuccessful - there may be several issues with what I'm doing!
On the view page I have tried this (to send 2 variables to a CI controller function):
<script type="text/javascript">
function ajax(id, user_id) {
jQuery('#dynamicdiv').load('/controller/function/' + id + '/' + user_id);
}
</script>
<div id='dynamicdiv'>
</div>
I have a textarea to collect the user comment, in the controller function should I be able to call this as post data in order to write it to the database? If so, I would still need to send two other variables ($id and $user_id) to the ajax function.
<?php $atts = array (
'class' => "alignright button",
'onClick' => "ajax('$id,$user_id')",
); ?>
<?php echo anchor(current_url(), 'Post my Comment', $atts); ?>
and in the controller, which involves a different function (view) than the page I want the user to stay on:
$data = $this->model->database_query($id, $user_id);
echo $data; // from reading other posts it seems I would process the data within this function, to have it displayed on the page the user is viewing?
Any help appreciated!
Don't forget to block you default anchor behaviour (for example by adding return false; to your onclick parameter).
<?php $atts = array (
'class' => "alignright button",
'onClick' => "ajax('$id,$user_id'); return false;",
); ?>
you can make the ajax request as follows:
function ajax(id, user_id) {
$.ajax({
url: base_url + controller_name + '/' + action_name,
type: 'GET',
data: { id: id, user_id: user_id },
dataType: 'json',
success: function (data) {
// append the returned result to your #dynamicdiv
}
});
}
and in the controller:
$id = $this->input->get('id');
$user_id = $this->input->get('user_id');
$data = $this->model->database_query($id, $user_id);
echo json_encode($data);
Hope this helps