-2

I try to dynamically change the key of the object data in jQuery.

Below is my code:

// User is "finished inputing selection or typing," do something
function doneInput (e) {

    var $column = 'product_title'

    $.ajax({
        url: draftUrl,
        type: 'POST',
        data: {$column : $value

        },
        success: function (data) {
                     console.log(data);
                     if ($eventId){
                         // Dbs mean draft saved box an extenstion to make it unique;
                         displayDraft('#'+$eventId+'Dsb');
                     }
        },
        error: function(jqXHR, errMsg) {
            // Handle error
            alert(errMsg);
        }
    });
} // End of doneinput function

I got the below result

Array
(
    [$column] => Blue addidas men's jeans
)

I wanted something like:

Array
(
    [product_title] => Blue addidas men's jeans
)

And I couldn't enter it manually since I will be changing the value of '$column' dynamically.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sam
  • 853
  • 3
  • 19
  • 50

1 Answers1

0

You need to pass a JSON array as the response from the server and parse it in JavaScript,

var resultJSON =  '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});

Check here: Loop and get key/value pair for JSON array using jQuery

PS: Unless you use some kind of PHP/JavaScript templating system, you seem to confuse PHP syntax with JavaScript (not "var $column" but "var column").

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vishukani
  • 11
  • 4