Luke85
Luke85

Reputation: 11

Ajax POST in Javascript is not working

I searched my problem but I cannot find any solution. I guess it's really simple and I missing something really easy...but I'm stucked.

I have an html page with a php generated list of links, like that:

<?php    
     $val = "'"my file with spaces.txt"'";
     echo '<a href="javascript:post_filename('.$val.');">click me</a>';
?>

Where $val is different each time, depending on a SQL query. And the file name is showed correctly, since I hover the mouse on the link and I can read on the bottom-left of the browser:

javascript:post_filename('my file with spaces.txt');

Clicking this link will call this javascript function:

<script type="text/javascript">
        function post_filename(val){
             $.ajax
            ({ 
                url: 'myurl.php',
                data: { filename: val },
                type: 'POST'
            });
        }
</script>

But clicking on it, does nothing! No errors, just nothing happens.

With the dev tools (F12 on Chrome) I see that it's all ok... just the mypage.php doesn't show... is a page with graphics, part of the site!

I'm stucked... please help me! Thanks so much

Upvotes: 1

Views: 48

Answers (3)

mpalencia
mpalencia

Reputation: 5997

I tried your code, but I made some some revisions for it to work ( I just notice you had a semicolon after type, I believe that should be a comma, that the reason why you have unexpected token) my codes works using this:

<?php    
$val = "'hello.txt'";
echo '<a href="#" class="click" file="'.$val.'">click me</a>';
?>

on javascript

$('.click').click(function() {
    $.ajax
    ({ 
        url: 'myurl.php',
        data: { filename: $(this).attr('file') },
        type: 'POST'
    })
    .done(function (data) {
        //check the output from your url
        console.log(data);
    })
    .fail(function (jqXHR, textStatus) {
        console.log("Request failed: " + textStatus);
    });
});

Upvotes: 0

Lynch
Lynch

Reputation: 910

Your AJAX call was invalid, data should be either a String, Array or Object. Object is probably what you're after here from the start you've made

<script type="text/javascript">
        function post_filename(val){
             $.ajax
            ({ 
                url: 'myurl.php',
                data: {
                    filename: val
                },
                type: 'POST';
            });
        }
</script>

Upvotes: 1

Dory Zidon
Dory Zidon

Reputation: 10719

Try making data an object:

<script type="text/javascript">
        function post_filename(val){
             $.ajax
            ({ 
                url: 'myurl.php',
                data: { filename: val },
                type: 'POST';
            });
        }
</script>

Upvotes: 0

Related Questions