I have a problem in the application I am building. And I have read many threads about the similar problem and have applied the suggestion given in those threads. However, the problem persists hence I write this.
The setup for is as follows:
I have the 3 php files: index.php, step_one.php and calculation.php.
From the index.php, I successfully load the step_one.php via the Ajax call which is as follows:
$(document).ready(function () {
var nocache = Math.random() * new Date().getTime() + Math.random();
$("#bookings").click(function () {
$.ajax({
url: 'step_one.php?cach='+nocache,
type: 'post',
cache: false,
success: function (data) {
$("#contentLeft").html(data);
}
});
});
});
Note: step_one.php is the html form.Then in step_one.php, I enter the data in the form and send the form data to calculation.php via another Ajax call that is as follows:
$("#viewprice").click(function () {
var nocache = Math.random() * new Date().getTime() + Math.random();
$.ajax({
url: 'calculate_quote.php?cache=' + nocache,
type: 'post',
dataType: 'json',
cache: false,
data: $("#stepOneForm").serialize(),
success: function (data) {
console.log(data);
$(".quote").append(data);
$(".quote").show();
document.getElementById("price").value = data;
}
});
});
The calculation.php file, calculates the price based on the data it receives and return the json to step_one.php. This is how I return json from calculation.php:
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Expires: 0'); // Proxies.
echo json_encode($data);
Note: The first time I click the #viewprice button, the price is correctly and successfully return to step_one.php. However, when in step_one.php I enter new data and re-click the #viewprice button, nothing is returned from calculation.php. And when I inspect the Network data, I see the calculation.php gets duplicated there and only the first Ajax call will the data in its response.
And this running in the local machine in xamp.
Would you please assist? What am I doing wrong here?
I found the bug that was giving me headache. It was a logical error.
Background
I use tokens in my forms for security reason. So for each form, I generate a token on page load and store it in the session. Then when the form sends its data (including the token), I first check if the received token is in the session - if the token is found, I then use the receives values and use them to compute $data which I then pass it to json_encode function. After the token is found, I delete it.
So, the calculation.php was not cached as my Ajax code is correct. Instead, the problem was when I resend the form data for re-calculation. During resend, the token in the session has already been deleted; therefore, the token I send with the form data could not be found in the session. Hence, data not computed and nothing is return.
Caching Ajax POST requests
Think the above link will be useful >>>
Related
I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing
I am taking some json data from an API using php. I'd like the data to refresh every 20 seconds without having to manually reload the page. This is my code below that works great at fetching the data. Just need to figure out how to refresh - maybe with ajax?
$getdata = file_get_contents("https://data.website.com/");
$datajson = json_decode($getdata);
$mydata = $datajson->whatiwant;
echo $mydata;
request your data using AJAX:
function requestMyData() {
$.ajax({
url: "/url/to/interface.php",
type: get,
success: function(data) {
//update your UI here
}
});
}
you are then able to request the data using a timeout:
setTimeout(requestMyData(), 100);
I have been staring at this problem for the past 2 hours and can't seem to fathom it, even after validating that everything loads correctly when scouring the console.
I basically have two sliders on my page which will eventually populate results in a table, every time I change my slider I send an array of two values to my AJAX script:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
The browser successfully finds update_results.php but it does not perform the logic on the page ( I assume it has found the page as the 404 error does not appear in my console. )
At this point in time the script is extremely bare-bones as I'm obviously trying to establish communication between both files:
<?php
$vals = $_GET['values'];
echo $vals;
In this case $vals is never echoed to the page, am I missing something in my AJAX? I know the values enter the function as alerted them out before attaching the PHP script.
Ajax Calls are suffering from Browser Cache. If your browser thinks, that he already knows the content of update.php, he will return the cached content, and not trigger the script. Therefore your
modified code might simply not get executed. (Therefore your insert query wasn't executed)
To ensure this is not happening in your case, it is always a good idea to pass a parameter (timestamp) to the script, so your browser thinks it's another outcome:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?random_parameter=" + (new Date().getTime());
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
This will ensure that - at least - the browser cache is refreshed once per second for update_results.php, no matter what browser cache-settings or server-side cache advices are telling.
when Ajax is done, the success callback is triggered and the output of you php script is saved in data.
you can handle the data like this:
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
dataType: "text",
success: function(data) {
document.write( data )
}
});
PHP, running at server, is unaware of what happening at the front-end browser and it simply respond to ajax request as any other normal http request. So the failure of SQL query has nothing to do with javascript, which only responsible for sending ajax request and receiving and handling the response. I guess there's some errors in your php script.
I'm building an AJAX form and I'm trying to send 3 fields by JSON.
Client-side, the form is serialised and entered into JSON format:
$('#form-signin').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel2';
$.ajax({
type: "POST",
url: url,
data: $.base64.encode($('#form-signin').serialize()),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
});
}
});
event.preventDefault();
});
Server side, my router splits the URL request up, sees that the first part contains 'ajax' then proceeds to specially pass the routing request to an AJAX handler.
my problem is that even inside the router, checking $_REQUEST, which is what is used to get the information about the post, the post data is not there. The same goes with $_POST.
Even the first page where the request hits (index.php), $_REQUEST does not have the data.
What am I doing wrong?
Server Side,
The request is sent to an index.php which includes the Autoloader and init script.
The init script initialises the database connection, sets the error, exception and session handling, then passes the request onto the router.
The router, in its construction method: sets the URL as an array (exploded $_SERVER['REQUEST_URI']), and then sets the relevant controller, method and additional parameters.
In this case, as we are doing an ajax request, special processing happens before we dispatch the request.
The method parameters are set to:
$requestParams = $_REQUEST;
unset($requestParams['url']);
This request parameter(s) along with additional information (url, controller, method and database object) are passed for dispatch.
In all cases, we are primarily dispatching using this method:
$dispatchedController = new $this->controller($this->database);
$method = $this->method;
return $dispatchedController->$method($this->params);
If I remember right from using a plugin a long time ago, the method $.base64.encode() returns a single string so what you are probably sending to the server is something like a single parameter with no value.
I believe you should be doing something like
data: "foo=" + $.base64.encode($('#form-signin').serialize()),
You are not sending json to the server just a base64 encoded string. Also you are expecting key/pair values. To send key/pair values just pass the serialized form data to the $.ajax function.
$('#form-signin').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel2';
$.ajax({
type: "POST",
url: url,
data: $('#form-signin').serialize(),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
});
}
});
event.preventDefault();
});
The code should work (assuming your HTML is not the problem here, e.g., '#form-signin' is the right selector for the right form).
You mentioned you are not able to get the data on the server side. However, are you absolutely sure you are even sending the data you need from the client? For example, have you analyzed the request using a tool such as Firebug?
I have a table that outputs all my contacts via a while loop from my database.
my syntax is like this:
SELECT * FROM contacts WHERE id = $_SESSION['user_id'] ORDER BY name ASC LIMIT 5
that pulls out all my data and only gives me 5 results.
Now my goal is to have a little button that opens up a model box with jquery (this I can manage on my own) with a form asking the user to input a number then that number will be sent via post or get to $PHP_SELF and update a local variable with the number the user inputed, then that variable will be used to update the database to increase or decrease the LIMIT value.
I have looked all over the web (with google) to look for submitting a form using AJAX but all the examples i've found don't work for me.
When the user submits the number and the sql query is executed and updated for the outputed table to dynamically update according to the new LIMIT value all without ever refreshing the page to the user.
my jquery code is:
(document).ready(function(){
$("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({
type: "post",
url: "process.php",
data: "val="+ val,
cache: false,
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
});
return false;
});
});
$(document).ready(function(){ $("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({ type: "post", url: "process.php", data: "val="+ val, cache: false, success:
function(){
$('form#form').hide(function(){$('.success').fadeIn();});
} }); return false; }); });
then my php code is:
$new_val = $_POST['new_val'];
$_val = "UPDATE `settings` SET `display_limit` = {$new_val} WHERE `user_id` = {$_SESSION['user_id']}";
mysql_query($_val) or die(mysql_error());
and my form is simple:
any suggestions? I haven't come to how to have my outputed table dynamically update yet so if anyone can point me in the right direction or provide some help that would be awesome.
thanks
EDIT:
Here is an updated jquery script I was working on, I'm able to submit the form successfully! but my only problem is that I can't see the changes until the page is refreshed with defeats the purpose of the AJAX usage... sigh
how can I now have my #results div updated and refreshed with the form submission content?
$(document).ready(function() {
var options = {
url: 'process.php',
type: 'post',
//dataType: 'json',
target: '#last_five_sellers',
success: success
};
// bind to the form's submit event
$('#form').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
function success(responseText, $form) {
$("form#form").hide();
$(".success").fadeIn();
}
});
In your php code where you do the update, You could echo your contacts in html-format. That would then return to your success function in jquery.
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
The function have a parameter data, which is the html-format you echoed in php.
Example
success: function(data){
$('form#form').hide(function(){$('.success').fadeIn();});
$(data).appendTo('#result');
}
You need to understand the flow of a request. Once the php script runs, that is it, it is done. If you plan on submitting back to that same page, it'll be a new request and a new execution of that script. Now, you could add a special case to that script to return the necessary data to your jQuery code, but that's messy IMO. I would rather have a separate script to handle that functionality. This can be looked at as a web service.
So, when a you go to that page in a browser, it will intially display 5 contacts (or w/e the default you have in the LIMIT clause). When you click the icon to display more contacts, you employ jQuery to submit a GET request to that 'web service' page (it really should be GET, since you're retrieving data, not submitting new data). This would then be a list of contacts that you use to update the display on the page, using jQuery/JavaScript.
As noted by Codler, the output from that 'web service' can be HTML which you simply use to replace the existing HTML which displays the contacts. (This would be the preferred way. You almost always want do as much on the server as you reasonably can.)
It looks like your jQuery code is duplicated — there's no need to bind the form's submit event twice. Additionally, the first jQuery block is missing the opening dollar-sign ("$"). And as far as I know, .hide() does not support passing a callback through the first parameter. In the jQuery API documentation, it's written as .hide( duration, [ callback ] ).
I would write:
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(){
$("form#form").hide();
$('.success').fadeIn();
}
});
return false;
});
});
Now, if you want to update your results table dynamically, the simplest way is just to replace the entire thing with the updated HTML. So for instance, if you modified your PHP script (process.php) so that, after updating display_limit, it outputted the new results table, you could then write something like (assuming your results table is table#results):
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(data){
$("form#form").hide();
$(".success").fadeIn();
$("#results").replaceWith(data);
}
});
return false;
});
});
You just have to make sure your script only outputs HTML.
Contrary to what George answers above, HTML will definitely work for this purpose, but I think the ideal method is to send purely the data alone (minus structure/presentation) in either JSON or XML format, and then use JavaScript to build the HTML; you can save a lot of bandwidth this way, and ultimately build a much more responsive application.
EDIT
Here's a mini JSON-based example.
JavaScript:
$(function(){
$("#form").submit(function(){
var val = $("input[name=new_value]").val();
$.getJSON("process.php?val=" + val, function(data){
$("#results").empty();
$(data.rows).each(function(){
$("#results").append('<tr><td>' + this.column_a + '</td><td>' + this.columbn_b + '</td></tr>');
});
});
return false;
});
});
PHP (process.php):
[assuming you already have a result/rows called $result]
$json = array('rows' => array());
while ($row = mysql_fetch_assoc($result)) {
$json['rows'][] = $row;
}
echo json_encode($json);
Now, granted, I haven't tested this code at all, but it should give you the gist of it.