将变量从Javascript传递到PHP并返回

将变量从Javascript传递到PHP并返回

问题描述:

The console ends up writing back

Uncaught ReferenceError: provhtml is not defined

Also, when I change up my Javascript to be the code right below, the console ends up just writing " <?= $provhtml ?>"

var provnum = "<?= $provhtml ?>";
console.log(provnum);

I'm not exactly sure what the problem is. I want $provhtml to be written inside the console when a user clicks a button named otherlistbut (I'm also not sure if there needs to be the d.preventDefault(); Here is my prov.php

<?php    
$phonenum = $_POST["phonenum"];
$provhtml = file_get_contents('http://api.data24-7.com/v/2.0?user=USERNAME&pass=PASSWORD&api=C&p1=1' . $phonenum);   
 ?>

Here are my scripts in my index.html

   $('button[name="otherlistbut"]').click(function(d) {
        lookupProvider(d);

    });
});

/************ FUNCTIONS ******************/

function lookupProvider(d) {
    d.preventDefault();
    var phonenum = $('input[name="phonenum"]').val();
    $.ajax({
        type: 'POST',
        data: {
            phonenum: phonenum
        },
        url: 'prov.php',
        success: function(data) {
            var provnum = $(provhtml);
            console.log(provnum);
        },
        error: function(xhr, err) {
            console.log("readyState: " + xhr.readyState + "
status: " + xhr.status);
            console.log("responseText: " + xhr.responseText);
        }
    });
}

In your prov.php file

<?php    
$phonenum = $_POST["phonenum"];
$provhtml = file_get_contents('http://api.data24-7.com/v/2.0?user=USERNAME&pass=PASSWORD&api=C&p1=1' . $phonenum);   
echo json_encode( array( "phonenum" => $phonenum,"provhtml"=>$provhtml)); //You should be returning the values to your ajax function
 ?>

In your index.html

function lookupProvider(d) {
    d.preventDefault();
    var phonenum = $('input[name="phonenum"]').val();
    $.ajax({
        type: 'POST',
        data: {
            phonenum: phonenum
        },
        url: 'prov.php',
        success: function(data) { //Receives the data from the php code
            var provnum = data.phonenum;
            console.log(provnum);
        },
        error: function(xhr, err) {
            console.log("readyState: " + xhr.readyState + "
status: " + xhr.status);
            console.log("responseText: " + xhr.responseText);
        }
    });
}