简体   繁体   中英

Saving to database via Ajax

I have a situation,I need to add lot of text to server (via ajax & php).Each is happeening by clicking on a add button.In order to reduce round trip.I am planning to give a save all button so once I store everything in client side and I can save all together to database via ajax so only one round trip.

I have 6 input fields and needs to save this info everytime

My planning

Store everything in a JavaScript hidden variable and itreate this in php side and save it. I will have to store lot of text in hiden field.Is my approach correct ? any better way ?

You dont need to store it on hidden fields, just make a JSON object containing the data you want and then send it to the server throught ajax.

You can create the JSON object this way:

var jsonObject = {'name': $('#name').val(), 'city': $('#city').val()};

And then you send it to PHP throught AJAX:

$.ajax({
    type: 'POST',
    url: 'some.php',
    data: jsonObject,
    dataType: 'json'
}).done(function() {
    alert('success');
}).fail(function() {
    alert('error');
}).always(function() {
    alert('complete');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM