0

I'm trying to pass a php variable to a javascript function via the onClick attribute.Heres the piece of code that I have tried but its not working php Section:

<li id="' . $todo1 . '" class="items">' . $todo1 . '<button onclick="ajaxdelete(' . $todo1   . ')">Delete</button></li>

Javascript function

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="JavaScript" type="text/javascript">

 function ajaxdelete(x){
   var todo = x;
   var hr = new XMLHttpRequest();
   var url = "ajaxtododelete.php";
   var vars = "todo="+todo;
   hr.open("POST", url, true);
   //Random Ajax stuff
   }
higfox
  • 87
  • 3
  • 9

2 Answers2

1

You need to put some php tags before and after your variable. For example in your case:

<? $todo1 ?>

or

<?php $todo1 ?>

and make sure that $todo1 got the value you wish to use.

== Update after your comments It seems you wish to pass the JS variable to the php side... in that case, you need to fix your question and pass the data in your ajax call to something like:

hr.open("GET", url + "/?" + vars, true);

Since you are using POST you can't just add the vars to the end of the url (btw, in your case you are not using 'vars' and this is way you are not getting anything in the server).

btw, an output of your html will help here as well.

Ido Green
  • 2,795
  • 1
  • 17
  • 26
  • there is no out put this variables is passed to ajax. – higfox Apr 15 '12 at 12:22
  • "...I'm trying to pass a php variable to a javascript function via the onClick attribute.." - if you are trying to pass php data to js you want the server to create the html and then send it to the client. – Ido Green Apr 15 '12 at 12:24
0

In order for the value contained in a PHP variable to be printed, you must either call echo, print etc. or enclose it between double quotes (not single). Also, put the php tags that Ido Green mentioned.

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69