This is the structure I have:
A router.php, based on $_POST['c'] generates the controller file name, includes the file and calls the $_POST['a'] method of it.
I have a gridview. The only way to open a details page when the user clicks the row is to use AJAX, since only javascript can handle the clicking. I don't want to have a button column - I want a row click.
So I have my javascript doing this:
$( document ).ready(function() {
// Handler for .ready() called.
$("tr" ).click(function() {
var id = $('td[name=id]').attr('id');
var c = $('input[name=c]').attr('value');
var a = $('input[name=a]').attr('value');
$.post("Router.php", { id: id, c: c, a: a }, function(data){
window.location.href = "Router.php";
});
});
});
I have my Router.Php:
if (array_key_exists('c', $_POST)) {
$controller = $_POST['c'];
};
if (array_key_exists('a', $_POST)) {
$action = $_POST['a'];
};
echo $controller;
echo $action;
I can never get the post values. I think I'm thinking about AJAX wrong - what AJAX is suppose to do is to just get a response and render it somewhere on the browser. What I'm using it for is to pass POST data and call a method within a PHP file. The reason for this is because I don't want to pass the id in the url.
Any way to fix this?
The following part of your code issues 2 requests to the server. A POST and then a GET.
$.post("Router.php", { id: id, c: c, a: a }, function(data){
window.location.href = "Router.php";
});
Most probably you are getting what you want on the first request, but the result that you see on your screen is the outcome of the second request, which is just a GET without params.
The result of the post is being written using echo $controller; and echo $action; and these are returned in (data) but you don't do anything with that. You just redirect the client to Router.php.
Related
I'm trying to create a page where a user can upload a file and select the people they want to email it to. Once they click submit, I prevent page refresh and reset their inputs in the form. Now I want to place their previously entered information into a table on the same page (different section of the page).
If you did want to proceed with this concept, you would capture the output of the PHP script in a done() function, insert it in an element on the page, and run eval(). Like this...
$.ajax({
type: "POST",
url: "../FileDrop/dbSystem.php",
data: {tags: JSON.stringify(tags), file:
$('input[name=fileName]').val()};
}).success(function(result) {
$( '#element' ).html(result);
$( '#element script' ).each( () => { $(this).html().eval() })
});
But it would make alot more sense to return data that you use to execute the javascript in your page - that is, keep all that logic together rather than splitting some of it off into a PHP file.
<?php
// php process that checks for 'valid'...
// create a json response
$output = array('valid' => 1);
echo json_encode($output);
?>
.... and in your JS
.success(function(result) {
// result is a stringified JSON object. We need to convert it into an actual JSON object with parse()
result = JSON.parse(result);
// might not matter, but result.valid will be a number which JSON converts into a string. By adding the + right before the variable, that tells JS to use it as a number for the comparison
if (+result.valid == 1) {
$(".outputDiv").show();
}
});
I am trying to get the sub total updated, when adding the items to the database from java-script. But, currently it displays the first amount and not updates when adding items. (But when runs the query from phpMyAdmin it works correctly)
java-script code
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
HTML code
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" / >
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
The problem is, that when you declare the function with PHP, the function cannot be refreshed by using PHP again... because everything that PHP does, happens before the page is loaded, therefore, let's say as an example:
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
this 'value' from $rowT[0] = 10 from the first query, it will always be 10, because that is what PHP read from the database when it checked upon page load. You will have to use something like jquery or ajax to read the contents of another php file that contains the value (the mysqli_fetch_row).
PHP is literally named hypertext preprocessor, meaning everything that is processed before the html is printed to the user. (before the page has finished loading)
try experimenting with this: https://api.jquery.com/jquery.get/
ShowSubTotal() will bring only the value when the page loads. Dynamic actions will not make any changes, because php needs an server request to operate.
You should bring the subtotal through a dynamic request (ajax) call.
Or:
Use javascript to sum the values and set the value in your txtSubTotal field. If you go for this option, remember to not rely on this value on your server side processing, as it may be adulterated by users.
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
try this code
$("#btnSave").click(function(){
$.ajax({
url : file_url.php,
type : 'post',
data : {
get_subtotal:"subtotal",
},
success : function( response ) {
alert(response);
$("#txtSubTotal").val(response );
},
error: function(response) {
console.log(response);
}
});
});
file_url.php
if(isset($_POST['get_subtotal'])){
$resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
echo $rowT[0];
}
I do not know what is happening with my code, when I run it, sometimes SESSION says there is an array is stored and sometimes it doesn't. I am using a debugger to check the session. When I use isset($_POST), the return value is always false. I am using ajax to pass an array to php.
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
Javascript:
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
window.location.href = 'example.php';
var jExample = JSON.stringify(array);
$.ajax({
data:{'jExam':jExample},
type: 'POST',
dataType: 'json',
url: 'example.php'
});
});
EDIT:
Figured out why the arrays are stored into SESSION, once I click on the button that opens the other page, and then type in the page before in the url, the array is stored into the SESSION. Don't know why. Still can't figure out why ajax is not sending to post.
EDIT 2:
I created a file that handles the request called handle.php. So the php script on top is added into handle.php instead of the webpage. But I am getting a "Parse error: syntax error, unexpected 'if' (T_IF)". The code is still the same on top.
handle.php:
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
EDIT 3:
I am using the ajax to pass an array to php in order to store it into session, in order to use the array in another page. The problem is that the array is not passing into $_POST. What I am hoping is that the array can actually pass so I can use it on another page.
SOLVED:
All i did was add a form that has a hidden value. And the value actually post
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(object)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone at has answered but hope this helps others.
If example.php is the php file which handles the request, you need to change your js code to
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
var jExample = JSON.stringify(array);
$.ajax("example.php", {
data:{'jExam':jExample},
type: 'POST',
dataType: 'json'
});
});
And you should add the complete-Parameter if you want to handle the response.
Your mistake is, you are redirecting the page using window.location.href before you even send your request. Therefore, your request never gets sent and the PHP-File is called directly instead, not via AJAX, not with the nessecary data. Therefore, you are missing the data in the PHP-File.
You will want to try and make this setup a bit easier on yourself so here are a few things that can help you simplify this. You may or may not have some of these already done, so disregard anything you already do:
Use a config file with concrete defines that you include on 1st-level php files
Just pass one data field with json_encode()
Don't send json as a data type, it's not required, troubleshoot first, then if you need to, make it default as the send type
Use a success function so you can see the return easily
Make functions to separate tasks
/config.php
Add all important preferences and add this to each top-level page.
session_start();
define('URL_BASE','http://www.example.com');
define('URL_AJAX',URL_BASE.'/ajax/dispatch.php');
define('FUNCTIONS',__DIR__.'/functions');
Form:
Just make one data that will send a group of data keys/values.
<button class="cart" data-instructions='<?php echo json_encode(array('name'=>'Whatever','price'=>'17.00','action'=>'add_to_cart')); ?>'>Add to Cart</button>
Gives you:
<button class="cart" data-instructions='{"name":"Whatever","price":"17.00","action":"add_to_cart"}'>Add to Cart</button>
Ajax:
Just send a normal object
$(document).ready(function(){
// Doing it this way allows for easier access to dynamic
// clickable content
$(this).on('click','.cart',function(e)){
e.preventDefault();
// Get just the one data field with all the data
var data = $(this).data('instructions');
$.ajax({
data: data,
type: 'POST',
// Use our defined constant for consistency
// Writes: http://www.example.com/ajax/dispatch.php
url: '<?php echo URL_AJAX; ?>',
success: function(response) {
// Check the console to make sure it's what we expected
console.log(response);
// Parse the return
var dataResp = JSON.parse(response);
// If there is a fail, show error
if(!dataResp.success)
alert('Error:'+dataResp.message);
}
});
});
});
/functions/addProduct.php
Ideally you would want to use some sort of ID or sku for the key, not name
// You will want to pass a sku or id here as well
function addProduct($name,$price)
{
$_SESSION['cart'][$name]['name'] = $name;
$_SESSION['cart'][$name]['price'] = $price;
if(isset($_SESSION['cart'][$name]['qty']))
$_SESSION['cart'][$name]['qty'] += 1;
else
$_SESSION['cart'][$name]['qty'] = 1;
return $_SESSION['cart'][$name];
}
/ajax/dispatcher.php
The dispatcher is meant to call actions back only as an AJAX request. Because of the nature of the return mechanism, you can expand it out to return html, or run several commands in a row, or just one, or whatever.
# Add our config file so we have access to consistent prefs
# Remember that the config has session_start() in it, so no need to add that
require_once(realpath(__DIR__.'/../..').'/config.php');
# Set fail as default
$errors['message'] = 'Unknown error';
$errors['success'] = false;
# Since all this page does is receive ajax dispatches, action
# should always be required
if(!isset($_POST['action'])) {
$errors['message'] = 'Action is require. Invalid request.';
# Just stop
die(json_encode($errors));
}
# You can have a series of actions to dispatch here.
switch($_POST['action']) {
case('add_to_cart'):
# Include function and execute it
require_once(FUNCTIONS.'/addProduct.php');
# You can send back the data for confirmation or whatever...
$errors['data'] = addProduct($_POST['name'],$_POST['price']);
$errors['success'] = true;
$errors['message'] = 'Item added';
# Stop here unless you want more actions to run
die(json_encode($errors));
//You can add more instructions here as cases if you wanted to...
default:
die(json_encode($errors));
}
I have 2 php files named card_process.php and payment.php. I'm trying to pass data from the cart_process page to payment page. The code goes like this:
cart_process.php:
$paynow = "<button type='submit' id='reset' class='btn btn-danger' align='center' disabled>PAY NOW</button> ";
$cart_box_total = '<div class="cart-products-total" id="cart-products-total" name="subtotalsub">.$total.</div>';
?>
<script>
$(document).ready(function() {
$("#reset").click(function() {
var content = $('#cart-products-total').html();
$.post("payment.php", { html: content})
.done(function(data) {
window.location = "payment.php";
});
});
});
</script>
And on payment.php:
<?php echo $_POST['html']; ?>
As the page redirects to payment.php, the $_POST['html'] doesn't echoes anything, but if I use alert(content) in cart_process.php it alerts me with the needed data.
How can I post the whole data to the page?
Replace window.location = "payment.php"; with:
$('body').append( data );
See how that works out. Eventually you may want to designate a destination target element:
<div id="ajax-target"></div>
Then instead of $('body').append( data ) you would have:
$('#ajax-target').html( data );
UPDATE
If you must be redirected, then you do not need ajax. Here is how you can do that:
$(document).ready(function() {
$("#reset").click(function() {
var content = $('#cart-products-total').html();
$('<form action="payments.php" method="POST"/>')
.html( '<textarea name="html">' + content + '</textarea>' )
[0].submit();
});
});
You have some misconceptions of the order of operations taking place here. You're actually invoking payment.php twice. Once as a POST request with the html parameter here:
$.post("payment.php", { html: content})
and then again as a GET request without any parameter here:
window.location = "http://selina.co.il/payment.php";
The client-side code is essentially ignoring the result of the POST request and just sending the user to the GET request, which naturally doesn't echo anything.
It's not entirely clear what you're trying to do here, but if you're using AJAX then you probably don't really want to be redirecting the user to anything anyway. So instead of doing this:
window.location = "http://selina.co.il/payment.php";
Do something in that AJAX callback to modify the current page. Maybe set the data variable to some content on the page? Something like this?:
$('#someDiv').html(data);
It's really up to you what should happen here, we can't tell for certain from the code posted.
If the flow of the application indeed is that the user should be redirected to another page, then you have two options:
1: Expect a GET parameter instead of a POST parameter in the PHP code and include it on the redirect:
window.location = "http://selina.co.il/payment.php?html=" + encodeURIComponent(content);
That will probably be pretty ugly if content is what it implies to be.
2: Don't use AJAX at all and simply have a form which POSTS to payment.php.
This is my first fully attempting to use ajax. I have looked all over Google and cannot seem to find an answer. I am not even sure if what I am trying to do is possible.
I am trying to populate a modal window with data from a mysql table.
Using this javascript below, I an able to print the DATA-ID in a modal window with an HREF click:
<script type="text/javascript">
$(document).on("click", ".open-RestrictModal", function () {
var myId = $(this).data('id');
$(".modal-body #Id").val( myId );
});
</script>
I would like to add to this code is the ability to run a PHP/MySQL query, get the results, and print it in the modal window.
I think I have to use AJAX, but I am not sure. How can I add to the existing code the ability to send the javascript variable to an AJAX page and return the results in a modal window?
Please help.
It doesn't appear that you are even using ajax here, assuming you are using the jQuery library you can build a call like this:
function some_ajax_call(your_param) {
$.ajax({
type: "POST", // We want to use POST when we request our PHP file
url : "some/url/to/your/file.php",
data : { query : your_param }, // passing an array to the PHP file with the param, value you passed, this could just be a single value i.e. data: your_param
cache: false, // disable the cache optional
// Success callback if the PHP executed
success: function(data) {
// do somethig - i.e. update your modal with the returned data object
$('.modal-body #id').val(data);
}
});
}
You can then write you file.php file to handle the query
<?php
// Capture the variable we passed in via AJAX
$param = $_POST['query'];
// Build a query
$query = "SELECT * FROM some_table WHERE val ='" . $param . "'";
// I assume you know how to run a query, this would be fetching an assoc array
$results = $DB->run__query($query);
// Check we have some results, then echo back to the AJAX call
if(sizeof($results) > 0) {
echo $results;
}
echoing at the $results array at the end of our PHP script if we have any results will populate the data array in our success callback with the returned rows, you can then perform any DOM manipulation in the success callback to update your modal, hope this helps.