Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't Save Backbone JS Model to MySQL Database
    primarykey
    data
    text
    <p>I'm a beginner learning Backbone JS, and I'm having trouble saving my first test model to a MySQL database. Although the AJAX request is being sent from Backbone with the correct POST payload (according to the browser inspector), my PHP script on the backend seems to be receiving an empty array. </p> <p>Here's the code for the model: </p> <pre><code>var UserModel = Backbone.Model.extend({ urlRoot: 'backboneUserBackend.php', defaults: { name: '', email: '' } }); var user = new UserModel(), userDetails = {name: 'Jim Smith', email: 'jimsmith@example.com'}; user.save(userDetails, {success: function(user){ console.log(user); } }); </code></pre> <p>And here is my PHP script: </p> <pre><code>if (!empty($_POST)) { // @todo: replace deprecated mysql method w/ PDO connection mysql_connect("localhost", "user", "password"); mysql_select_db("mydatabase"); if (mysql_errno()) { exit('DB connect error: '.mysql_error()); } $name = mysql_real_escape_string($_POST['name']); $email = mysql_real_escape_string($_POST['email']); $query = sprintf("INSERT INTO users VALUES (NULL, '%s', '%s')", $name, $email); if (mysql_query($query)) { echo mysql_insert_id(); } else { exit('Error inserting record: '.mysql_error()); } } </code></pre> <p>To test whether or not my PHP script was actually being executed via the AJAX request, I added this test to the top: </p> <pre><code>$fh = fopen("mytest_".time().".txt", "w"); ob_start(); print_r($_POST); $payload = ob_get_clean(); fwrite($fh, $payload); fclose($fh); </code></pre> <p>Whenever my Backbone model is saved, a new file is created, but the file contains an empty array. Any thoughts?</p> <p>Note: I'm using Chrome. Also, I know that I should be using a simple root URL, such as "/user," in my Backbone model... I'm just using the "backboneUserBackend.php" script temporarily, for testing purposes. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload