Understanding of ajax returning - php

I have some problems with understanding of ajax use.
Let's say I have file like this (this is just a pseudo code, dont look at the basic mistakes right now please) I have read so many articles, but i find them so hard to understand
///////////////// file 1 /////////////////
<?php
x = 1;
<button onclick=somefunction(x)></button>
?>
<script>
//here goes some ajax code sending this x variable to another php file
</script>
Lets say it looks like this
////////////// file 2 ////////////////
<?php
/get x variable + sendint it back
return x=2
?>
Now what i want to do is to make this x value come back to the first script and make x=2. How do i do this?

Here is an example using JQuery with some notes to try to describe what happens.
<html>
<!--file: ajax_basic.php-->
<head>
<title>Ajax Basic Example</title>
</head>
<body>
<input type="text" id="example_input" value="1">
<button id="example_button">Example</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// .click(function() executes an anonymous function when the button is clicked
$('#example_button').click(function() {
// get the current value from the input
test_value = $('#example_input').val();
// $.get is the AJAX method.
// It sends the object {'sent_value': test_value} to test.php
// function(response) is the the function that will be executed when
// a response is returned from the test.php
$.get('test.php', {'sent_value': test_value}, function(response) {
// here, x is taken from the response of the php script.
// You can do whatever you like with this value.
x = response.returned_value;
// for this example, it updates the value of the text input
$('#example_input').val(x);
}, 'json');
});
});
</script>
</body>
</html>
This is the PHP file that will handle the request. All it does for this example is increment the value it receives and return the new value.
<?php
// file: test.php
$response = array('returned_value' => $_GET['sent_value'] + 1);
echo json_encode($response);

If you are using jQuery, you should switch from onclick=somefunction(x) to a jQuery binding, ie. .on()/.click()/etc. see https://stackoverflow.com/a/826697/689579
Using jQuery you could do something like-
<?php $x=1;>
<button id="mybutton">MyButton</button>
<script>
var x = <?php echo $x; ?>; // set initial x value to php value
$(function(){
$('#mybutton').click(somefunction);
});
function somefunction(){
$.ajax({
url: 'phppage.php',
data: {number:x}, // send current x value
...
success: function(result){
x = result; // when php file returns 2 (or other value increase x
}
});
}
</script>

Related

set session from jquery to session in php

i have a page in php to execute query. when i need the parameter from another page with session using jquery. so, how to set session in php from session in jquery. please check my code and give me solution. thanks...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.ciphertrick.com/demo/jquerysession/js/jquerysession.js?d56ac9"></script>
<script>
$(document).ready(function(){
var sDecode = $.session.get("sesDecode");
alert(sDecode);
});
</script>
<?php
include('connection.php');
$content= ==> how to get " sDecode " ???
$upd = mysql_query("UPDATE t_modules set content='$content' where id_t_modules='3'") or die(mysql_error());
?>
You can use ajax to send parameter to a php file like this
$.ajax({
url: "connection.php",
data: "Session="+$.session.get("sesDecode"),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
Note that both solutions needs you to check the input since the user could potentially modify it.
Using Ajax
The best way to get sDecode is probably to send it via jQuery.post() (AJAX) to a PHP page that will register the session value (after doing the appropriate checks to it).
$.post('session.php', { d: sDecode }, function (response) {
alert(response);
});
and you get it in PHP via :
$sDecode = $_POST["d"]; // Please test the input here!
You might have to use .serialize() and then unserialize it in PHP depending on the content and how you treat it.
Using Redirection
You can simply redirect to a page and transmit it directly as a GET value:
window.location.href=”session.php?d="+sDecode;
Then on the session.php page you would read it using this code :
$sDecode = $_GET["d"]; // Please test the input here!
You can have PHP fill in the Javascript variable from the session variable.
<?php session_start(); ?>
<html>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var sDecode = <?php echo json_encode($_SESSION['sDecode']); ?>;
alert(sDecode);
</script>
PHP execute before Jquery so use ajax after get the parameter from session to do your query

Global variable inside Ajax function

I'm learning the Ajax method with jQuery. I've a simple code here. It's to load data from a csv file by jQuery Ajax method, and put it into an array for further use. But it seems the array lost outside of the Ajax function even I do make the array global in the first place.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var db=[];
$(document).ready(function(){
$.ajax({
url: 'loaddata.php',
success: function(data){
var arr = data.split('|');
for(var i=0; i<arr.length; i++){
var miniArr = arr[i].split(',');
db.push(miniArr);
}
printTest(); //work here
}
});
printTest(); //not working and collapse here
});
function printTest(){
document.getElementById('test').innerHTML += db;
}
</script>
</head>
<body>
<div id="test" />
</body>
</html> `
My php file should be fine,
<?php
$database = file('database');
foreach($database as $item){
if ($item===end($database))
echo $item;
else
echo $item.'|';
}
?>
Thanks in advance.
Your second printTest() is where the .ajax parameters go, so there's a syntax error there. The reason the first call works is because it's inside the success callback, and since AJAX is asynchronous this is called when the call has completed.
If you put the printTest() call after the AJAX call, it will be called immediately after the AJAX call has started, not waiting until it completes, due to async.
You can't call your second printTest() here.
And for the record, try to use JSON to retrieve your datas, it's way much easier.

How to update the PHP current timestamp using jquery/javascript every second

I am working on the PHP cart timer script using PHP and jQuery/JavaScript.
I am iterating the set-interval function every seconds to get the PHP's current time-stamp.
When the first product is added to the cart, the timer begins before getting timer-stops it prompts the user, whether the user want to continue or cancel.
My code is follows
$(document).ready(function(){
var orderedtime = "echo $_SESSION['ordertime'];";
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}
else{
init();
}
});
var currenttime;
var alerttime;
var extratime;
function cd(){
alerttime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (1 * 60))); ?>"
extratime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (2 * 60))); ?>";
redo();
}
function redo(){
currenttime = "<?php echo date('h:i:s', time()); ?>";
if(alerttime == currenttime) {
//doing something
}
else if(currenttime == extratime){
//doing something
}
else{
cd = setTimeout("redo()",1000);
}
}
function init(){
cd();
}
The currenttime variable only storing the 1st iteration value is not getting updating.
How to solve this issue?
Please kindly help me to solve it.
Thanks in advance.
You're not actually requesting a time from the server in your setTimeout loop.
This line
currenttime = "<?php echo date('h:i:s', time()); ?>";
is set when the page is first generated and not changed again. If you want the time updated you need to send a request to the server. This probably isn't the best way to do it though.
Further to MikeW's excellent but incomplete answer, you need a way to request the time from the server and receive it back in the DOM.
There is only one way to do that: AJAX.
As Mike pointed out, the PHP code that you typed above only runs once: when the page is first generated. After the page has been generated and the document is "ready", you must use AJAX.
Below is a fully-working, copy/pastable example to demonstrate one way this could work.
Note that I had to over-ride the orderedtime variable because I don't know how/when you set that.
HTML/javascript side: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
//var orderedtime = "<?php echo $_SESSION['ordertime']; ?>";
var orderedtime = '';
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}else{
doAjax();
}
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
PHP side: get_the_time.php
<?php
if (isset($_POST['ordertime']) != true) {
$d = date("h:i:s");
}else{
$ot = $_POST['ordertime'];
$d = date('h:i:s', (strtotime($ot) + (1 * 60)));
}
echo $d;
IMPORTANT NOTE:
When using AJAX, the response sent from the server is received inside the success: function, and no where else.
If you later wish to use that data, assigning it into a variable inside the success function will not work. The best way I have found is to stick the received data into an element of some kind (a hidden input field works great for this), and then retrieve it from there when needed.
For example:
<input type="hidden" id="myHiddenField" />
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
$('#myHiddenField').val(myData);
}
});
Then, inside some other javascript function, you can grab that data and assign it to some variable, thus:
var someVar = $('#myHiddenField').val();
Hope this helps, late as it is.
This stackoverflow post has further information/explanation regarding AJAX. Check out the simplified AJAX examples at the bottom.

How to POST data from a field with Javascript

Hi I am trying to make a page which will use the $.post method in Javascript to post the data from a live text field through to another script when the space bar is pressed. I want the data from a the page known as index.php to be posted through another file called save.php. I want to the value of txt_a textfield to to be the value of the post varible text. How would I do this? Below is my code so far...
<html>
<head>
<script type="text/javascript">
function event_a() {
if (event.keyCode == 13) {
$(document).ready(function(){
txt=$document.getElementsByName('txt_a')[0].value;
$.post("save.php",{text:txt});
};
};
}
</script>
</head>
<body>
<form method="POST" name="" action="">
<input name="txt_a" type="text" id="txt_a" onkeypress="event_a()"/>
</form>
</body>
</html>
Thanks
This should get you started:
$(function(){
$('#txt_a').keyup(function(e){
if(e.which === 13) {
$.post('save.php',{text: $(this).val()}, function(data){
//do something with the response
});
}
});
});
And in save.php:
$text = isset($_POST['text']) ? $_POST['text'] : null;
Your javascript function should look more like this:
function event_a(event) { // event needs to be defined as arg to use.
if (event.keyCode == 13) { // ready is used to trigger code when the page is ready, not needed here
var txt=$('txt_a').val(); // assuming you are using jQuery, you can access the value like this
$.post("save.php",{text:txt});
}
}
Why are you passing variable from one file to the another? Use $_SESSION to save and retrieve the set data/variable in multiple pages .

autorepeat a php script

i would like to ask how can i make a php script which echoes the id of the data stored in a database repeat itself after specific time for example after 2 minutes.i don't want to use a cron job or another scheduler.Just php or javascript implemantation.Thanks in advance..
I've done similar with this script. While the user is on the page, it runs scriptToRun.php every 2 minutes.
function changeFeedAddress() {
$.ajax({
type: 'get',
url: 'scriptToRun.php',
success: function(txt) {
// do something with the new RSS feed ID here
}
});
}
setInterval(changeFeedAddress,120000); // 2 MINUTES
Alternate to #JMC Creative (Self-contained for example's sake):
<?php
// check if the $.post below is calling this script
if (isset($_POST['ajax']))
{
// $data = /*Retrieve the id in the database*/;
// ---vvvv---remove---vvvv---
// Example Data for test purposes
$data = rand(1,9999);
// End Example Data
// ---^^^^---remove---^^^^---
// output the new ID to the page so the $.post can see it
echo $data;
exit; // and stop processing
}
?>
<html>
<head>
<title>Demo Update</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
// assign a timeout for this script
var timeout = 2 * 60000; // 2 minutes
// create a function we can call over and over to fetch the ID
function updateDBValue(){
// call this same script and retrieve an "id from the database" (see top of page)
$.post('<?php echo $_SERVER['PHP_SELF']; ?>',{ajax:true},function(data){
// 'data' now contains the new ID. For example's sake, place the value
// in to an input field (as shown below)
$('#db-value').val(data);
// set a timer to re-call this function again
setTimeout(updateDBValue,timeout);
});
}
// call the function initially
updateDBValue();
});
</script>
</head>
<body style="text-align:center;">
<div style="margin: 0 auto;border:1px solid #000;display:block;width:150px;height:50px;">
DB Value:<br />
<input type="text" id="db-value" style="text-align:center;" />
</div>
</body>
</head>
Why not just do this?
<?php
header('refresh: 600; url=http://www.yourhost.com/yourscript.php');
//script here
?>
If your generating your ID at random from within the script...this will work fine. The page will refresh itself every 10 minutes.

Categories