0

I want to get day and month from a client's computer, and then pass it to PHP in two separate variables, which would result in something like this:

$day_num = 11;
$month_num = 12;

I need JavaScript function and PHP function to be separate files, and I need to pass the value not in the URL.

I would be grateful for a bit of help from an expert!

2 Answers 2

3

Javascript:

If you are using jQuery gettting it back to the server is super easy (if you do it without, see: How to make an AJAX call without jQuery?):

<script language="javascript">
var date = new Date(),
    month = date.getMonth(),
    day = date.getDate();

    $.post('path-to-php.php', { day: day, month: month});  
</script>

PHP:

<?php
    var_dump($_POST['day']);
    var_dump($_POST['month']);
?>

Edit:

path-to-php.php is the filename of your php file. It can be absolute or relative, depending on your application. If you wanted to post it to the same file, you could use this instead of path-to-php.php: <?php echo $_SERVER['PHP_SELF'];?>

Sign up to request clarification or add additional context in comments.

5 Comments

What would be the way to do it without relying on jQuery?
Looks like jQuery is a better option. Forgive me a novice question: should I include jQuery IN the JS file - or somewhere else?
There really isn't a clean or easy way to include jQuery in a javascript file. It is doable, though. You include jQuery in the <head></head> tag of the page, like this: <script language="javascript" src="ajax.googleapis.com/ajax/libs/jquery/1.8.3/…> - this example is using Google's CDN version, so you wouldn't have to host it yourself.
Happy to help!! Please remember to mark as an answer if this answered your question.
A couple of quick questions: how do I determine the path-to-php? And what if I needed to pass it within the same page, not between two separate ones?
1

With javascript:

function executeAjax()  { 
var date = new Date(),
var month = date.getMonth(),
var day = date.getDate();

var url="daymonth.php?month="+month+"&day="+day;
var objX=new XMLHttpRequest();
objX.open("GET",url,false);
objX.send(null);
var response=objX.responseText;

}

daymonth.php

<?php
    $day=$_GET['day'];
    $month=$_GET['month'];
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.