0

I have a problem to pass value to my php script via Ajax, there is my code :

I send value to ajax via a href link :

After scan directory i get links of my files on href :

<a href=""  onclick="getfilename('<?php echo $file; ?>');"><?php echo $file;  ?></a>

My js function to receive value :

 function getfilename(content) {

 alert(content); // i can see my value here

 $.ajax({ //not work

type: 'POST',
url: 'script.php',
data:{song: content},
async: false,
success: function(response) {
alert(response); //nothing
 });
}

My script.php

$album = $_POST['song'];
echo $album;

I dont understand why it does not work.

Thank you for your help!

4
  • the code seems to be alright, my first guess would be to verify the url script.php.....are you sure the path is correct? It's in the same folder as your JS file? Commented Apr 16, 2014 at 20:30
  • use firebug to check response. And when you say "does not work", what is that supposed to mean? Commented Apr 16, 2014 at 20:32
  • Both file is located in the same folder, does not wo Commented Apr 16, 2014 at 20:38
  • does not work, beacause Ajax not showing data received by php in success: function(response) { alert(response); //nothing Commented Apr 16, 2014 at 20:39

3 Answers 3

1

Try changing

<a href=""  onclick="getfilename('<?php echo $file; ?>');"><?php echo $file;  ?></a>

To this

<a href="#"  onclick="getfilename('<?php echo $file; ?>');"><?php echo $file;  ?></a>

Maybe your page is refreshing before the ajax data loads.

Sign up to request clarification or add additional context in comments.

1 Comment

Happy to help. If you think this is the correct solution please mark it as your accepted answer. It allows others wanting to help people to see this post as "answered" so they can move on. If someone else's answer is more correct, select that one.
1

When you use the link element it will automatically go to the location in the href after it executes the onclick event. Leaving it empty will reload the page.

I would recommend you to add a "return false;" as the last instruction of the onclick.

<a href="" onclick="getfilename('<?php echo $file; ?>'); return false;"><?php echo $file?></a>

Hope this helps.

Comments

1

Looking to your js code your success callback is missing a "}" in the end of function.

// $file = 'teste';
<a href="#" onclick="getfilename('&lt;?php echo $file; ?>');"><?php echo $file?></a>

function getfilename(content) {
  alert(content);

  $.ajax({ 
    type: 'POST',
    url: 'script.php',
    data:{song: content},
    async: false,
    success: function(response) {
        alert('Response: ' + response); //Alerts Result
    }
  });
}

// Script.php

<?php 
  echo $_POST['song']
?>

1 Comment

This is true it miss } :) but my problem came from my a href link, thank you very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.