PHP reload page when adding forms (maybe needs ajax) - php

Sorry for maybe incorrect title for the topic, but this is the best that I came up with.
So, I'm building admin panel for a website.
I have a page, and in some part of the page, i'd like to refresh it and load another form.
let's say add a schedule, and somewhere down on the page I'd like to have this form displayed as soon as the link is clicked.
when a user saves it, I'd like that form to disappear and and in stead of that to have a list displaying all of the schedules.
I don't want to use frames - I'm not a supporter of frames. The panel is built using PHP.
Maybe this might be achived with Ajax? If yes -> How? any link to good example or tutorial.

yes this will be solved with ajax.
Here is a code example when the page is supposed to refresh
$('#button').click(function() {
$.ajax({
url: 'path/to/script.php',
type: 'post',
dataType: 'html', // depends on what you want to return, json, xml, html?
// we'll say html for this example
data: formData, // if you are passing data to your php script, needed with a post request
success: function(data, textStatus, jqXHR) {
console.log(data); // the console will tell use if we're returning data
$('#update-menu').html(data); // update the element with the returned data
},
error: function(textStatus, errorThrown, jqXHR) {
console.log(errorThrown); // the console will tell us if there are any problems
}
}); //end ajax
return false; // prevent default button behavior
}); // end click
jQuery Ajax
http://api.jquery.com/jQuery.ajax/
Script explained.
1 - User clicks the button.
2 - Click function initiates an XHR call to the server.
3 - The url is the php script that will process the data we are sending based on the values posted.
4 - The type is a POST request, which needs data to return data.
5 - The dataType in this case will be html.
6 - The data that we are sending to the script will probably be a serialization of the form element that is assigned to the variable formData.
7 - If the XHR returns 200, then log in the console the returned data so we know what we are working with. Then place that data as html inside the selected element (#update-menu).
8 - If there is an error have the console log the error for us.
9 - Return false to prevent default behavior.
10 - All done.

Related

Create a waiting page with PHP and twig

I post data to a page and make some checks that take 5-6 seconds. I would like to insert a waiting page to improve the user experience.
My code is like this:
....functions that take time
echo $twig->render('template.html.twig',[ variables ....]);
Because PHP calls the twig template at the end after processing the data I cannot use a javascript solution.
I tried rendering a waiting template first, then process the data and store the output in a session variable then after that send a location header to the results page but I found PHP does not echo the waiting template untill it finishes the whole script even if i call it in the beginning.
echo $twig->render('waiting.html.twig',[ variables ....]);
....functions that take time
store output as session variable.
send location header to another page that renders the template from the session variable
How can I achieve a waiting page?
You could always store the data temporarily and load a dummy "loading page" for the user. And right when the dummy page loads you send an ajax request that recovers your data and processes it. When the ajax call returns you could do your redirection or whatever it is you want to do when the process is done.
When I say "store the data temporarily" I mean in a database or a file, etc.
The solution I ended up doing was the following:
Call the page by Ajax and display a waiting page.
function submit_form(file_method) {
var spinner = $('#loader');
spinner.show(); //show waiting div
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
success: function (res, status) {
if (status == 'success') {
window.location.href = 'results.php';
} },
error: function (jqXHR, textStatus,res) {
spinner.hide();
alert('Error encountered: '+textStatus+'-'+jqXHR.responseText);
} })
};
In the php page, store the output as an array in a session variable.
....functions that take time
$_SESSION['result'] = [RESULTS .......]
After the ajax call is completed successfully the user is redirected to a new page. The new page uses the session variable to call the template.
echo $twig->render('waiting.html.twig',$_SESSION['result'] );
unset($_SESSION['result']);
Simplest solution is to add 'waiting page' inside first page but hide it. When user presses button browser will send request, but will still wait for response showing old page. Here you can show it using JS.
In short - user presses button, you show template (which was already there but hidden) and then browser just waits for response with your template in front.
But best way would be to use AJAX like Patriot suggested.

PHP: Assigning an AJAX response value into PHP Variable

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

Why my AJAX function blocks the header of PHP that I have on my page?

I am doing a program in PHP (MVC) in which I need to delete a row from the database when I click on a link on the View side. So, when I click on the link, the following ajax function it is called.
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
}
});
}
but I do not want to send any data so it is the reason why I put it as above.
Then, in the Controller side I have the following method:
public function deleteCar($id)
{
//Here I call the function to delete the Car that I send by id. It works fine.
header('Location: http://localhost/project/car');
}
If I call directly the method deleteCar on the link without Ajax the header works properly but in the same moment I use Ajax to call it, I have to refresh the page to see the content that I have modified, I mean, that the Car have been deleted.
The code works fine, just I do not want to refresh the page after AJAX function had finished.
Thanks in advance!
I am guessing the use case is to allow the app to work when the user does not have JS enabled - so they just click the links and get a non-AJAX experience. In this case you probably want to redirect ONLY if the page was requested via GET, not POST. something like
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
header('Location: http://localhost/project/car');
}
is likely what you are looking for.
You will then have to actually remove the element representing the car from the DOM in your success handler, with something like:
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
$('#car-row-' + id).remove();
}
});
}
(that won't be it exactly, it depends how the HTML of your page is setup how exactly you will do this).
I believe the key thing to understand here is - when your PHP function has completed it has removed the car from the database, but the browser still has the same HTML it got from the page originally. Just sending an AJAX request won't change that. If you want the HTML in the browser to change to reflect the new state of the database, you will NEED to do one of two things:
Refresh the page, so the entire thing is rebuilt by PHP based on the current database state
Use javascript to change the HTML in the browser, to reflect the changes you have made to the database state.
It is wrong on so many levels but it's difficult to put in words. It's subtle.
Long story short - think about jquery.ajax as of another virtual tab of you browser.
When you make ajax-request to the server - you create new virtual tab.
You php header could affect this virtual tab and redirect it where that header defined.
But it will redirect that virtual tab, not your current tab - if that makes sense.
What are your options? On success - make redirect with pure javascript.
success: function(response){
location.href = "http://localhost/project/car";
}
This would be the basic way to solve your problem.

Show each response of php file using ajax

I use ajax type for send data to php file and get response and show. In my php file i have
while($i<14){ echo $i.'<br />'; $i++;}
that return 14 replay.
So, my webpage when call data with ajax method, after some secounds, show all 14 results. But i want get live response from my ajax file.
So i want my webpage show :
1
...
and then
1
2
....
etc
This is my Ajax code that return all response together in shower div.
I want get live responses. for any responses that sent from php file
function update_table(uptype){
$("#shower").html("Loading...");
var dataString = 'type=' + uptype;
$.ajax({
type: "POST",
url: "motor.php",
data: dataString,
cache: false,
success: function(html) {
$("#shower").html(html);
}
});
return false;
}
What you are asking is not possible with your current setup.
Think of an ajax-call to a PHP-script is like visiting a website like www.example.com/yourscript.php
PHP will then server-side render a code which is sent to your web-browser. This is a one call and one answer operation. PHP will not dynamically add elements to the website. Neither will it then be able to dynamically send answers to your ajax-call. What you have to do to solve this is storing the progress of the PHP script somewhere, and do several calls to get a update on the status.

AJAX call to PHP receives the "previous" posted data

So I post data from a form using the jQuery form extension. This code is executed when the user presses ["Save"] on the HTML page.
$('#myform').ajaxForm({
async: false,
cache: false,
target: $(this).find('.save-response'),
beforeSubmit: function(arr,$form){
json_ = JSON.stringify (vars.table_settings[aux.getTableId()].by_ix); //, null, 4);
$form.find('.user-settings').val(json_);
$form.find('.save-response').stop(true,true).hide().show();
alert (json_);
},
success: function(){
$(this).fadeOut(15000);
},
As you see, I use the alert() function to check what is actually being delivered in the AJAX call, to the destination PHP file. What I see is the following:
[
...
{"id":"colpartdesc","vis":"vis","width":500,"ix":3,"desc":"Part Desc."},
...
]
On the PHP file, I read the $_POST value, and feed it back to the calling page (to the .save-response element in this example) as a response. What I get as a reply is this:
[
...
{"id":"colpartdesc","vis":"vis","width":270,"ix":3,"desc":"Part Desc."},
...
]
As you see, the "width" value is different. In fact, a value of 270 is the value that I sent the last time I pressed the ["Save"] button. If I press ["Save"] again, the server will receive the 500 value sent in this call. But it may be that the value of 500 is wrong by that time.
If I press the ["Save"] button twice each time before changing the input, then the functionality works as expected.
As you see, I've disabled the cache in the Ajax call, so I don't think this is the problem.
Does anyone have an idea why I am experiencing this behaviour?
Aside: the original HTML page is generated using Smarty templating engine. However, I have switched off caching in the Smarty engine too, so again, I don't think this is significant. Also, the PHP file processing the Ajax call does not use a Smarty template.
The answer to the problem is that I don't know how the jQuery Form plugin works.
jQuery Form does not submit the values in the fields of the form, but rather the value in the array. Therefore, updating the values in the form itself withing the beforeSubmit function (as done in the following line) is incorrect:
$form.find('.user-settings').val(json_);
What I should be doing instead is to update the form-data array, like this:
$('#myform').ajaxForm({
$(this).ajaxForm({
target: $(this).find('.save-response'),
beforeSubmit: function(formData,$form){
json_ = JSON.stringify (vars.table_settings[aux.getTableId()].by_ix); //, null, 4);
formData[1].value = json_;
$form.find('.save-response').stop(true,true).hide().show();
},
success: function(){
$(this).fadeOut(15000);
},
});
The answer to >>this<< post is what put me on the right tracks.

Categories