Maivinam
Maivinam

Reputation: 33

How to send code to database with AJAX

I tried to save a HTML and also Javascript codes to Database by Ajax, but don't know how to optimize this way. I can't just write all codes like Strings for the variable. Do you have another idea to make it simpler ?

<script type="text/javascript">
  $(document).ready(function(){
    $("#add_code").click(function(){
        var addCode = "Here is Javascript code";
        $.get("includes/dashboard/addcode.php", {addCode:addCode
        },function(data){
        });
    });
  });
</script>

And this is the addcode.php

<?php
 require('database/connect_database.php');
  session_start();
   $addCode = $_GET['addCode']; 
   $codename = $_SESSION['codename'];
   $stmt = $pdo->prepare("INSERT INTO code (codename, w_code) VALUES ('$codename','$addCode')");
   $stmt->execute();
?>

Upvotes: 1

Views: 278

Answers (1)

godot
godot

Reputation: 3545

I'd use jquery ajax with post method:

<script type="text/javascript">
  $(document).ready(function(){
    $("#add_code").click(function(){

        var addCode = "Here is Javascript code";
        $.ajax({
            url: 'includes/dashboard/addcode.php',
            type: 'post',
            data: {addCode: addCode},
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error.responseCode);
            }
        });

    });
  });
</script>

and change code also on php-side:

<?php
 require('database/connect_database.php');
  session_start();
   $addCode = $_POST['addCode']; 
   $codename = $_SESSION['codename'];
   $stmt = $pdo->prepare("INSERT INTO code (codename, w_code) VALUES ('$codename','$addCode')");
   $stmt->execute();
?>

also see this answer:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

you add this function to your javascript code and pass get parameters in the url:

$(document).ready(function(){ $("#add_code").click(function(){

    var addCode = "Here is Javascript code";
    console.log(httpGet('includes/dashboard/addcode.php?addCode='+addCode));

});

});

Upvotes: 1

Related Questions