简体   繁体   中英

value not defined when access php with get method from javascript

I want to send value with get method to my php file. if i set my url like this

http://example.com?id=13

it can run normally, but when my id is like this

http://example.com?id=a0013

a get error in my console log a0013 is not defined. This is my code

<?php
//set $id value
$id=a001;
?>
<script type='text/javascript'> 
function init(){
     ja = new google.maps.Data();
     ja.loadGeoJson('example.php?id='+<?php echo $id; ?>+'');
}
</script>

my example.php

<?php
$id=$_GET['id'];
//another action
?>

You seem to be confusing PHP and JavaScript;
PHP is a server side scripting language
JavaScript is a client side scripting language

The console you mention, is through a browsers inspector tool, and runs off of JavaScript.
If you want to get a request param from this, you could do the following;

// Remove the "?" from the URL and split this down by the ampersand
var requestParams = window.location.search.replace("?", "").split("&");
for (var i in requestParams)
{
    // For each of the request parts, split this by the = to het key and value
    // the console log them to display
    var _params = requestParams[i].split("=");
    console.log("Request Param; " + _params[0] + " = " + _params[1])
}

This will output something such as;

Request Param; id = a0013

You can also use these in PHP;

foreach ($_REQUEST as $key => $value)
{
    print "Request Param; {$key} = {$value}<br />";
}

Which will result in the same thing. If you wanted just the a0013 value; using;

print $_REQUEST['id'];

Will give you this.
Trying to target via the a0013 won't work as that is the value in the data, not the key

NB - I use $_REQUEST in this, there is also $_GET (what you see in the URL bar and what JavaScript has access to via window.location.search) and $_POST which is hidden from the user

FOLLOWING OP EDIT
Add quote marks around your $id=a001; to make it $id='a001';

The reason it works with 13 and not a0013 (or a001) is because 13 is an integer and does not need quotes, because the latter has a string (starts with "a") it MUST have quotes around it (single or double, doesn't matter)

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