0

I'm still relatively new to jquery so I was wondering what was the best practice for sending multiple variables to php using ajax. For example, should I send the variables in a package like:

$.ajax({
    data:{
        input: {x: 1, y: 2}
    },
    ...
})

or send them as individual variable such as:

$.ajax({
    data:{
        x: 1,
        y: 2
    },
    ...
})

Is there any performance benefit or any other kind of benefit of using one over the other?

Thanks for your time, LL

kLai
  • 271
  • 3
  • 11
  • 1
    There is no difference in your code examples, save for style of layout. – Jay Blanchard Oct 08 '14 at 19:47
  • 1
    Voted to close as primarily opinion-based because really, it is just a personal preference. I prefer the second one. – Karl-André Gagnon Oct 08 '14 at 19:51
  • The first one will be a TINY amount slower on the backend because it's more complicated to deserialize and subsequently requires one extra step to access the members (I don't know much about how PHP uses memory so this might be inconsequential). In this case it's a trivially minor difference and I can't imagine you care about such tiny performance issues so it really just comes down to what you like more. – UpQuark Oct 08 '14 at 19:56

2 Answers2

2

This function is the simplest when there are many fields in a form .serialize()

    <html>
    <body>

    <form action="#" id="formsend" method="post" name="formsend"> 
    <input name="val1" id="val1">
    <input name="val2" id="val2">
    <input name="val3" id="val3">
    ......
    </form>
    <a  href="javascript:;" id="btn_send" >Send</a>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type= "text/javascript"></script>

    <script>

$( "#btn_send" ).click(function() {
     $.ajax({
       type: 'POST',
       url: 'ajax/ImAjaxPhpFile.php',
       data: $("#formsend").serialize(), // send all form
       beforeSend: function(){              
       },
       complete: function(){  
       },
       success: function(a){                            
          alert (a);
       }
    });
});


    </script>
    </body>
    </html>
Dario
  • 417
  • 4
  • 17
0

This depends on your usage. If you just need simple variables ( one or two ) , you can directly pass them like the 2nd one. But if you need to pass a complex structured data , you can go for 1st one. But again, if you have more complex structured data as ajax param, server side deserialization might be slow. - Some related link - Getting "The JSON request was too large to be deserialized"

Community
  • 1
  • 1
Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48