简体   繁体   中英

get value from javascript to php variable

javascript保存到php变量

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.

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
}

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

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