jquery - getting ajax to pass string variable from javascript to php -


this javascript using now

<script>     $( document ).ready(function() {         var namer = sessionstorage.getitem("namer");         $.ajax({             type: "post",             url: "antibiotics2.php",             data: { 'name': namer }         }).done(function( msg ) {             alert( "data saved: " + msg );         });     }); </script> 

and php:

<?php echo $_post['name']; ?>             

it throws error , says index 'name' can't found.

well have replicated set , each time able retrieve variable set within $_post. have avoided amending names stated session being correctly captured in similar question.

i able reproduce error setting namer variable undefined or trying retrieve value not present.

since able send variable namer long set have couple of things.

  1. check if namer variable set, perhaps client , server side. in javascript test if variable not undefined or in php check if $_post['namer'] set.

  2. your session may expire , therefore trying retrieve value ofcourse no longer there, dependent upon library using or settings declared when creating session

in both instances experience same error , doing logic avoid error.

server side check - php:

if(isset($_post['namer'])){     echo $_post['namer']; }else{     echo "session capture unsuccessful"; } 

client side check - javascript:

var namer = sessionstorage.getitem("namer");  if (typeof namer === "undefined")     console.log("your session not set"); } else{     // place ajax request here     // or set namer variable default value } 

please if possible develop web applications locally easier debug , final note may easier use console.log(yourerror) debugging purposes rather alert(yourerror).


Comments