将表单输入存储在javascript变量中,然后将其值传递给php变量而不提交表单? [重复]

将表单输入存储在javascript变量中,然后将其值传递给php变量而不提交表单?  [重复]

问题描述:

This question already has an answer here:

what I want to do is whenever a user fills his address in text field input I want to grab it on blur with javascript which I am able to do .. now how to pass this variable in a php variable so that i can use it for some operations ? the javascript file is called inside php file ..

</div>

此问题已经存在 这里有一个答案: p>

  • 如何将JavaScript变量传递给PHP? 14 answers span> li> ul> div>

    我想要做的是每当用户在文本字段中填写他的地址时 输入我想用javascript来抓住它我可以做的..现在如何在php变量中传递这个变量,以便我可以用它进行一些操作? javascript文件在php文件中调用.. p> div>

Pull the data from the form elements first

var dataObject = {};
// #search is the form with search params
$.each($('#form name').serializeArray(), function(i, field) {
dataObject[field.name] = field.value;
});

then POST the data to the php

    $.ajax({  
         type: "POST",  
         url: "./api.php",  
        data: dataObject,
        success: function(dataout) {
            //dataout is what is returned from php
            //process it how you like from here
        }
    });

in php do something with POST data

<?php
   $element1 = $_POST["form_element_name1"];
   $element2 = $_POST["form_element_name2"];
   ...do something
   print $result;
?>

the printed result is output to dataout in the ajax function.. process from there

PHP is a server-side language so after the page is called from the client's computer, there is no more PHP on the page but only converted to HTML. If you want to do something with the input in PHP on blur then you have to POST (easily done with jQuery) the data to a new instance of a PHP file so it can be compiled on the server.

Page with the form

$.post('name_of_php_file_to_send_data_to.php', {name: value}/* <-- data to pass to the PHP file*/,function(output) {
    // do something with the returned output of the PHP file
});