3

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.

2 Answers 2

5

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);
        }
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

you need to define object property dynamically

function updateData(x,y){
     var post_data= {};
     post_data[x]=y; // dynamic property
     $.ajax({   
        type: 'POST',   
        url: 'myupdate.php',   
        data: post_data,
           success: function(data){
           $("#resultdiv").html(data);
          }
       });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.