简体   繁体   中英

error javascript method is not defined calling using php

I am unable to make a javascript function call through php on click of a button. I am placing the method before calling it in my php code. However, i get the error Uncaught ReferenceError: pouchITSave is not defined on the console. what is strange about the error is that on the console it says line number profile.html:1. This is the previous file that make a call to the searchcode.php. I am not sure what is wrong here why would it say line number of a previous file when in reality the method is present in searchcode.php ? Can someone help?

Error:

Uncaught ReferenceError: pouchITSave is not defined   profile.html:1
onClick

searchcode.php

<?php
ob_start();
header("Access-Control-Allow-Origin: *");
header('Content-type: ' . $image['mime_type']);
?>

<!DOCTYPE html>
<html>
<head>
<script   type="text/javascript" >
function pouchITSave(){
alert("PouchITSavecalled = ");
}
</script>  

</head>

<body>

<?php

    echo '<input type="submit" class="btn" id="'.$row['UniqueAdvertisingCode'].'" onclick="pouchITSave()" value="POUCH"  >';

?>


</body>
</html>

Your javascript code must not be placed in searchcode.php. It must be placed at the top of the file calling searchcode.php.

The main reason behind this is the script must be loaded on the OnLoad event of your main file and if it was not loaded then the function will not be recognized by the interpreter.

In additional you must also echo those tags you've put on searchcode.php.

Try replacing your echo:

echo "<input type='submit' class='btn' id='".$row['UniqueAdvertisingCode']."' onclick='pouchITSave();' value='POUCH' >";

As you had a mixture of " and ' , which I suggest you opt for " for outside quotations, easier to understand and maintain in my opinion, and make sure as Vhevhang said that you're retraiving the js code too, if not place it at the bottom of the page in your html file.

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