Nikolaj Møller Nikolaj Møller - 9 days ago 5
JSON Question

Trying to send data to database with AJAX (CI)

i have a problem with my AJAX, not posting any data to my database, i have googled the internet dry, and now i ended up here.

I tried in Postman, inserting my Json data (seen below) and i did a POST to my method in my API controller(user/add_user), my controller then runs the query from my model, and it is inserted into the database correctly.

{
"first_name": "Admin",
"last_name": "Panna",
"email": "Admin2@mail.com",
"password": "Admin1234",
"phone_number": "12345678",
"address": "Nowhere 1",
"city": "somwhere",
"country": "Germany",
"nationality": "Finnish",
"speak_danish": "1",
"colleague": "Dora The Explorer",
"task": "Security"
}


So the problem is really that my frontend, with my jquery ajax calls is not doing a POST, or atleast not right, because i cant see any data being send anywhere, and in the console tool in the browser, in the network tab, no POST method is being listed :(

Here is my function that loads the HTML in my API (just so you can see the HTML code)

function registrationPage() {
var html =
'<div class="register-text container">'
+'<h3>You are about to register as a volunteer for</h3>'
+'<img src="' + RESS +'img/tinderbox_date.svg">'
+'</div>'
+'<div class="register-input container">'
+'<div>'
+'<input id="email" type="email" name="email" placeholder="Email">'
+'<input id="password" type="password" name="password" placeholder="Password">'
+'<input id="first_name" type="text" name="first_name" placeholder="First Name">'
+'<input id="last_name" type="text" name="last_name" placeholder="Last Name">'
+'<select id="gender" name="gender" placeholder="Gender">'
+'<option value="" disabled selected>Gender</option>'
+'<option value="1">Female</option>'
+'<option value="0">Male</option>'
+'</select>'
+'<label for="dateofbirth">Date of Birth</label>'
+'<input id="dateofbirth" placeholder="Date of Birth" type="date" name="dateofbirth" >'
+'<select id="nationality" name="nationality" >'
+'<option value="nationality" disabled selected>Nationality</option>'
+'<option value="Danish">Danish</option>'
+'<option value="German">German</option>'
+'<option value="norwegian">Norwegian</option>'
+'</select>'
+'<div class="upload-image">'
+'<img src="images/picture.svg">'
+'<p>Upload image</p>'
+'</div>'
+'<input id="phonenumber" type="number" name="phonenumber" placeholder="Phonenumber">'
+'<input id="address" type="text" name="address" placeholder="Address">'
+'<select id="country" name="country" placeholder="Country">'
+'<option value="Denmark">Country</option>'
+'<option value="Denmark">Denmark</option>'
+'<option value="germany">Germany</option>'
+'<option value="Norway">Norway</option>'
+'</select>'
+'<input id="zipcode" type="number" name="zipcode" placeholder="Zip code">'
+'<input input="city" type="text" name="city" placeholder="City">'
+'<select id="speak_danish" name="speak_danish">'
+'<option value="danish" disabled selected>Speak and understand Danish</option>'
+'<option value="1">Yes</option>'
+'<option value="0">No</option>'
+'</select>'
+'<select id="task" name="task">'
+'<option value="tasks" label disabled selected>Preferred work tasks</option>'
+'<option value="fences">Building Fences</option>'
+'<option value="bartender">Bartender</option>'
+'<option value="it-work">IT Work</option>'
+'</select>'
+'<input id="colleague" type="text" name="colleague" placeholder="I like to work with (name)">'
+'<button class="link-register-user" type="submit" value="REGISTER">Register</button>'
+'</div>'
+'</div>';

jQuery('#main').html(html);
}


and the AJAX i have for it is here

function register(e) {
e.preventDefault();

var emailVal = jQuery('#email').val();
var passwordVal = jQuery('#password').val();
var first_nameVal = jQuery('#first_name').val();
var last_nameVal = jQuery('#last_name').val();
var genderVal = jQuery('#gender').val();
var dateofbirthVal = jQuery('#dateofbirth').val();
var phone_numberVal = jQuery('#phone_number').val();
var addressVal = jQuery('#address').val();
var cityVal = jQuery('#zipcode').val();
var zipcodeVal = jQuery('#city').val();
var countryVal = jQuery('#country').val();
var nationalityVal = jQuery('#nationality').val();
var speak_danishVal = jQuery('#speak_danish').val();
var colleagueVal = jQuery('#colleague').val();
var taskVal = jQuery('#task').val();
var sendData = {
"email": emailVal,
"password": passwordVal,
"first_name": first_nameVal,
"last_name": last_nameVal,
"gender": genderVal,
"dateofbirth": dateofbirthVal,
"phone_number": phone_numberVal,
"address": addressVal,
"city": cityVal,
"zipcode": zipcodeVal,
"country": countryVal,
"nationality": nationalityVal,
"speak_danish": speak_danishVal,
"colleague": colleagueVal,
"task": taskVal
};
jQuery.ajax({
url: URL + 'user/add_user',
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(sendData),
success: function(data, status, response) {
console.log('Success');
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
console.log(sendData);
}
});
}


Like i said i know my controller and model is working, since it works in POSTMAN, but none the less let me know if i should share that also,
for you to be able to help better? :)

Btw plz bear with me, since my this is my very first posting on stack overflow ever, and i also am fairly new to coding in genral.

Thank you in advance awesome community! :)

Answer

I think the problem is how you are doing your .ajax() options. Let's change it up a little.

Since you are using event delegation, get the element that contains your inputs i.e. #main by using e.delegateTarget. Then use a nice method called .serialize() to serialize all your form inputs. (You may have to rename some of your input name attributes to pass the key-value pairs in the correct format that you are handling them on the server-side.)

I am not too sure about contentType option as I've never used it for anything, so I'd also remove that. Based on Patrick's comment, it would give an undesired behavior.

So, the code would simply look like

function register(e) {
    e.preventDefault();
    jQuery.ajax({
        url: URL + 'user/add_user',
        type: 'POST',
        data: jQuery(e.delegateTarget).find(':input').serialize(),
        success: function (data, status, response) {
            console.log('Success');
        },
        error: function (xhr, status, error) {
            var err = JSON.parse(xhr.responseText);
            console.log(sendData);
        }
    }); 
}

// somewhere
jQuery('#main').on('click', 'link-register-user', register);
Comments