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!
-
"//Insert ajax code here" creates so many questions, it should not be there....Rayon– Rayon2016年11月24日 07:15:22 +00:00Commented Nov 24, 2016 at 7:15
-
Add your ajax code here, What you tried ?Elby– Elby2016年11月24日 07:17:13 +00:00Commented Nov 24, 2016 at 7:17
-
Ajax code cannot be under PHP.Bhavik Shah– Bhavik Shah2016年11月24日 07:17:46 +00:00Commented Nov 24, 2016 at 7:17
-
Check this answer.Bhavik Shah– Bhavik Shah2016年11月24日 07:20:19 +00:00Commented Nov 24, 2016 at 7:20
-
@Cpt0Teemo Do you want variable in same file ?Jalpa– Jalpa2016年11月24日 07:22:59 +00:00Commented Nov 24, 2016 at 7:22
2 Answers 2
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);
?>
5 Comments
$.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/