简体   繁体   English

从javascript获取值到php变量

[英]get value from javascript to php variable

javascript保存到php变量

This is a dragable image like Facebook.这是一个像 Facebook 一样的可拖动图像。 When I drag it change JavaScript value.当我拖动它时更改 JavaScript 值。 The Question is how can I get this value to PHP and when I click the button it should save changes?问题是如何将这个值传递给 PHP,当我单击按钮时,它应该保存更改吗?

This is the code JavaScript:这是 JavaScript 代码:

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

  });

And this is HTML:这是 HTML:

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

Also I want to save it into database from the variable of PHP.另外我想将它从 PHP 的变量保存到数据库中。

Look at jQuery.ajax() .看看jQuery.ajax() With it you can dynamicaly send the variable value to your php.有了它,您可以动态地将变量值发送到您的 php.ini 文件。

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你的html

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

your javascript你的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你的 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.当您想与服务器通信客户端值时,AJAX 是我们得到的最佳选择。 Go with AJAX.使用 AJAX。

On click of save, call an AJAX function to send the values to the server.单击保存,调用 AJAX 函数将值发送到服务器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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