I have the following $ajax code which is meant to send an array with 'title' and 'name' keys populated with data to script.php.
This script creates a new instance of a 2D array, and adds it to an existing multidimensional array with the 'name' as the key.
However the script.php is not reading the $newTitle & $newName being sent from the ajax.
I'm sure it's something easy - I am very new to PHP and jQuery.
javascript:
$.ajax({
data: {title: 'this', name:'testthis'},
url: 'script.php',
method: 'POST',
success: function(msg) {
alert(msg);
}
});
script.php:
//load the existing array into memory
$newLogins =json_decode(unserialize(file_get_contents("config.data")),true);
// get the data from ajax
$newTitle = $_POST["title"];
$newName = $_POST["name"];
//create a new instance of the example array
$addNew = array(
'password' => 'pw',
'title' => $newTitle,
'emails' => array('[email protected]'));
//add the new array to the existing array with 'name' as key
$newLogins[$newName] =$addNew;
//save it
file_put_contents("config.data", serialize(json_encode($newLogins)));
//send it back to ajax
echo json_encode($newLogins);
EDIT
Added HTML file below:
<?php
$thisLogins = json_decode(unserialize(file_get_contents("config.data")),true);
?>
<head>
<script src="../libs/jquery.min.js"></script>
<script src="../libs/jquery-ui.min.js"></script>
</head>
<table id="tableId" border=1>
<thead>
<tr>
<th> Project Login</th>
<th> Project Name</th>
</tr>
</thead>
<tbody>
<?php foreach( $thisLogins as $name => $infos ): ?>
<tr>
<td><?= $name ?></td>
<td><?= $infos["title"]?></td>
<td><button>Delete</button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">
$.ajax({
data: {title: 'this', name:'testthis'},
url: 'script.php',
method: 'POST',
success: function(msg) {
alert(msg);
}
});
</script>
What I'm getting is for output:
"":{"password":"caps","title":null,"emails":["[email protected]"]}}
{"testthis":{"password":"pw","title":"this","emails":["[email protected]"]}}. Does your JS console provide any clues?