简体   繁体   中英

How to put jQuery variable to a PHP variable

I am trying to give a jQuery variable to a PHP variable when document is ready. What I have is a list with all sort of values with different links, which I get by an external website via cURL. With jQuery I am getting the value's by the href link. So what I want is when document is ready with loading, then it should give the jQuery variable to a php variable and echo it.

What I have so far:

//Javascript.js
$(document).ready(function() {
var value = $("a[href='index.php?p=trading&m=42&b=BTC']:eq(3)").text();
 $.ajax({
    url: "index.php",
    type: "get",
    data: value,
    success: function(){
        alert("success");
        alert(value);
    },
    error:function(){
        alert("failure");
    }
});

alert(value);   
});

The output of value = 55.0

<a href="index.php?p=trading&m=42&b=BTC">55.0</a> //from cURL page
<!-- index.php -->
<?php
$a = $_GET['value'];
if($_GET['value'] == "")
{
    echo("empty");
}
else {
    echo($a);
}
?>

The GET/POST is success, but it doesn't show up at the php page. Hope anyone got a solution for this.

Change this:

data: value,
success: function(){
    alert("success");
    alert(value);
},

to this:

data: "value=" + value,
success: function(response){
    alert("success");
    alert(response);
},

You need to capture the response(echo) from the index.php file and alert that.

ADDITIONAL INFO: After seeing the whole index.php file

Put this block at the top of your PHP file, not the bottom:

<?php
    if($_POST['value'] == "")
    {
        echo "empty";
    }
    else {
        echo $_POST['value'] ;
    }
    exit;
?>

And add the exit; at the end like above.

When you call this php file via ajax, you do not want to execute the rest of the php file, only the part in the if $_GET block. So this needs to be at the top of the file with exit after it so the rest doesn't get executed when it is a $_GET request.

$(document).ready(function() {
var value = $("a[href='index.php?p=trading&m=42&b=BTC']:eq(3)").text();
 $.ajax({
    url: "index.php",
    type: "post",
    data: "value="+value,
    success: function(result){
        alert("success");
        alert(result);
    },
    error:function(){
        alert("failure");
    }
});

alert(result); 
});


index.php

$a = $_POST['value'];
if($_POST['value'] == "")
{
    echo "empty";
}
else {
    echo $a ;
}

You can get the desired result by changing data:value to data:{"value":value}

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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