简体   繁体   中英

ajax simple js variable to php

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!

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);
?>

$.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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM