1

I've seen many js var to php question asked but none seem to help me as its either to complicated or doesn't fit my requirements. I'm looking to transfer three variable in js called title, body and author. Body being a very long string therefor I cannot place in URL. I am looking for the simplest Ajax code possible that follows this: js var already defined -> ajax -> php var Here is the code I've got so far:

<script>
var title;
var body;
var author;
function post(){
    title = document.getElementById("title").value;
    body = document.getElementById("body").value;
    author = document.getElementById("author").value;
}
    //Insert ajax code here
<?php


$title;
$body;
$author;
$post = "INSERT INTO post (title, body, author) VALUES ($title,$body,$author)";
$sql = mysqli_query($conn,$post);
?>
</script>

Thank you in advance!

Yoan Poulmarc'k
  • 33
  • 2
  • 11

2 Answers2

3

You can do this way simple

<script>
var title = document.getElementById("title").value;
var body = document.getElementById("body").value;
var author = document.getElementById("author").value;

$.ajax({
    type: 'POST',
    url: 'insert.php',                
    data: {title:title,body:body,author:author},
 success: function(data) {

 }  
})
</script>

inside, insert.php file

<?php
$title = $_POST['title'];
$body = $_POST['body'];
$author = $_POST['author'];
$post = "INSERT INTO post (title, body, author) VALUES ($title,$body,$author)";
$sql = mysqli_query($conn,$post);
?>
  • Thanks to this my JS function post() works but the Ajax doesn't seem to work as it doesn't update the database. I've tried to put a JS alert inside insert.php to test but it doesn't activate. Thank you for help! – Yoan Poulmarc'k Nov 25 '16 at 04:58
  • you can't put a JS alert inside insert.php, you can print $_POST value, it will get your values. your ajax – Nidhi Barhate Nov 25 '16 at 05:09
  • sorry, it is unanswered, you can't put a JS alert inside insert.php,your ajax is not working, I think your script not added, please add it "" and you can print $_POST value, it will get your values. I hope it help. – Nidhi Barhate Nov 25 '16 at 05:11
  • Sorry I explained this incorrectly. I put an alert inside a script in the insert.php and have put an alert in the function(data) in ajaz which activetes so I do not know what is wrong with code> It would probably be connection between both documents. Thank you! – Yoan Poulmarc'k Nov 25 '16 at 07:26
  • @NidhiBarhate Gud Keep it up – Chetan Panchal Nov 28 '16 at 06:11
0

$.post('url', {title: title, body: body, author: author})

Then use $_POST global variable to get the data you wanted.

$title = $_POST['title'];
$body = $_POST['body'];
$author = $_POST['author'];

More info on ajax post shorthand here:
https://api.jquery.com/jquery.post/

Aron
  • 129
  • 1
  • 3
  • 13