开发者

Getting a value from a variable , send to php to process and add that value to mysql database?

i am new to p开发者_运维知识库hp and mysql.

How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.

var A = "somevalue"

I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.

Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!


You've asked for... a lot. But, this tutorial looks like it could help you.

(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)


I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:

$(function(){
   var hello = "HELLO";

   $.post(
            "posthere.php",
            {varhello: hello},
            function(response){ alert(response); }
   )
});

and "posthere.php" is like this:

$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';

you should then get an alert box saying "HELLO is posted!"


What you need is Ajax. This is an example jQuery to use:

 function sendData(data) {
    $.ajax({ 
        type: 'POST',
        data: data,
        url: "/some/url/which/gets/posts",
        success: function(data) {

        }
    });
 }

This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.

If you have a form:

<form id="theformid">
   <input type="text">
</form>

Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:

$("#theformid").submit(function(){
    sendData($(this).serializeArray());
    return false;
});

If you though want to send just a variable, you need to do it like this:

function sendData(data) {
        $.ajax({ 
            type: 'POST',
            data: {somekey: data},
            url: "/some/url/which/gets/posts",
            success: function(data) {

            }
        });
     }

Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].

Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜