frosty
frosty

Reputation: 2669

Using ajax to display what is being typed not working, PHP, AJAX, JAVASCRIPT

Using ajax, I'm trying to display what is being typed in the text box, but it's not displaying anything at all for some reason. I know the ajax function itself got called, by using alert inside the function, and I think the real problem is actually in test2.php, but I'm not sure what I did wrong. Please take a look:

test1.php

<?php

include('ajax.php');

echo "<input type = 'text' name = 'select' onkeyup = 'ajax(\"test2.php\",\"select\",\"output\")'>";
echo "<div id = 'output'/>";

?>

test2

<?php

$select = $_POST['select'];
echo $select;

?>

ajax.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type = "text/javascript"> 

function ajax(url,select,id) {

      $.ajax({
           type: "POST",
           url: url,
           data: { select: $('select[name="select"]').val()},
           error: function(xhr,status,error){alert(error);},
           success:function(data) {
             document.getElementById( id ).innerHTML = data;
           }

      });

}

</script>

Upvotes: 1

Views: 62

Answers (2)

ksealey
ksealey

Reputation: 1738

function ajax(url,unused,id) {
    $.post(url,{select: $('input[name="select"]').val()})
    .error(function(e){
        alert(e);
    })
    .success(function(d){
        $("#"+id).text(d);
    });
}

Upvotes: 3

CodeGodie
CodeGodie

Reputation: 12142

The problem is here:

 data: {select: $('select[name="select"]').val()},

There is no select element. And if you meant to get the id named element, then you need to change it to:

data: {select: $('#select[name="select"]').val()},

or in your case:

data: {select: $('input[name="select"]').val()},

Upvotes: 0

Related Questions