0

I am trying to send a JSON object into an Symfony action.

The script used to build and send the array looks like this:

var rows, arr = [];
 rows = table.find('table tbody tr');
 arr['x'] = new Array(rows.length);
 table.find('table tbody tr').each(function (i) {
 arr['x'][$(this).find('.username').text() - 1] = i;
 });
 console.log(arr); //PRINTS THE PROPER JSON OBJECT
 $.ajax('some/correct/path', {
 type: 'PUT',
 data: arr,
 datatype: 'json',
 success: function (e) {
 console.log(e);
 }
 });

And here I have an action for which should for now do nothing but capture the request data and send it back:

/**
 * @View\Route("/x", name="x", options={"expose"=true})
 * @View\Method("PUT")
 */
public function xAction(Request $request)
{
 $all = $request->request->all();
 return $this->json($all);
} 

The problem here is that when I use the console.log on the arr variable, it results in a proper print, yet when I console log the e which was supposed to come from the action the result is:

[]

Here are the things I have already tried:

  • Running the $.ajax with data : 'sometext' (response was: {sometext: ""})
  • Changing the method to POST
  • Removing the datatype: 'json'
  • Setting the data to: JSON.stringify(arr)
  • Setting the data to: {data : arr}
  • Setting the data to: {data : JSON.stringify(arr)}
  • Setting the arr values directly into the array (without the ['x'] key)
  • Clearing the cache
  • Installing Linux
  • Setting laptop on fire
  • Going back in time to kill hitler

So far I have ran out of ideas to have it work properly. What could be the issue here and how can I make it work?

marc_s
759k185 gold badges1.4k silver badges1.5k bronze badges
asked Nov 19, 2017 at 16:43
4
  • Did you try with: data: JSON.stringify(arr), contentType: "application/json"? Commented Nov 19, 2017 at 16:51
  • Arrays have numeric index. You are creating an array like object as arr. Create object instead Commented Nov 19, 2017 at 16:53
  • @DannyFardyJhonstonBermúdez same effect Commented Nov 19, 2017 at 18:01
  • @charlietfl This worked! Can you please post it as an answer, so I can mark it? Commented Nov 20, 2017 at 9:25

1 Answer 1

1

arr should be an object not array. Arrays only have numeric index and when you add the property "x" it becomes an "array like" object

Change

arr = [];

To

arr = {};
answered Nov 20, 2017 at 12:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.