0

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.

1
  • Can be done with ajax call, you can pass any js value to php file. Commented Jun 22, 2014 at 17:22

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your response, this case must in form right? inside the value of input? and how I set the value to input?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.