Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax post within a function not working

Tags:

jquery

ajax

php

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.

like image 668
Somename Avatar asked Sep 24 '26 10:09

Somename


1 Answers

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);
        }
    });
}
like image 58
Rory McCrossan Avatar answered Sep 26 '26 03:09

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!