Ich benutze AJAX, um ein Chat-System für ein Twitch-Video zu erstellen. Der Punkt besteht darin, die übermittelten Nachrichten dynamisch anzuzeigen, ohne dass die Seite neu geladen wird, und es funktioniert. Die Nachrichten werden jedoch nicht an meine Datenbank gesendet, und bei der Seitenaktualisierung sind die übermittelten Nachrichten nicht mehr vorhanden. Diejenigen, die ich manuell in die DB eingefügt habe, werden angezeigt. Hier ist mein Code:Probleme mit AJAX beim Einfügen von Daten in DB
Dashboard.twig:
<script>
$("#forminput").submit(function(e){
var url = "dashboard";
$.ajax({
type: "POST",
url: url,
data: $("#forminput").serialize(),
dataType: 'json', //what is returned
success : function(data)
{
$("#table").append("<tr><td>" + data.name + "</td><td>" + data.comment + "</td></tr>");
}
});
e.preventDefault();
});
DisplayCommentsModel: -
private $name;
private $comment;
public function printComments()
{
$app = \Yee\Yee::getInstance();
$cols = Array ("name", "comment");
$comments = $app->db['db1']->get("comments", null, $cols);
if ($app->db['db1']->count > 0)
{
return $comments;
}
}
AddCommentsModel
private $name;
private $comment;
public function __construct($name, $comment)
{
$this->name = $name;
$this->comment = $comment;
}
public function comment()
{
if ($this->validateEmptyFields() == false)
{
return false;
}
if ($this->validateFilledFields() == false)
{
return false;
}
return true;
}
public function validateEmptyFields()
{
if(empty($this->name) || empty($this->comment))
{
return false;
}
else
{
return true;
}
}
public function validateFilledFields()
{
$nameLenght = strlen($this->name);
$commentLenght = strlen($this->comment);
if($nameLenght < 2 && $commentLenght < 2)
{
return false;
}
return true;
}
public function insertCommentsInDb()
{
$app = \Yee\Yee::getInstance();
$data = array(
"name" => $this->name,
"comment" => $this->comment
);
$app->db['db1']->insert('comments', $data);
}
CommentsController:
public function index()
{
$app = $this->getYee();
$newDisplayCommentsModel = new DisplayCommentsModel();
$comments = $newDisplayCommentsModel->printComments();
$data = array(
'comments' => $comments
);
$app->render('dashboard/dashboard.twig', $data);
}
/**
* @Route('/dashboard')
* @Name('dashboard.post')
* @Method('POST')
*/
public function post()
{
$app = $this->getYee();
$name = $app->request->post('name');
$comment = $app->request->post('comment');
//add to database
$data = array(
'name' => $name,
'comment' => $comment
);
echo json_encode($data);
}
Wie erhalten Sie '$ (" # forminput "). Serialize()' Werte in 'php' –
Konnten Sie genauer sein? Was meinst du damit, die Werte in PHP zu bekommen? – CoffeeGuy
@MayankPandeyz hat gerade verstanden, was du meinst. Es ist dank meiner Kommentare Controller – CoffeeGuy