Pass array with ajax and php - php

I need to add a class to some elements based on the time without page reload
I am creating this array when the page loads. I have a start time, an end time and an identifier.
$hrs = array(
array("2013-07-27 21:00", "2013-07-27 22:00", "one"),
array("2013-07-27 22:00", "2013-07-27 23:00", "two"),
array("2013-07-27 23:00", "2013-07-28 00:00", "three"),
);
Then I get the current time and grab the identifier from the array. I tried running this script in a separate file time.php using setInterval but I can't pass $hrs.
<ul>
<li class="one">1</li>
<li class="two">2</li>
<li class="three">3</li>
</ul>
var className = "<?php echo $class_name"; ?>
$(className).addClass("red");
what is the proper way of running this so I won't need to refresh the page? I did something like this but it alerts error:
* Working code below ****
<script>
var hrs = '<?php echo json_encode($hrs); ?>';
//get active class from time.php
$.ajax({
url : 'http://domain.com/time.php',
type : 'POST',
data : { val : hrs },
dataType : 'json',
success : function (result) {
className = result['current_class'];
},
error : function () {
alert("error");
}
})
</script>
time.php
$hrs = json_decode($_POST['val']);
date_default_timezone_set('Europe/Bucharest');
$date = date('Y/m/d H:i');
$test = strtotime($date);
$now = date("Y-m-d H:i", $test);
$class_name = "";
foreach ($_POST['val'] as $h) {
if ($h[0] <= $now and $now <= $h[1]) {
$class_name = $h[2];fa
break;
}
}
$class = array(
'current_class' => ( $class_name ),
);
echo json_encode($class);

If you are sending data using POST
type : 'POST',
You have to access it using $_POST, you are using $_GET.
$_POST['val']

Replace:
var hrs = '<?php echo $hrs; ?>';
To:
var hrs = '<?php echo json_encode($hrs) ?>';

Neither language has any clue about the internals of the other language, your best bet to pass a full array is to encode the AJAX side array to JSON, pass that to your PHP script, and then use json_decode to decode it into a PHP array.
You could also try passing the parameters with square brackets on the end, with the same name as php interprets this as an array. i.e.
file.php?p[]=1&p[]=2&p[]=3&p[]=4&p[]=5
Would result in $_GET['p'] being a 5 item array containing 1 - 5.
The same is also true of post, if you post multiple p[]'s, you will end up with $_POST['p'] as an array of all your elements.

Related

calling to php function in seprate file from ajax not working

I want to get data(time) by comparing userid and date against a post. But for testing I am simply calling php function by ajax. I made a separate php file (myscript.php) in which I made a function and echo something like that.
function my_action(){
echo "dasdasasdaaddad";
$date = $_POST['date'];
echo $date;
return $date;
}
Now when I click on a button I get the date and userid.
global $wp;
$current_url = home_url(add_query_arg(array(),$wp->request));
add_action( 'the_content', 'my_action_javascript' );
function my_action_javascript() {
$current_user = wp_get_current_user();
$uid = $current_user->ID;
?>
<script type="text/javascript" >
jQuery(".date").click(function(){
clicked = this;
var dates= jQuery(clicked).closest("ul").find(".getdate").val();
var item= jQuery(this).closest("li.lia");
var date = jQuery(item).find("input.getdate").val();
//var dates = jQuery(item).find("input.getdate").val();
alert(date);
jQuery.ajax({
type:"post",
url: "<?php $current_url;?>/myscript.php",
data : {
'action': 'my_action',
'date': date,
'userid': "<?php echo $uid?>"
},
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
success: function(data) {
successmessage = 'Data was succesfully captured';
$("label#successmessage").text(successmessage);
},
error: function(data) {
successmessage = 'Error';
$("label#successmessage").text(successmessage);
},
});
});
</script>
<?php
}
I gave the URL of that file in ajax url. Now it should print data from myscript.php file but I am getting this result in response from ajax.
Got this from the server:0
I have checked the network also and it seems good to me.
ajax is getting userid and date but response is 0.Don't know why?
on
myscript.php page remove function my_action().. because you are not calling this.
if you want to call this before that use my_function();
<?php
my_function();
function my_action(){
echo "dasdasasdaaddad";
$date = $_POST['date'];
echo $date;
return $date;
}
?>
You are not calling your my_action function in myscript.php file. Call your function you will get the your desired result.
<?php
function my_action(){
echo "dasdasasdaaddad";
$date = $_POST['date'];
echo $date;
return $date;
}
my_action();
?>

Get url variable from AJAX in PHP

I've looked at a couple of related topics here on Stackoverflow such as this answer, but I can't seem to get this one correct – it could be something particular in my code, but I don't think that should be the case, thus I'm seeking your advice.
My goal is to pass index.php?key=123testID through the client.js script below to my update-check.php in order to long-poll the txt file with the corresponding name (in this example 123testID.txt). If there's an other way for update-checker to grab the variable, that is also acceptable.
I currently have working functionality for long-polling the .txt data – I simply want to add the functionality to dynamically load the txt file with the same name as the URL variable.
At the moment my code looks like this:
client.js
function getContent(timestamp)
{
var queryString = {'timestamp' : timestamp};
$.ajax(
{
type: 'GET',
url: 'update-check.php',
data: queryString,
success: function(data){
// put result data into "obj"
var obj = jQuery.parseJSON(data);
// put the data_from_file into #response
$('#response').html(obj.data_from_file);
// call the function again, this time with the timestamp we just got from server.php
getContent(obj.timestamp);
}
}
);
}
// initialize jQuery
$(function() {
getContent();
});
update-check.php
<?php
// set php runtime to unlimited
set_time_limit(0);
// how can I load a variable insead of a static txt file?
$data_source_file = "stories/123testID.txt";
// main loop
while (true) {
// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : null;
clearstatcache();
// get timestamp of when file has been changed the last time
$last_change_in_data_file = filemtime($data_source_file);
if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {
$data = file_get_contents($data_source_file);
$result = array(
'data_from_file' => $data,
'timestamp' => $last_change_in_data_file
);
// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
echo $json;
// leave this loop step
break;
} else {
sleep( 1 );
continue;
}}?>

ajax return single variable and an array variable

I have a comment form that requests a newtimestamp and newcomment variables. The newtimestamp variable is a single variable and the newcomment variable is an array returned from a foreach loop.
ajaxrequest.php:
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp = $now;
$newcomment = "<div class=post>$var1</div>";
echo json_encode(array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment));
}
I then use ajax to prepend the new comment's and set the newtimestamp on a hidden input field.
ajax:
<script>
$(document).ready(function(){
$('#commentform').on('submit',function(e) {
$.ajax({
url:'ajaxrequest.php',
data:$(this).serialize(),
type:'POST',
dataType: 'JSON',
success:function(data, response){
$("#posts").fadeOut(300);
$("#posts").prepend(data.newcomment);
$("#time").val(data.newtimestamp);
$("#posts").fadeIn(500);
$('html, body').animate({ scrollTop: $('#posts').offset().top - 100 }, 'fast');
console.log(data);
},
error:function(data){
console.log(data);
}
});
e.preventDefault();
return false;
});
});
The above method gives me a success message in console, the prepend works but only shows 1 result everytime when it should show all results from the last timestamp. The prepend and setting the value of the hidden input field do not work if the user posts a second, third etc comment.
console:
Object {newtimestamp: "2014-11-19 07:59:48", newcomment: "<div>a new comment</div> 1"}
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
I need to return the newtimestamp variable as a single variable (not an array) and set this on a hidden input field value, and I need to return the newcomment variable as an array that can be prepended to a div.
How can I do this?
Change your php file. I am not sure this is you are expecting.
ajaxrequest.php:
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp[] = $now;
$newcomment[] = "<div class=post>$var1</div>";
}
echo json_encode(array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment));
Rewrite your php code like this
$data = array();
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp = $now;
$newcomment = "<div class=post>$var1</div>";
$data['data'][] = array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment);
}
echo json_encode($data);
now the JSON response will look something like
{"data" : [{"newtimestamp" : 72345654,"newcomment" : "comment data"},{"newtimestamp" : 72345654,"newcomment" : "comment data"}]}
loop through array of objects using jQuery each. The final code will look something like this.
$.each($response.data,function(index,value){
$("#posts").prepend(value.newcomment);
$("#time").val(value.newtimestamp);
})
NOTE: either send application/json header (so that the response will be parsed and converted to an js object by default) or parse it after receiving. This action should happen before the each loop
That's because you are echo multiple JSON string. You need to echo a single JSON string with all data.
Try something like the code below, this worked for me. You only need to fit this into your jQuery and PHP code.
<?php
$jsonArray = array();
$array2 = array(array('var'=>1),array('var'=>2));
foreach ($array2 as $print2)
{
$var1 = $print2['var'];
$newtimestamp = time();
$newcomment = "<div class=post>$var1</div>";
$jsonArray[] = array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment);
}
print_r($jsonArray);
$data = json_encode($jsonArray);
?>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
var data = jQuery.parseJSON('<?=$data?>');
$.each(data, function(item, value){
console.log(value['newtimestamp']);
});
</script>

loop through JSON array to generate Multiple Countdown timer?

Currently I'm using a jquery count down timer plugin (This Plugin) to generate the Counter through Ajax call .
for now its working fine with no problem for a single call but when i tried to generate a multiple counter whole looping through Json array it doesn't work .
JS
$(document).ready(function(){
$.ajax({
url: 'time.php',
async: false,
dataType: 'json',
success: function(data) {
var response = data ;
$.each(response, function(i, item) {
var time = new Date(item.time) ;
$('.timer').append('<li id='+ i +'></li>');
$('#'+i).countdown({
until: time,
compact: true,
format: 'HMS'
});
});
},
error: function(http, message, exc) {
time = new Date();
}
}
);
})
PHP
<?php
$now = time() + 9999;
$now1 = time()+ 5000;
$data = array($now,$now1);
$json = array();
foreach ($data as $value){
$json[] = array(
'time' => $value
);
}
echo json_encode($json);
?>
this is the Json output
[{"time":1365712506},{"time":1365707507}]
When I tried to show up the result of loop without setting the time it works fine and showing the right result .
But after setting the time and setting the count down timer its shows 00 instead of the counter
00:00:00
00:00:00
You need to multiply the dates with 1000
var time = new Date(item.time*1000);
I also changed the class to ID and added a letter to the iDs of the LIs for non-html5 browsers
DEMO
$(function(){
var response = [{"time":1365712506},{"time":1365707507}];
$.each(response, function(i, item) {
var time = new Date(item.time*1000) ;
$('#timer').append('<li id="t'+ i +'"></li>');
$('#t'+i).countdown({
until: time,
compact: true,
format: 'HMS'
});
});
});
You need to check your dates, I dont believe that they are in the furture.
console.log(time);
Fiddle

how to show the "content" from a php variable with jquery? (it shows me the "name" itself, not the content in it)

Hmm... i'm trying to use a php variable in jquery, in my edit.php : i'd like to use jquery to show the php variable, using the "rel" attribute, but it gives me the "name" of the variable, not its content.
i'm using php to retrieve the text from the xml file : (edit : one click on submit does not update the text, but 2 clicks do)
/* READ */
$dom = new DomDocument();
$dom->load('edition.xml');
$_home = $dom->getElementsByTagName('home')->item(0);
$home = $_home->firstChild->nodeValue;
$_rhizo = $dom->getElementsByTagName('rhizo')->item(0);
$rhizo = $_rhizo->firstChild->nodeValue;
$_disco = $dom->getElementsByTagName('disco')->item(0);
$disco = $_disco->firstChild->nodeValue;
/* array */
$rels = array('home' => $home,
'rhizo' =>$rhizo,
'disco' =>$disco);
echo '<script>var rels = ' . json_encode($rels) . '</script>';
/* WRITE */
if ( isset($_POST['cache']) ){
if ( isset($_POST['home']) ){
$home = stripslashes($_POST['home']);
$_home->firstChild->nodeValue = $home;
}
if ( isset($_POST['rhizo']) ){
$rhizo = stripslashes($_POST['rhizo']);
$_rhizo->firstChild->nodeValue = $rhizo;
}
if ( isset($_POST['disco']) ){
$disco = stripslashes($_POST['disco']);
$_disco->firstChild->nodeValue = $disco;
}
$dom->save('edition.xml');
}
?>
(the text is simply shown in a textarea, where i just put the php variable)
then i use jquery to show the content from the php variable : (edit with the array object : )
$('#left a').bind('click', function(){
var text_from_link = $(this).text();
var rel = $(this).attr('rel');
$('#textarea1').attr('name', rel);
$('#textarea1').text(rels[''+rel+'']);//output is "$home" for example, which will retrieve the "home" part from the xml
return false;
})
And this works if i double click on submit, if i just click once, the text is not updated... i'm a bit confused with that
Thanks for your help
You need to do an ajax call to do that.
Or you can write a javascript object in your HTML:
$rels = array('rel23' => 'Hello world');
echo '<script>var rels = ' . json_encode($rels) . '</script>';
Then access them with javascript:
alert(rels.rel23);
like mentioned you will need to use ajax for this.. jQuery provides ajax and it appears you are already using it soooo....
if(isset($_POST["getHome"])) {
$dom = new DomDocument();
$dom->load('edition.xml');
$_home = $dom->getElementsByTagName('home')->item(0);
$home = $_home->firstChild->nodeValue;
echo $home; // anything returned by this page will become 'data'
}
and
$(function(){
$('a').bind('click', function(){
$.post("mypage.php",{getHome : 1}, function(data) {
alert(data);
});
})
});
ok assuming you have an array in your php
if(isset($_POST["varName"])) { // will check if the POST variable with the name 'varName' is set
$arr = array(1,2,3); // your array
echo json_encode($arr); // encode your output as a json string
}
then in your javascript
$(function(){
$('a').bind('click', function(){
$.post("mypage.php",{varName: 1}, function(data) { // the value of 1 is trivial. and is likely not needed, you can post to a page without passing any values. In which case the use if isset() in php is not required.
var json_obj = JSON.parse(data);
console.log(json_obj); // assuming you have a console at your disposal.
});
})
});

Categories