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);
}
);
Related
I'm a new developer. I've read a lot of question all around about my topic, and I've seen a lot of interesting answers, but unfortunately, I cannot find a way to resolve mine.
I have a simple form in HTML and <div id="comment"></div> in it (empty if there is nothing to pass to the user). This DIV is supposed to give updates to the user, like Wrong Username or Password! when it's the case. The form is treated via PHP and MySQL.
...
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
header("Location: ../main.html");
} else {
//Please update the DIV tag here!!
}
...
I tried to "read" PHP from jQuery (with AJAX), but whether I didn't have the solution, or it cannot be done that way... I used this in jQuery (#login is the name of the form):
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
$("#comment").replaceWith(data); // You can use .replaceWith or .html depending on the markup you return
},
error: function(errorThrown) {
$("#comment").html(errorThrown);
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
But I'd like to update the DIV tag #comment with some message if the credentials are wrong. But I have no clue how to update that DIV, considering PHP is treating the form...
Can you help please ?
Thanks in advance ! :)
In order for AJAX to work, the PHP must echo something to be returned from the AJAX call:
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'good';
} else {
//Please update the DIV tag here!!
echo 'There is a problem with your username or password.';
}
But this will not show up in error: function because that function is used when AJAX itself is having a problem. This text will be returned in the success callback and so you must update the div there:
success:function(data) {
if('good' == data) {
// perform redirect
window.location = "main.html";
} else {
// update div
$("#comment").html(data);
}
},
In addition, since you're calling the PHP with AJAX, the header("Location: ../main.html"); will not work. You will need to add window.location to your success callback dependent upon the status.
To begin, your pretend is using Ajax to send form data to PHP. So your client (HTML) have to communicate completely via Ajax. After you do authenticate, you need send an "Ajax sign" to the client.
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'true';//it's better for using json format here
// Your http header to redirect won't work in this situatition
// because the process is control by javascript code. Not PHP.
} else {
echo "false";//it's better for using json format here
}
//the result is either true or false, you can use json to send more details for client used. Example: "{result:'false', message:'wrong username'}";
// use PHP json_encode(Array(key=>value)) to convert data into JSON format
Finally, you have to check the "Ajax sign" in your js code:
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
// You can use `data = JSON.parse(data)` if the data format is JSON
// Now, data.result is available for your checked.
if (data == 'true')
window.location.href = "main.html";
else
$("#comment").html('some message if the credentials are wrong');
},
error: function(errorThrown) {
$("#comment").html('Other error you get from XHTTP_REQUEST obj');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
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?
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.
I have a web Page, in which i an downloading data one after another in a loop. After each data download is finished i want to update the status to a DIV tag in the Web Page. How can i do this. Connecting to server and downloading data via php code and the div tag is within the .phtml page.
i have tried
echo "
<script type=\"text/javascript\">
$('#tstData').show();
</script>
";
But the echo statement update will happen at the end only. Refreshing of DIV tag need to happen at the end of each download.
Use jQuery load()
$('#testData').load('http://URL to script that is downloading and formatting data to display');
$("#save_card").submit(function(event) {
event.preventDefault();
var url = "card_save.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#save_card").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data);
if(data.msg=="success")
{
$("#submit_msg").html("Thank You !!!");
console.log("Record has been Inserted Successfully!!!");
}
else
{
$("#submit_msg").html(data.er);
console.log("There Is Some Error");
}
$("#submit_msg").show();
setTimeout(function() { $("#submit_msg").hide(); }, 5000);
$("#save_card").get(0).reset();
}
});
return false; // avoid to execute the actual submit of the form.class_master
});
Use This Ajax function to call PHP function to get data. Here
#save_card = Id of the form that you want to submit.
url = action for the form or the location to the php file from where your data is coming.
data: $("#save_card").serialize() = it is sending all the data of the form in serialize form. Data can be created manually to do this repalce this line with data: {'name':name,'year':year}
function(data) = here data is returned from the php code in json formate.
data.msg = It is a way to access different field from data.
$user_email = $_REQUEST['user_email'];
$cat_id = $_REQUEST['category'];
$title = $_REQUEST['title'];
$country = $_REQUEST['country'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO project(title, user_email, cat_id, country, start_date) VALUES ('$title','$user_email','$cat_id','$country', '$date')";
if (mysql_query($sql)) {
$project_id = mysql_insert_id();
echo json_encode(array('project_id' => $project_id, 'msg' => 'Successfully Added', 'status' => 'true'));
} else {
echo json_encode(array('msg' => 'Not Added', 'status' => 'false'));
}
PHP code to send data in json format
Assume I have 2 textbox, that's serial_no10 and serial_no12. That 2 textbox appear not simultaneously depends on case
1 PHP file for checking the SN.
1 DIV status to display the data.
jQuery Ajax
var serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();
$.ajax(
{
type: "POST",
url: "chk_dvd_part_no.php",
data: 'serial_no10='+ serial_no10 +'&serial_no12='+ serial_no12,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
}
}
}
HTML
<div id="status"></div>
PHP File
if(!empty($_POST['serial_no12']))
{
echo "Serial No 12";
}
else if(!empty($_POST['serial_no10']))
{
echo "Serial No 10";
}
Now I'm facing the problem when get POST from textbox serial_no_12, the value is undefined. But if get POST from textbox serial_no_10, I got the value.
Is that something wrong with that PHP code? Or I do something that should not be.
You have to just empty the variables before filling up. As if value is not reset then last value computed would remain in variavar
serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();ble
change it with
var serial_no10='';
var serial_no12='';
serial_no10 = $("#serial_no10").val();
serial_no12 = $("#serial_no12").val();
Noww do things it will all good
Give your form tag an id if it has no anyone. and than do something like this.
var form = $("#form_id").serialize();
$.ajax({
type: "POST",
url: "chk_dvd_part_no.php",
data: form,
success:function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
//do your stuff
});
}
});
and in php file get your post variable by its name, suppose you have 2 inputs name serial_no10 and serial_no12
now do your php code like this.
if( isset($_POST['serial_no10']) && $_POST['serial_no10'] != '' ){
echo 'Serial No 10';
}
if( isset($_POST['serial_no12']) && $_POST['serial_no12'] != '' ){
echo 'Serial No 12';
}