Somename Somename - 4 months ago 8
Ajax Question

jquery ajax post within a function not working

So i have created a function to post data to a php page:

function updateData(x,y){
$.ajax({
type: 'POST',
url: 'myupdate.php',
data: {x:y},
success: function(data){
$("#resultdiv").html(data);
}
});
}


And I call the function like this:

$(".myclass").click(function(){
var newname = $("#myname").val(); //value of input type="text".
updateData('name', newname); // also tried updateData(name, newname)
});


So if i input the value as Rocky and initiate the function, problem is that the value sent to the php page
myupdate.php
is x=Rocky. I want it to be name=Rocky. How can i solve this.

Many thanks.

Answer

You need to use bracket notation when providing the key of an object in a variable. Try this:

function updateData(x, y) {
    var data = {};
    data[x] = y;

    $.ajax({   
        type: 'POST',   
        url: 'myupdate.php',   
        data: data,
        success: function(data){
            $("#resultdiv").html(data);
        }
    });
}