Using jquery to create php sessions - php

I am looking to use jquery to add to the DOM for an <ul>, I want to add more <li>'s into the list, but just to last for a session with php.
e.g.
$lists = $_SESSION['names']
//which contains an array of all the 'names', and then I would run a loop:
echo "<ul>";
foreach($lists as $list) {
echo "<li>$list</li>";
}
echo "</ul>";
So the user can add these variables into the list, during this session.
How would this be done, and how is the jquery able to interact with php like this? And what method would be easiest?

It seems like you misunderstand how PHP works.
PHP is a server side script. This means that it runs on a server and the user can't see it running or have the code appearing on his side.
jQuery is a javascript library. It is a client side helper for user interactions.
So basically there's no way to directly run PHP from an HTML document
But indirectly there is AJAX.
AJAX allows you to visit a page (and basically running a PHP script) without reloading your page.
http://api.jquery.com/jQuery.ajax/
Example
$.ajax({
type: "POST",
url: "some.php",
data: { list: jQueryVariableList
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Now on the PHP side you can pick up the list using $_POST['jQueryVariableList']

Have a look at this:
In javascript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In html:
<div id='div_session_write'> </div>

Related

run a query code to retrieve array from database without page refresh

Am kind of not into ajax or json requests, but it seems i might be needing it now or any alternative means, am working on a school management software, i have a page with forms in which when i select a class on the form, it loads all subjects attributed to the class from the database, i already have a php code that would query that, but since php is a server-side language, i would have to reload the page to get the list of subjects from the selected class.. please how can i go about it using any means; here is my code to get classes based on class selected into an array... how can i make this run without a reload
$subjects = $this->crud_model->get_subjects_by_class(class_id);
Basic ajax call:
<script>
$('#button').click( function () {
$.ajax({
type:"POST",
url: "phpsite.php",
data: {
postdata: variable
},
success: function(data){
$('#divtochange').html(data);
}
});
} );
</script>
In phpsite.php, just put the code you would usually refresh. You will need to include jQuery.
Here is a tutorial

Saving variable data from jQuery to PHP and getting it after page reload

I'm new to PHP and trying to figure this out and still not understanding. I'm trying to take the value of a html text box in jQuery and turn it into a variable I can then store as a (variable or string?) and pull back again after a page refresh.
I want the user to hit a button that then executes the following:
$('.save').click(function () {
// pulls the value from the textarea
var file = $('#subtext').val();
// send to php to hold text
$.ajax({
url: '/mininote/system/data.php',
type: 'POST',
data: { textbox: file },
success: function(data) {
alert('Saved data to php!');
$(save).text('All changes saved.').show().delay(3000).fadeOut(800);
}
});
});
Then receives the post data and stores in the php until the user reloads the page where it pulls data (or checks if there is any) from the php like so and replaces the value of the textbox with the value from the php:
$.ajax({
url: '/mininote/system/data.php',
type: 'GET',
data: { textbox: file },
success: function(data) {
// add text back to text box
$("#subtext").val(data);
}
});
Basically what I'm looking for is below:-
a way to perform an ajax POST to insert the data grabbed from the textbox,
add to PHP
on a page reload use a GET request and replace textbox text with text from the PHP file.
What would I need to put into the PHP code? Or would it be easier to go in another direction? I've gotten this method to work in local storage. I also want browser compatibility for this work.
I don't need to set it up for a bunch of users. Any response that will increase my knowledge on this will help greatly.
EDIT: I'm really looking for something more server-side so it's usable across multiple platforms and devices.
actually jquery-ajax works like below:-
it takes request and
it gives response.
For Your requirement You also need to follow this steps. so for this , You
send request to PHP page then
send response from php page
so replace Your above jquery-ajax code part with below:-
$('.save').click(function () {
// pulls the value from the textarea
var file = $('#subtext').val();
// send to php to hold text
$.ajax({
url: '/mininote/system/data.php',
type: 'POST',
data: { textbox: file },
success: function(data) {
alert('Saved data to php!');
$('#subtext').val(data);
$(save).text('All changes saved.').show().delay(3000).fadeOut(800);
}
});
});
make sure in Your data.php page textbox value has made echo after inserting data to DB. This process would be something like below:-
data.php
<?php
$textbox = $_POST["textbox"];
/*
perform Your DB inser part here
*/
if(data inserted to db)
{
echo $textbox;
}
?>
Hope this will help You.
You could use the following simple PHP script to accomplish your goal:
<?php
session_start();
if (isset($_POST['textbox'])) {
$_SESSION['textbox'] = $_POST['textbox'];
} else {
echo $_SESSION['textbox'];
}
?>
Another option would be to use HTTP Cookies. Just set the cookie with JavaScript using a plugin or something simple such as, document.cookie = "variable=value"; and access it in PHP with, $_COOKIE["variable"].
Hope this helps.
In the PHP code you could use a PHP session variable like so:
$_SESSION['saveMe'] = $saveMe;
Then get it later, even after a refresh, by using the session variable in php as you would normally use any variable.
For more info see http://www.w3schools.com/php/php_sessions.asp
Use a session, like a temporary cookie, like the following.
session_start();
$_SESSION['sessionName'] = $sessionVar;
Then you can destroy the session with, session_destroy();
See more here.
Why you send it to PHP ?
Just saving in client-side with cookie is better and access in PHP with $_COOKIE
Download jQuery.cookie from :
carhartl/jquery-cookie
and do :
$('.save').click(function () {
// save data from textarea to cookie
var data = $.trim($('#subtext').val());
$.cookie('TEXTAREA_VALUE', data);
});
and go to read by PHP :
<?php
echo $_COOKIE['TEXTAREA_VALUE'];
?>
and to remove :
$.removeCookie('TEXTAREA_VALUE', { path: '/' });
Okay friend !
Ajax is mainly used for sending data without reloading the webpage - from client(js) to serverside(php) or from serverside(php) to client(js). Make sure that name-attribute is given in the textarea and that method is set to post in the form. If I understand your issue correctly you could do something like this:
<?php
session_start();
if (isset($_POST['subtext'])) {
$_SESSION['subtext_value'] = $_POST['subtext'];
}
if (isset($_SESSION['subtext_value'])) {
$subtextValue = $_SESSION['subtext_value'];
}
else {
$subtextValue = '';
}
?>
<html>
<body>
<form action="/mininote/system/data.php" method="post">
<textarea id="subtext" name="subtext"><?php echo $subtextValue;?></textarea>
<input type="submit" value="ok" />
</form>
</body>
</html>

Run ajaxed javascript

I know this has been covered a few times, but I'm completely a noob when it comes to javascript so I have no idea what I'm doing. I am running a javascript that sends variables to a php file and that info is ajaxed into the current page using innerhtml. Here is that part of the code...
function givingHistory(dyear,did)
{
var divname="giving" + dyear;
$.ajax({
url: 'finance/givinghistory.php',
type: 'POST',
data: {
year: dyear,
id: did
},
success: function(givedata) {
document.getElementById(divname).innerHTML = givedata;
}
});
}
</script>
In the givedata function response from the php file there is a call to another javascript function that is already loaded in my common .js file (so both javascript functions are loaded when the page loads). How do I get the onClick that is added via innerhtml to work? Inside the php file, I check to see if id = a php session variable. If it does it spits out the text that includes the onClick.
If you use a specific id/class/identifier when the page loads in the $('*') function then the action will only bind to that. To get the action bind to anything ever try using $(document).on('click', **selector**, function() {});.
Previously there was bind/live that bound to elements as and when but on is the function now.
Also why are you mixing the $.ajax (jQuery) with document.getElementById(divname).innerHTML (regular javascript)? If you are already using jQuery you could just use $('#'+divname).html(blahbahblah);

PHP Does Not Seem To Play Nicely With An XML String?

I am creating an application where a users draws shapes on a canvas and then saves and retrieves them from a database. The saving part works fine, now though, im trying to load this XML content, Thats where the troubles are starting.
Firstly a user has a list of documents they have created, when clicked it loads that document into the applicaiton to do this, i use the following code, firstly a javascript function which takes the ID of the document, then sends it to a PHP script which retrieves that documents data from a database. The PHP script than loads that documents data into a $_SESSION['data'] variable. Once done, it goes back to the javascript function which redirects the user to application page.
function loadDocument(docID){
$.ajax({
url: "load_a_document.php",
type: "POST",
data: {
documentID: docID,
},
success: function(data)
{
alert(data); //THIS DISPLAYS THE XML WITH NO PROBLEMS???
window.location = "application.php";
}
});
};
The PHP queries the database and retreives the name and XML content of the document, it then does this:
$_SESSION['document_Name'] = $doc_NAME;
$_SESSION['document_XML'] = $doc_DATA;
echo($_SESSION['document_XML']); //this is 'data' on the ajax success call
Now when the PHP is finished it echoes the php context, this shows up in the alert box in the success:{} of AJAX with no problems. Now it takes the user to the actual application which begins like so:
<?php
session_start();
$document_Name = $_SESSION['document_Name'];
$document_Data = $_SESSION['document_XML'];
?>
<script>
alert(" <?php echo $document_Name; ?> "); //WORKS FINE
alert(" <?php echo $_SESSION['document_Name']; ?> ") //WORKS FINE
//alert(" <?php echo $document_Data; ?> "); //STOPS THE PAGE LOADING
//alert(" <?php echo $_SESSION['document_XML']; ?> ") //STOPS THE PAGE LOADING
</script>
Fetching the first two items, there are no problems, as soon as XML data is printer then their is a real problem. I dont understand why the loadDiagram() can alert
() the XML but my application page cannot. Has the data been corrupted somehow?
Thanks for any feedback.
You probably have quotes in the string that's causing the problem. Try
alert(<?php echo json_encode($document_Data) ?>);

Include PHP file inside a DIV using Jquery & AJAX [duplicate]

This question already has answers here:
using php include in jquery
(2 answers)
Closed 9 years ago.
My problem is that I need to include a PHP file inside a DIV when a button is pressed without the page reloading.
There is even more explanation in the 'Jsfiddle' file.
Below is an included Jsfiddle document.
http://jsfiddle.net/jjygp/5/
Thanks for your time. I am more than happy to provide any information upon request.
See here for your updated jsfiddle
You had marked the change button with a name of Change but were trying to select it with an id of change. Also, you had not told jsfiddle to include jQuery.
Try the following:
<button name="Change" id="Change">Change Div</button>
You are specifying a click function on an id, but no id is set on the button.
You can try with load() function in jquery
http://api.jquery.com/load/
PHP is a server-side script language, which will be executed before a JavaScript script did.
Therefore, you cannot use .load() to execute a PHP code, however, you may try .ajax() to create an AJAX request to the server which can implement the PHP code.
Please see http://api.jquery.com/jQuery.ajax/ if you have trouble on using .ajax().
Note: in .ajax() method, there is a setting called beforeSend, which "can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent". Hope this method helps you in any way.
Then, your JavaScript code will be like this:
$(document).ready(function(){
$("#Change").click(function(){
//doing AJAX request
$.ajax({
url:"include/start10.php",
beforeSend:function(){
$('#myDiv').fadeOut('slow');
},
success:function(data){
// do something with the return data if you have
// the return data could be a plain-text, or HTML, or JSON, or JSONP, depends on your needs, if you do ha
$('#myDiv').fadeIn('slow');
}
});
});
});
You cannot include PHP file with AJAX, but instead the response of the AJAX server-side script, which is the PHP (which has the same effect).
Loading...
The JS file (code):
function ajaxalizeDiv()
{
$.ajax({
type: "get",
url: "/path/to/the/php/you/want/to/include",
data: {
// Anything in json format you may want to include
id: myvarwithid, // descriptive example
action: "read" // descriptive example
},
dataType: "json",
success: onAjax
});
}
function onAjax(res)
{
if(!res || !res.text)
return;
$("#mydiv").html(res.text);
}
And here goes the PHP file:
<?php
$id = (int) #$_GET['id']; // same as in data part of ajax query request
$action = #$_GET['action']; // same as in data part of ajax query request
$text = 'click me';
// Note this is short example you may want to echo instead of die
// You may use not JSON, but raw text. However, JSON is more human-friendy (readable)
// and easy to maintain.
// Note also the array keys are used in the onAjax function form res (response).
die(json_encode(array('text' => $text /* and anything else you want */)));
?>

Categories