Reputation: 103
I have a form , that I'm sending its by ajax to php file to manipulate database.
//html
<form id='editUserForm' action='insert.php' method='post'>
<input type='text' name="userName/>
<input type='text' name="userLastName/>
<input type='submit' name='editUser' value='submit'/>
</form>
//ajax
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
alert("Done");
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#editUserForm').submit( processForm );
})(jQuery);
//insert.php
if(isset($_POST['editUser'])){
if(isset($_POST['chUserStatus'])){
$active='َactive';
}else{$active='disabled';}
$query="update admins set user='$_POST[chUserName]', pass='$_POST[chUserPass]',email='$_POST[chUserEmail]',level='$_POST[chUserLevel]',status='$active' where id=$_POST[userId]";
$result=mysqli_query($dbCnn,$query);
echo(mysqli_error($dbCnn));
} The problem is here, because my function is preventing form default submit, it doesn't post submit btn name/value to insert.php. How can I send it as parameter to insert.php?
Upvotes: 0
Views: 92
Reputation: 157
$("#search").submit(function(e){
e.preventDefault();
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
alert("Done");
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="search">
<input name="q"/>
<input type="submit" value="Submit"/>
</form>
see the result in console.
Upvotes: 1
Reputation: 647
You can put it in the form data object before serialize, ore even append it after serialize. Personally I'll just add a new hidden input like:
<input type="hidden" name="action" value="editUser" />
Upvotes: 0
Reputation: 337620
serialize()
does not retrieve any attributes from button
elements, you would need to add that information yourself, if you need it:
var $button = $('#editUser :submit');
// in the $.ajax...
data: $(this).serialize() + '&' + $button.prop('name') + '=' + $button.val(),
Upvotes: 1