简体   繁体   中英

Value attribute of html element is undefined

Why is name undefined?

$('#langs li').click(function(){
    var name = $(this).attr('value');
    $.ajax({
        type: "POST",
        url:'test.php',
        data: 'name='+name,
        success:function(raspuns){
            //$('#content1').html(raspuns);
            var ras = raspuns;
            $.ajax({
                type: "POST",
                url: "index.php",
                data: 'ras='+ras;
            )};
        }
    });
});

If what you mean is that raspuns seems to be undefined, maybe it's because you did not echo your response from test.php ?

test.php

...
echo 'this is my response';

AJAX call

$.ajax({
  ...
  success: function(raspuns) {
    // raspuns == 'this is my response'
  }
});

And also, if you're passing POST data, I think it would be better if you pass a JSON object, like so:

$.ajax({
  url: 'test.php',
  type: 'POST',
  data: {name: name},
  ...
});

You can check a few things: make sure you have data before sending. you have value attribute on li? or if you want to get li contents, use html() or txt(). But probably you want to get input field value inside li?. then use $(this).find("input").val() if you have just one input inside. Then others to check:

1) Visit http://example.com/test.php to make sure it echoes the response correctly. You may have error in php or the link may not be accessible.

2) Your url is like this: http://example.com/test.php ? It is also fine if you have a virtual host in your local machine like http://example.local/test.php . But it will not work if you have something like

http://localhost/mysite/test.php 

unless you correct your path in ajax call to a full link.

3) Make sure your javascript doesnt fail before sending. I mean, are you able to do alert(name) ? You can also use beforeSend() above success to check if you are ending data correctly.

4) Make sure you are not trying to make a cross domain ajax request as you can't do so with POST.

5) May try using "/test.php" instead of "test.php" although it wouldn't be the problem, I think.

You can also use console to see what is going on.

li elements don't support a value attribute. Perhaps you're looking for an input or the contents of li via .html() .

See in this demo that name is undefined: http://jsbin.com/IzOXiJOZ/2/edit

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