send data from page to page using ajax without server interaction html - php

I want to send json object from page 1 to page 2 without server interaction what i have tried so far is like this
from page 1 i have this code
url = '../reports/page2.php?basicinfo=' + encodeURIComponent(JSON.stringify(basicinfo));
window.open(url + "&month=" + month, '_self');
in page two i acces the data by getting the object from the url.
But i had a problem. I exceeded the The requested URL's length exceeds the capacity limit for this server. So i wanted to try if it is possible using ajax what i have tried is
var url = '../reports/page2.php;
var basicinfo = JSON.stringify(basicinfo)
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
action: "page2",basicinfo:'basicinfo '
},
complete: function() {
window.location = url;
}
});
I was directed to the correct page my problem is i cant get the data now.

For this purpose You can use localstorage save your json in localstorage variable and fetch it at any moment
localStorage.setItem('favoriteflavor','vanilla'); /*how to save data in localstorage*/
var taste = localStorage.getItem('favoriteflavor');/*how to fetch data from localstorage*/
alert(taste);
localStorage.removeItem('favoriteflavor');/*how to delete data from localstorage*/
For more details click here
So save all your json in localstorage variable before
window.location = url;
in your ajax complete section and fetch localstorage data after redirection (i.e. on this page url )
If you don't want to use jquery variable for data security. Then the only possible way is by using cookies.
Here is the link on stack from where you can see how to create cookies using jquery how to save data in a cookie using jquery

Try to write this to a file and read from the popup.
http://php.net/manual/en/function.file-put-contents.php
http://php.net/manual/en/function.file-get-contents.php

HTTP is stateless protocol. When you redirected to another page - it is new request and data from previous page will be lost.
To share data between pages need to store data (from first ajax request), e.g in session, and restore data from session on second page.

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

Sending data ajax

I have a page called post-blog.php, in here I've set-up a blog entry. I have all this data being saved into one variable. Its displaying this data in an array.
var data = title + content + image + datetime + categories;
How can I send this data to another page called publish.php and redirect the user to that page ?
I've tried to set up a ajax to do this but its not working. Any suggestions ?
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: data,
success: function( data ) {
alert ( data );
}
});
return false;
});
As per my understanding of the problem, you need to pass the data to a new page and open that page.
If this is your question then this can be done without AJAX, basically AJAX does not even provide solution here. Instead you can just pass all the data to your new page in query format as below -
var page = 'publish.php?title='+title+ '&content='+content+'&image='+image+ '&datetime='+datetime+'&categories='+categories;
Then just change the window location as below
window.location.href = page;
And to get all those variables in your PHP file, do the following in publish.php on top -
if($_GET['title'])
{
$title = $_GET['title'];
}
// similarly get all the data in publish.php file and continue with your page
I am assuming all your variables are strings. If they are not, for example the datetime may be an object, change them into a string first.
Docs say Object must be Key/Value pairs or a string.
Objects work well for this, try something like:
var data = {title: title, content: content, image: image, datetime: datetime, categories: categories};
If your data is coming from a form check out jQuery's serialize.
I've never tried to pass as a string in a POST, but my gut feeling is it would need to be in a format similar to passing the data through the url.
var data = 'title=' + title + '&content=' + content;
Also keep in mind the data in the success function is not the same as what is being passed to the php page. This is what the php page will return. If you're php page returns nothing your alert will be empty. When I'm testing I like to throw something like echo $_POST['title']; in the php file to see something come back.
Here is a similar question that might help too.

Send sql data from jQuery

I'm trying to retrieve database information based on what row a user clicks in a table, then later use that data in another page to display other database information. I don't know the best way to achieve it. Should I use Ajax and $.post() or are there other better/simpler ways?
I can retrieve the data from the table by
echo "<tr data-href=". $row["id"] . " class=\"tableclass\"><td>"
and then in jQuery
$(".tableclass").click(function () {
data = $(this).data("href");
alert(data);
The alert shows that I do get the database information (column ID). Now, I would like to post that information, preferably in a secure manner, to another PHP page where I can retrieve it and use it to get other information from the database.
How do I post it and then how should I retrieve it in the next php page?
Both works in same manner.
1. $.post is just a call with $.ajax(), just with the type set.
2. $.ajax() defaults to a GET
$.post( "/ajax", {"data" : json }) //is nothing but
$.ajax({
type: "POST",
url: "/ajax",
data: {"data": json}
});
If you want the data to be passed securely, use json or don't do thing if the request is not properly authenticated.
Typically, when you make an AJAX request, cookies are also sent: along with the request so you should just be able to use the same authentication method that you use for your regular requests with your AJAX requests.
Nothing much to do that, you need to use $_POST to access all the values in php in file save.php

Return PHP data back to my current webpage for Javascript to access

I have a form which users will submit to my WordPress website, and with that data I will create a post. The form submission is done with AJAX so the page does not reload. I have the post ID that I need to pass back onto the page so the Javascript can POST more data to that specific post.
How can I pass the post ID, which is just a integer, back to the page so I can keep editing that post?
You're going to have to use AJAX. It's impossible for PHP code to pass variables directly to Javascript without a page load, since PHP is server sided (parsed before page load) and Javascript is client sided (parsed after/during page load).
My suggestion: Make a script that retrieves post IDs, for example "pid.php". Then simply get the contents of that page with AJAX and convert to integer form with parseInt for Javascript.
EDIT: As Austin so wisely suggested, you could also use json.
After a successful ajax request, save the post id to a global variable so It can be used later.
For example
Client side:
var post_id = 0; //use the post id later to edit the same post.
$.ajax({
url: 'somefile.php',
success: function(data) {
alert('success, post id is: ' + data.id);
post_id = data.id;
}
});
Server side:
$post_id = 123;
echo json_encode(array('id' => $post_id));

Categories