Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use element name when initializing object in javascript?

I'm trying to get data using ajax function, but my code returns :

Uncaught SyntaxError: unexpected string..

Javascript :

var myParams = {
  $('#csrf').attr('name') : $('#csrf').val(),
  'module' : 'culinary',
  'id' : '12',
}
$.ajax({
  url: '/uploader/get_list',
  type: 'GET',
  data: myParams,
  success: function(response) {
    reponse = $.parseJSON(response);
    console.log(response);
  }
});

One of my friends suggested to use this:

var myParams = [];
myParams[$('#csrf').attr('name')] = $('#csrf').val();
myParams['module'] = 'culinary';
myParams['id'] = '12';

But if I use the second method, the PHP function can't recognize the parameters.

What's the correct way to send parameters to an ajax function?

like image 727
dapidmini Avatar asked Jun 19 '26 00:06

dapidmini


2 Answers

The issue is in your creation of the myParams object. To create a key using a variable you need to use bracket notation. Try this:

var myParams = {
  'module': 'culinary',
  'id': '12',
}
myParams[$('#csrf').attr('name')] = $('#csrf').val();

The second example you have doesn't work because you create an array, ie. [], not an object, {}.

Also note that if you set the dataType property of the request then you don't need to manually parse the response as jQuery will do it for you:

$.ajax({
  url: '/uploader/get_list',
  type: 'GET',
  data: myParams,
  dataType: 'json',
  success: function(response) {
    console.log(response);
  }
});
like image 97
Rory McCrossan Avatar answered Jun 20 '26 14:06

Rory McCrossan


You should define new object {} and not new array [] :

var myParams = [];

Should be :

var myParams = {};

Hope this helps.

like image 33
Zakaria Acharki Avatar answered Jun 20 '26 13:06

Zakaria Acharki



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!