0

At first I want to apologize for the weak English. I would like to use jQuery ajax, but I do not know how to use it. I want to send a data form to addcomment.php without preloading.

<?php
require_once('config/config.php');

if($_POST['sent']){
    $nick = $_POST['nick_ajax'];
    $content = $_POST['content_ajax'];
    $postID = $_POST['id_content_ajax'];

    $sql_comment = $PDO->prepare('insert into `comments` (`nick`,`content`,`postID`) values (:nick,:content,:id)');
    $sql_comment->execute(array(':nick' => $nick, ':content' => $content, ':id' => $postID));
    header('Location: home.php?success');
}
else {
    header('Location: home.php?fail');
    die();
}
?>

Code below is in home.php

<form action="addcomment.php" method="POST">
    <input type="hidden" name="nick" id="nick_ajax" value="'.$_SESSION['user'].'" />
    <input type="text" style="max-width: 1100px;" id="content_ajax" class="form-control" placeholder="Write a comment" name="content" /><br />
    <input type="hidden" name="id" id="id_content_ajax" value="'.$article['id'].'" />
    <input type="submit" id="smb_ajax" class="btn btn-default" style="float:right; margin-top: -15px;"name="sent" value=SEND" />
</form>

Now i have this code

$(document).ready(function(){
$("#smb_ajax").click(function(){
    var user = document.getElementById("nick_ajax").Value;
    var content = document.getElementById("content_ajax").Value;
    var id_cnt = document.getElementById("id_content_ajax").Value;
    var todo = 0;
    $.ajax({
    method: "POST",
    type: 'POST',
    url: "addcomment.php",
    data: { 
        'user': user,
        'content': content,
        'id_cnt':id_cnt
     },
     error: function() {
            alert('Error!');
        }
    })
});

});

MIKE
  • 1
  • 2
  • 1
    [Stack Overflow](https://stackoverflow.com/) is not a free code writing service. You are expected to try to **write the code yourself**. After [doing more research](https://meta.stackoverflow.com/questions/261592) if you have a problem you can **post what you've tried** with a **clear explanation of what isn't working** and providing a [**Minimal, Complete, and Verifiable example**](https://stackoverflow.com/help/mcve). Since you do not know how you can use `jQuery.ajax()` I suggest you take a look at the documentation of [`jQuery.ajax()`](https://api.jquery.com/jquery.ajax/) to get started. – Tom Udding May 15 '17 at 17:20
  • Check this out: [jQuery Ajax POST example with PHP](http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php), this answer explains some basics. – Tom Udding May 15 '17 at 17:25
  • I will check it – MIKE May 15 '17 at 17:36
  • Okay. The code in part works, just do not know how to make the contents of the query to insert into the class – MIKE May 15 '17 at 17:52
  • You'll have to check if the `$_POST` of `nick_ajax` or `content_ajax` or `id_content_ajax` `isset()` (instead of `if($_POST['sent']){`). – Tom Udding May 15 '17 at 19:08

0 Answers0