Wildan Angga Rahman
Wildan Angga Rahman

Reputation: 53

get value from javascript to php variable

javascript save to php variable

This is a dragable image like Facebook. When I drag it change JavaScript value. The Question is how can I get this value to PHP and when I click the button it should save changes?

This is the code JavaScript:

$(document).ready(function(){
    $('.wrap').imagedrag({
      input: "#output",
      position: "middle",
      attribute: "html"
    });

  });

And this is HTML:

<span id="output"></span>

Also I want to save it into database from the variable of PHP.

Upvotes: 0

Views: 1282

Answers (2)

Orelsanpls
Orelsanpls

Reputation: 23575

Look at jQuery.ajax(). With it you can dynamicaly send the variable value to your php.

Example:

$.ajax({
  type: "POST",
  dataType: "json",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

In your case :

your html

<span id="output"></span>

your javascript

 // Define the click evenement to your button
 $('#output').click(function(){

    // Retrieve the value you want to save
    var valueToSave = ...;

    // Send the value in PHP
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "yourPhpPage.php",
        data: { "value": valueToSave }
    })
    .done(function(msg) {
        alert("Data Saved!");
    });
 });

your PHP

if (($value = filter_input(INPUT_POST, "value", FILTER_UNSAFE_RAW)) !== null)
{
    // You got your value here
}

Upvotes: 2

Jebin
Jebin

Reputation: 742

When you want to communicate to server the client side values, AJAX is the best option we got. Go with AJAX.

On click of save, call an AJAX function to send the values to the server.

$.ajax({
  type: "POST",
  url: "your.php",
  data: { value: $("#output").text() } //here you get data from dom and post it
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

Upvotes: 1

Related Questions