dahui dahui - 1 month ago 9
Ajax Question

Using AJAX/JQuery to post form data to a php script

I pieced this together from other answers on this site and various tutorials. Not sure why it isn't working, and I've not had any luck with other methods.

Here is parts of my page html:



<form id="newMovie" >
Title:<input type='text' id='title'/>
Genres:<input type='text' id='genres'/>
Cast:<input type='text' id='cast'/>
Director:<input type='text' id='director'/>
Metascore:<input type='text' id='metascore'/>
<input type="button" value="Send" id="theButton"/>
</form>
...
<table>
<tr>
<td id="tr1td1">
<p>..</p>
</td>
...


On "theButton" click, I want to grab the values from the inputs in the form and POST it to a php script, here is my AJAX:

<script>
$(document).ready(function(){
$("#theButton").click(function(){

var titleData = $('#title');
alert(titleData);


I've got an alert here for debugging, this alert doesn't even pop, so it seems to be failing before we even get here?

var genresData = $('#genres');
var castData = $('#cast');
var directorData = $('#director');
var metascoreData = $('#metascore');

var dataIn = {
title : titleData.val();
genres : genreData.val();
cast : castData.val();
director : directorData.val();
metascore : metascoreData.val();
}
var dataOut = $('#tr1td1');
$.post("..../insert.php", dataIn, function(data, status) {
dataOut.html(data);
});
});
});
</script>


In the PHP script, I wil try and grab the values like so:

$titleData=$_POST['title'];
$genresData=$_POST['genres'];
$castData=$_POST['cast'];
$directorData=$_POST['director'];
$metascoreData=$_POST['metascore'];

Answer

Your comment points to the error:

Uncaught Syntax Error: unexpected ; at line 27, which is the first line in the "dataIn" brackets

You have errant semi-colons in your object construction:

var dataIn = {
    title : titleData.val();
    genres : genreData.val();
    cast : castData.val();
    director : directorData.val();
    metascore : metascoreData.val();
}

Should be:

var dataIn = {
    title : titleData.val(),
    genres : genreData.val(),
    cast : castData.val(),
    director : directorData.val(),
    metascore : metascoreData.val()
};

Object literals are a list of comma-separated properties as a single overall line of code, not individual lines of code.

Comments