jquery - Submit form with AJAX to php api -
i have form posting data php api file. got api working , creates account want use ajax send data can make ux better. here php sending script expecting:
<form id="modal-signup" action="/crowdhub_api_v2/api_user_create.php" method="post"> <div class="modal-half"> <input type="text" placeholder="first name" name="user_firstname"></input> </div> <div class="modal-half"> <input type="text" placeholder="last name" name="user_lastname"></input> </div> <div class="modal-half"> <input type="radio" placeholder="gender" value="male" name="user_gender">male</input> </div> <div class="modal-half"> <input type="radio" placeholder="gender" value="female" name="user_gender">female</input> </div> <div class="modal-half"> <input type="date" placeholder="dob" name="user_dateofbirth"></input> </div> <div class="modal-half"> <input type="text" placeholder="zip code" name="user_zip"></input> </div> <input class="end" type="email" placeholder="email" name="user_email"></input> <input type="password" placeholder="password" name="user_password"></input> <input type="submit"></input> </form>
php
$user_firstname = $_request['user_firstname']; $user_lastname = $_request['user_lastname']; $user_email = $_request['user_email']; $user_password = $_request['user_password']; $user_zip = $_request['user_zip']; $user_dateofbirth = $_request['user_dateofbirth']; $user_gender = $_request['user_gender']; $user_phone = $_request['user_phone']; $user_newsletter = $_request['user_newsletter'];
how send via ajax? found script says worked, did not create user. imagine sending data not right way.
ajax
$(function () { $('#modal-signup').on('submit', function (e) { e.preventdefault(); $.ajax({ type: 'post', url: '/api_v2/api_user_create.php', data: $('form').serialize(), success: function () { alert('form submitted'); } }); }); });
first, let's ajax in order:
$(function () { $('#modal-signup').on('submit', function (e) { e.preventdefault(); $.ajax({ type: 'post', //same url form url: '/crowdhub_api_v2/api_user_create.php', data: $('form').serialize(), //we need variable here see happened php success: function (msg) { //output page $('#output').html(msg); //or console //console.log('return ajax: ', msg); } }); }); });
somewhere on form page, add div id output:
<div id="output></div>
finally, in api_user_create.php, there error:
$user_gender = $_request['user_gender']; //these last 2 not exist on form $user_phone = $_request['user_phone']; $user_newsletter = $_request['user_newsletter'];
i'd recommend error-checking on php side, this
if(!empty($_request)){ //for developing, may want print incoming data see came through //this data returns msg variable of ajax function print_r($_post); //once that's good, process data if(isset($_request['user_gender'])){ $user_gender = $_request['user_gender']; } //etc... before } else { echo 'no data received'; }
Comments
Post a Comment