0

I would like to pass data from a dynamically built form via ajax to a php script, but have trouble finding the correct syntax for the parameter string format. There's a couple of fixed parameters and some are added dynamically, keys and values of the latter may change.

I've tried to build the parameter list as a concatenation of strings as below:

...
var dataVars = '{fctSelect: 2, strat: strat, ' + gbl.dataVariables + '}';

...

$j.ajax({
    url: "ajax/script.php",
    type: "POST",
    data: dataVars,
...

gbl.dataVariables is formatted as follows : 'field1: value1, field2: value2, field3, value3'

The resulting string to go into data "looks right" in console.log, but in the post tab of the console once the field validated, it appears like this:

{fctSelect: 2, strat: strat, ...

instead of:

fctSelect: 2
strat: 1
...

meaning that the parameters are not parsed. Could someone please point me to where I went wrong?

2 Answers 2

3

I would recommend you an alternative approach than string concatenations:

var dataVars = {};

// add some static values
dataVars['fctSelect'] = 2;
dataVars['strat'] = 'some value';

// now add some dynamic values
for (var i = 0; i < 10; i++) {
    dataVars['field' + i] = i;
}

// send the data as a JSON encoded request
$j.ajax({
    url: 'ajax/script.php',
    type: 'POST',
    data: JSON.stringify(dataVars),
    contentType: 'application/json',
...

and then inside your script.php:

$data = json_decode(file_get_contents("php://input"));
Sign up to request clarification or add additional context in comments.

Comments

2

Darin Dimitrov's solution is probably the way to go for you, I'll just give you an alternative. If you collect your form's fields and their values through serialize(), you can simply append your static data like this:

var dataVars = $('form').serialize(),
    dataVars += dataVars.length > 0 && '&'; // in case there are no form fields
    dataVars += 'fctSelect=2&strat=somevalue';

$j.ajax({
    url: 'ajax/script.php',
    type: 'POST',
    data: dataVars,
    success: function() {}
});

Comments

Your Answer

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.