Sending Jquery autocomplete query to PHP file - javascript

I am using Jquery's autocomplete and connecting to a database to grab an array in which you can search.
However the issue I am having is sending the data back to the current file or another php file.
I am able to see that date is being sent, (firebug) but I am unable to echo the information on screen:
$('#school').each(function(i, el) {
var that = $(el);
// autocomplete function
that.autocomplete({
source: "extraction.php",
minLength: 1,
select: function( event , ui ) {
info = ui.item.label;
$.ajax({
url: 'advisor.php',
type: 'POST', // changed
data: { info : info },
success: function(){
window.location.href = "advisor.php";
}
});
} // end of select function
});
});
And on the PHP side, a simple:
<?php
if (isset($_GET['info'])){
$x = $_POST['info'];
echo $x;
}
?>
How can I send a request and get a live update?

Related

Not receiving data from ajax to php

I want to send data from javascript to another php page where I want to display it. I found that I need to use Ajax to pass the data to php so I tried myself.
My file where is the javascript:
$('#button').on('click', function () {
$.jstree.reference('#albero').select_all();
var selectedElmsIds = [];
var selectedElmsIds = $('#albero').jstree("get_selected", true);
var i = 0;
$.each(selectedElmsIds, function() {
var nomenodo = $('#albero').jstree('get_selected', true)[i].text;
//var idnodo = selectedElmsIds.push(this.id);
var livellonodo = $('#albero').jstree('get_selected', true)[i].parents.length;
//console.log("ID nodo: " + selectedElmsIds.push(this.id) + " Nome nodo: " + $('#albero').jstree('get_selected', true)[i].text);
//console.log("Livello: " + $('#albero').jstree('get_selected', true)[i].parents.length);
i++;
$.ajax({
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo
},
success: function(data)
{
$("#content").html(data);
}
});
});
});
I want to send the data to another php page which consists of:
<?php echo $_POST["namenodo"]; ?>
But when I try to go to the page there's no data displayed.
This is a very basic mistake I think every beginner (including me) does while posting a data using ajax to another php page.
Your ajax code is actually posting the data to lamiadownline.php (if you are using the variables correctly) but you can't get that data by simply using echo.
Ajax post method post data to your php page (lamiadownline.php) but when you want to echo the same data on the receiver page (lamiadownline.php), you are actually reloading the lamiadownline.php page again which makes the $_POST["namenodo"] value null.
Hope this will help.
First of all you won't be able to see what you have post by browsing to that page.
Secondly, is this
<?php echo $_POST["namenodo"]; ?>
in the current page?
Otherwise, specify the url
$.ajax({
url: "lamiadownline.php",
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo},
success: function(data) {
$("#content").html(data);
}
});
//try this
$.ajax({
type: "POST",
url:"Your_php_page.php"
data: { namenodo: nomenodo levelnodo: livellonodo},
success: function(data)
{
$("#content").html(data);
}
});

jQuery.ajax post is being sent but $_POST is empty

I am trying to send information using AJAX from JavaScript in one file to PHP in another file. When I inspect the page on chrome after I have pressed the button, it shows the values under the form data sub section in networks, however, if I var_dump[$_POST] it shows it is empty.
Here is my JavaScript:
function details(id) {
var data = {"id" : id};
jQuery.ajax({
url: "/Example/includes/detail.php",
type: 'POST',
data: data,
success: function(data){
jQuery('body').append(data);
},
error: function(){
alert("Error");
}
});
}
Here is the PHP:
<?php
$id = $_POST['id'];
$id = (int)$id;
?>
Any help would be greatly appreciated. Thanks

Passing a PHP variable to JavaScript For AJAX Request

So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).
With attempt 2), I get a null when viewing its value in the web inspector.
The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):
$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
function( data ) {
console.log(topic_id);
data = data.trim();
if ( data !== "" ) {
//get the participants data for avatars
$.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {
The end of topic-search.php, which echoes out the built up card. Script is supposed to return the topic_id variable for use in the success function.
}
//One attempt: echo $content; //
//Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}
?>
<script>
var topic_id = "<?php echo $row['topicid'] ?>";
</script>
Try this:
In php
$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array
In javascript
var $url = '/wp-content/mu-plugins/topic-search.php';
var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});
$.ajax({
url: $url,
type: "POST",
data: $json,
dataType: "json",
success: function(data){//you will have the body of the response in data
//do something
},
error: function(data){
//do something else
}
});
EDIT:
This will request $url with the $json data. You will have it available on $input on the server side as an array. You can then on the server prepare a response with a json body that you will have available on the success function as the data variable.

Not recieving values sent via AJAX POST to PHP

I'm trying I'm trying to send a specific section of my URL string, to my php file, to then populate my page accordingly. Everything is working fine, except for the AJAX POST method. I've tried doing var_dump of the POST variable in my PHP, and my array is empty (so I know nothing is getting through).
The success DOES return as being passed, so I don't know where the data is going. I'm testing locally on XAMPP, and I've combed through SoF and no luck on any of the fixes. My code is below.
Screen shot of page:
jQuery AJAX Request:
$(document).ready(function() {
str = window.location.href;
pos = str.search("pages/"); //42
send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
tom: send
},
success: function() {
$.get("retrieve.php", function(data, status) {
$("#main").html(data);
}) //ends GET function
},
error: function() {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
echo "<i>hello</i>";
echo var_dump($_POST);
$url = $_POST['tom'];
json_decode($url);
echo $url;
Try the below,
Also you don't need to json_decode unless you send a json request,And please make sure all the post values are passing.
Ajax:
$(document).ready(function() {
var str = window.location.href;
var pos = str.search("pages/"); //42
var send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
'tom': send//make sure this is not empty
},
success: function(data) {
console.log(data);
},
error: function(arguments) {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//echo "<i>hello</i>";
//echo var_dump($_POST);
$url = $_POST['tom'];
json_encode($url);
echo $url;
}

Using Ajax with cakephp doesnt work

I have a page like this:
Basically, I pick 2 dates and hit the button, then the data below will change without refreshing this page.
Here is the code in controller:
if( $this->request->is('ajax') ) {
$this->autoRender = false;
//if ($this->request->isPost()) {
print_r($this->request->data);
// get values here
echo $from=( $this->request->data('start_time'));
echo $to= $this->request->data('end_time');
Debugger::dump($from);
Debugger::dump($to);
//$this->layout = 'customer-backend';
$this->Order->recursive=-1;
$this->Order->virtualFields['benefit']='SUM(Product.product_price - Discount.product_discount)';
$this->Order->virtualFields['number']='COUNT(Order.order_id)';
$option['joins'] = array(
array('table'=>'discounts',
'alias'=>'Discount',
'type'=>'INNER',
'conditions'=>array(
'Order.discount_id = Discount.discount_id',
)
),
array('table'=>'products',
'alias'=>'Product',
'type'=>'INNER',
'conditions'=>array(
'Discount.product_id = Product.product_id'
)
)
);
$option['fields']= array('Discount.product_id','Product.product_name','benefit','number');
$option['conditions']=array('Discount.start_time >='=>$from);
$option['group'] = array('Discount.product_id','Product.product_name');
//$option['limit']=20;
$products = $this->Order->find('all',$option);
//Debugger::dump($products);
$this->set('products',$products);
//}
}
else
{
$from='27 November 2012';
//$this->layout = 'customer-backend';
$this->Order->recursive=-1;
$this->Order->virtualFields['benefit']='SUM(Product.product_price - Discount.product_discount)';
$this->Order->virtualFields['number']='COUNT(Order.order_id)';
$option['joins'] = array(
array('table'=>'discounts',
'alias'=>'Discount',
'type'=>'INNER',
'conditions'=>array(
'Order.discount_id = Discount.discount_id',
)
),
array('table'=>'products',
'alias'=>'Product',
'type'=>'INNER',
'conditions'=>array(
'Discount.product_id = Product.product_id'
)
)
);
$option['fields']= array('Discount.product_id','Product.product_name','benefit','number');
$option['conditions']=array('Discount.start_time >='=>$from);
$option['group'] = array('Discount.product_id','Product.product_name');
//$option['limit']=20;
$products = $this->Order->find('all',$option);
$this->set('products',$products);
}
If the request is ajax, it gets 2 values $from and $to from the POST and pass them to the SQL query. If the request is not ajax (mean the access this page for the first time when the dates havent picked yet), $from and $to are assigned default values.
Here is my ajax in view:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/project/cakephp/orders/hottest_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
success: function(data){
alert("success");
}
});
});
});
it gets data from 2 date picker then send it to the controller as a POST method.
My problem is that after I choose 2 dates and hit the button, nothing happens. the data doesnt change according to the dates.
Any thoughts about this. Thanks in advance.
When opening your page and running the following in the console:
$(".tab_container").html("loaded from ajax");
The products table now only shows "loaded from ajax". If the content of the products table is generated by it's own template you can have cakephp render that template only when it's an ajax call: http://book.cakephp.org/2.0/en/controllers.html
$this->render('/Path/To/ProductTable/');
If your cakephp will output only the product table when an ajax call is made you could try to run the following code:
var from = "2000-01-01";
var to = "2014-01-01";
$.ajax({
url: "/project/cakephp/orders/hottest_products",
type: 'POST',
data: {"start_time": from, "end_time": to }
}).then(
function(result){
$(".tab_container").html(result);
},function(){
console.log("fail",arguments);
}
);

Categories