David G
David G

Reputation: 6871

ajax error date undefined when firing

I have a form like so:

<form method="post" action="functions/updateWeek.php">
    <label for="dateStart">View From</label>
    <input type="date" name="dateStart" required>
    <label for="dateEnd">Until</label>
    <input type="date" name="dateEnd" required>
    <input type="submit" id="submitWeek" value="Go"/>
</form>

And some javascript like this:

$(document).ready(function() {
     //if submit button is clicked
    $('#submitWeek').click(function () {              
        //Get the data from the field
        var dateStart = $('date[name=dateStart]');
        var dateEnd = $('date[name=dateEnd]');
        //organize the data properly
        var data = 'dateStart='  + dateStart.val() + '&dateEnd=' + dateEnd.val();
        //start the ajax
        $.ajax({
            //this is the php file that processes the data and send mail
            url: "functions/updateWeek.php", 
            //GET method is used
            type: "POST",
            //pass the data         
            data: data,     
            //Do not cache the page
            cache: false,
            success: function() {
             alert("done");
            }
        });     
        //cancel the submit button default behaviours
        return false;
    }); 
}); 

Which sends to this php file:

//Start sessions
session_start();
//include config file
include_once 'config.php';
include_once 'accountFunctions.php';
//get start date from form
$dateStart = $_POST['dateStart'];
//get end date from form
$dateEnd = $_POST['dateEnd'];
//collect the start week
$startWeek = getStartWeek($dateStart);
//collect the end week
$endWeek = getEndWeek($dateEnd);

I've not included the rest of the function.

The problem I have however, is upon inspection (because the query doesn't work) it appears both dateStart and dateEnd in my post method are "undefined".

I haven't the foggiest as to why. Am I missing something obvious? I suspect it must be an issue with my jquery selectors, but if so, what could it be?

Upvotes: 0

Views: 206

Answers (3)

SomeShinyObject
SomeShinyObject

Reputation: 7811

In jQuery, the selector for input names is as such (in your case):

var dateStart = $('input[name="dateStart"]');
var dateEnd = $('input[name="dateEnd"]');

This also works for any attribute in an element:

jQuery prefix selector docs

SO question

Fiddle Example

Upvotes: 4

Hkachhia
Hkachhia

Reputation: 4539

Try this code

var dateStart = $('input[name="dateStart"]').val();
var dateEnd = $('input[name="dateEnd"]').val();

var data = 'dateStart='  + dateStart+ '&dateEnd=' + dateEnd;

Upvotes: 0

Edwin Alex
Edwin Alex

Reputation: 5108

You have to use selectors like this,

var dateStart = $('input[name="dateStart"]');
var dateEnd = $('input[name="dateEnd"]');

Upvotes: 5

Related Questions