简体   繁体   中英

Unable to pass javascript variable to PHP through ajax?

I have searched through a couple of QA here at stackoverflow, none of solutions seemed to help. I am trying to pass input to my PHP file but for some reason the input doesn't get passed from javascript to and it keeps on returning undefined on the console.

my javascript:

$.ajax({
    type:"GET",
    url:"go.php",
    data:{input:input},
    success:function(data){
        console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
    }
});

my php:

<?php
$input = $_GET['input']; //$input here is empty

$keywords= explode(" ",$input);
$link = "https://mp3skull.wtf/search_db.php?q=" . $keywords[0];

for($i = 1; $i < count($keywords); $i++){
    $link .= "+" . $keywords[$i];
}
$link .= "&fckh=1d41a1579f21a921d1008d90dc6246a7";
echo $link; //$keywords is not appended to $link
?>

该代码可能可以从ajax调用之外的console.log正常工作。

hi first you need to declare it as a variable. Second does your variable really have a value? I'll give u sample you can run your code do it something like this

var input = $("#input").val();

$.ajax({
type:"GET",
url:"go.php",
data:{input:input},
success:function(data){
    console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
}
 });

hope this helps

If you have the following Html:

<input type="text" class="field" />
<input type="button" class="button">

You should use the following script:

$(document).ready(function() {
    $('.button').click(function(){
        $.ajax({
            type:"GET",
            url:"go.php",
            data:{'input':$('input.field').val()},
            success:function(data){
                console.log(data);
            }
        });
    });
});

I think it's because when you send data in "data: { input: input } " are defining the variable input with the same name. It should be like that

 var inputValue = $("#idInput").val();
 $.ajax({
    type:"GET",
    url:"go.php",
    data:{input:inputValue},
    success:function(data){
        console.log(data);
    }
});

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