Using Ajax to create PHP session and echo results - php

I'm using ajax to pass data to a php session in order to save the contents of a js powered shopping cart. Here is the test js code:
//js.html
<html>
<body>
<script>
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"productName": brandName}, function(results) {
//success alert
});
}
</script>
</body>
</html>
and here is the php code:
//session.php
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
?>
<html>
<body>
<?php
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
</body>
</html>
However what I need is after having saved the data to the session, I want to output it to the user in a mini cart in the sidebar.
When I run js.html it successfully passes the data to sessions.php. However the echo isn't displayed in js.html. If I run sessions.php then the echo displays but isn't in the page I need.
My question is, either via PHP or js, how do I then echo or display this data to the user on the page I need?
Thanks

Change session.php to this:
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
And in your HTML code:
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"name": brandName}, function(results) {
$('#SOME-ELEMENT').html(results);
});
}

$.post("sessions.php", {"productName": brandName}, function(results) {
alert(results.productName);
},"json");
//session.php
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
echo json_encode(array('productName' => $_SESSION['productName']);
?>

Using Pure Javascript
The echo isn't appearing because you're making an AJAX call. I don't see what's stopping you from outputting the details in the JS code, underneath where you make the Ajax request.
$.post("sessions.php", {"name": brandName}, function(results) {
//As in put the code here.
});
With the mootools Library
Alternatively, you can look into the mootools library. That library has a Request object, with an onSuccess method. You can port your shopping basket code into that onSuccess method.

Related

How do I use jquery to get data from a form before submission?

I am trying to get data from a gravity forms field to update data in another field. From my research it seems I need to use jquery to do this. What is the bast way to handle this? If I put the following code in my php code - how do I access the variable?
add_filter("gform_field_value_MgrPhone", "set_mgr_phone");
function set_mgr_phone($value){
global $wpdb;
$mgr_name = "Tracy Kaufenberg";
?>
<script>
var mgr_name = document.getElementById('input_20_81').value;
console.log(document.getElementById('input_20_81').value);
</script>
<?php
$sql = "SELECT PhoneNumber
FROM ADusers
WHERE phoneNumber IS NOT NULL AND displayName = '" . mgr_name2 . "'" ;
//echo $sql;
$sql = $wpdb->prepare($sql,20);
$results = $wpdb->get_results($sql);
$myArray = array();
//echo count($myArray);
foreach ($results as $result) {
$myArray[] = $result->PhoneNumber;
}
foreach ($myArray as $v) {
$phone = $v;
}
echo $phone;
return $phone;
}
Native JavaScript option:
<script>
var mgr_name = document.getElementById('input_20_81').value;
</script>
You can test this in your JavaScript console too:
console.log(document.getElementById('input_20_81').value);
I would strongly suggest you take a basic JavaScript Tutorial: https://www.w3schools.com/js/default.asp
You can then look at jQuery if you want.
Update
Moving a PHP Variable into JavaScript
<?php
$mgr_name = "Tracy Kaufenberg";
echo "<script>var mgr_name = '$mgr_name';</script>";
?>
Since PHP is a preprocessor, it is only executed on the server-side. So to pass a variable back to PHP, we have to send it via HTTP with either GET or POST.
<html>
<body>
<form action="saveMgrName.php" method="POST">
Manager Name <input type="text" id="input_20_81" name="input_20_81" value="Tracy Kaufenberg" />
<button type="submit">Send</button>
</form>
</body>
</html>
So the user hits Send and the browser sends the data to the web server and PHP can access it using $_POST['input_20_81'] and the value will be "Tracy Kaufenberg".
If you want to collect data from PHP with data entered in the Browser, you can use AJAX to send that data to PHP and get a response without loading a new page. It uses JavaScript to build a HTTP Request and send it to the server in the background in a sense.
Given the above HTML Code, you can use jQuery like so to accomplish this.
$(function(){
$("form").submit(function(e){
e.preventDefault();
$.post($(this).attr("action"), { mgr_name: $("#input_20_81").val() }, function(response){
console.log(response);
if(response){
alert("Manager Name is saved.");
}
});
});
});
If you need to GET data from PHP, you may consider using $.get() versus $.post().
Hope that helps.

posting data on jquery post

Using jquery
$.post('target.php', data, function(result) {
window.open('target.php');
});
In target.php
var_dump($_POST);
Results in
array(0) { }
I have the code above inside ajax success after success I want to open the target page in new tab and sending data in that page.
But this results in an empty array.
How to correctly send data using post request and how to retrieve it in target page
You can simply do like below
var data = {suggest: 'Any String'};
$.post("target.php", data, function(result){
window.location.href = 'target.php'
});
In PHP Side, You can store that in $_SESSION variable like this
session_start();
if(isset($_POST) && !empty($_POST)) {
$_SESSION['my_post_data'] = $_POST;
echo 'done';
exit;
}
When the page is opened using window.open method, you can get the POST data using
print_r($_SESSION['my_post_data']);
jQuery post is an ajax call that happens on the background and therefore you won't be able to achieve it that way.
What you can do is a normal form post to the new tab.
<form target="_blank" action="target.php" method="post"> ... </form>
Notice the target blank like in a link. Then submit that form.
$('form').submit()

Resetting a PHP $_SESSION array with jquery function

I am trying to reset a session array in php with a function in jquery using a button. I would use a submit but I don't want the page to refresh. I tried to send a $.post request leaving the variables and return blank, and then sending a variable so I could use $_session[''] = array() but none of it worked. I have searched and can't find much about it just a lot on sending strings.
OK this is very simple to stop the page from refreshing you need to tell js to disable the default event i use jquery for this here is my code
Html & js
<html>
<head>
<title>Reseting a PHP $_SESSIO array with jquery function</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function sessRest(){
$.post("rest.php", {x: "9845621"}).done(function(data){
alert("States: " + data);
});
}
$(document).ready(function(){
$("#target").click(function(event){
event.preventDefault();
sessRest();
});
});
</script>
</head>
<body>
<div id="main">
Click to rest me
</div>
</body>
</html>
php code rest.php
<?php
session_start();
(string)$data = $_POST['x'];
if($data == "9845621"){
$_SESSION['gx'] = array();
return $_SESSION['gx']; //return the empty array to js
}else(
return "error";
)
?>
I hope this helps .
User below jquery to submit to php code
var requestData = { param: "value"};
$.ajax({
url: your_url/session_change.php,
type: "post",
dataType: "json" or what ever,
data: your_data,
success: function (data) {
}
});
You can end the session successfully on server side with an ajax call, but apart from reloading the page, you're not going to clear what information was loaded already on client side. The session information wont be there once you do reload, but there is no way around that.
You can, however, emulate what you want to do with javascript.
When you load your session information, echo it to the page as javascript variables, then you have full control on client side. Just beware of echoing sensitive information like passwords, obviously.
try this:
your html file should contain this jQuery file:
$('#button').click(function(e){
e.preventDefault();
jQuery.ajax({
url: 'http://yourwebsite.com/session.php'
}).done(function(data){
if(data=='reseted'){
//do anything...
}
else {
//do anything...
}
})
});
and in your session.php file:
<?php
session_start();
session_unset();
if($_SESSION == FALSE){
echo 'reseted';
}
else echo 'no';
?>
the answer was
jquery $.post('reset.php');
in reset.php
$_SESSION['products'] = array();
?>
this reset my session array when the reset button was clicked with no page refresh...
I had done this originally and forgot to include my core.php in the reset.php which contained my start session()..
Thank you all for the help though.... great suggestions

Change value of PHP variable with AJAX

The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it

Refreshing data in session_start()

I have two files php(index.php & data.php), the first send data to the second, and this it runs every one second and show the data.
The problem is the data is not updating
Maybe the code explains better
data.php
<?php
session_start();
$xml = simplexml_load_file("file.xml"); // the contents of the file changes every second
$json = json_encode($xml);
$_SESSION['varname'] = $json;
?>
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script language="JavaScript">
window.setInterval(function() {
<?php
session_start();
$json = $_SESSION['varname'];
?>
var newdata = <?php echo $json ; ?>;
//code to show data
}, 1000);
</script>
Thank you in advance
session_start must be called before any output (see notes in the documentation) which means you have to call session_start before any output:
<?php
session_start(); ?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script language="JavaScript">
window.setInterval(function() {
<?php
$json = $_SESSION['varname'];
?>
var newdata = <?php echo $json ; ?>;
//code to show data
}, 1000);
</script>
You are not actually calling your data.php script from your javascript at all. Your javascript is just static at this point (look at your output source), executing the same function over and over again with the same value for newdata. You need to actually make an AJAX call to the data.php script to update the JSON.
Note that the session_start comments on this thread are important. This should be fixed as well, but that will not solve the fundamental problem you area having of wanting to use javascript to pull in the updated JSON data, but not having the value of newdata change because it is currently just static on your page.

Categories