form submit results to load in div - html

Struggling now for a few days and editing a few codes just to send my form to the process.php and then reload the result in the div the form is.
I'm working with a bootstrap layout and don't want the page to reload / go to process.php
HTML form is working when not by ajax call so the form and process.php is ok.
Only thing is I check in process on
$_POST['toevoegen'] == "training toevoegen"
because more forms go to process.php if I succeed the transfer to it.
HTML form just a snapshot out of it, it has more values in it.
<form id="form1" name="form1" method="post" action="process.php">
<label>datum:</label>
<input name="datum" id="datum" size="10" type="text" autocomplete="off" /><br><br>
<label>club:</label>
<select name="clubid" id="club-list" onChange="gettrainer(this.value);">
<option value="">Selecteer club</option>
<?php
foreach($results as $club) {
?>
<option value="<?php echo $club["id"]; ?>"><?php echo $club["clubnaam"]; ? ></option>
<?php
}
?>
<input type="submit" id="submit" name="toevoegen" value="training toevoegen" />
</form>
The ajax call is something like this but this won't work at all for the moment.
<script>
$( document ).ready(function() {
$('#form1').on('submit', function (e) {
e.preventDefault();
var form1 = document.getElementById("form1");
var fd = new FormData(form1);
$.ajax({
type: 'POST',
url: 'process.php',
data: fd,
success: function (response) {
$("#main").html(response);
}
});
});
});
</script>

changed the data field to data: $('#form1').serialize(),
<script>
$( document ).ready(function() {
$('#form1').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'process.php',
data: $('#form1').serialize(),
success: function (response) {
$("#main").html(response);
}
});
});
});
</script>

Related

a form inside another and ajax

hello I have the following code that tries to show the field "name" in the div "target2", but for this I use a form within another form I think is the problem. But I don't see a way to fix it.
index.php
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<form method="post" id="fuera">
<div id="target1">
</div>
<button type='button' id="botonFuera">EnviarElDeFuera</button>
</form>
<div id="target2">
</div>
</body>
</html>
otro.php
<form method="post" id="dentro">
<input type='hidden' id='nombre' name='nombre' value='hola'>
<button type='button' id="botonDentro">EnviarElDeDentro</button>
</form>
otroMas.php
<?php
echo($_POST["nombre"]);
?>
ajax.js
(document).on('ready',function(){
$('#botonFuera').click(function(){
var url = "otro.php";
$.ajax({
type: "POST",
url: url,
data: $('#fuera').serialize(),
success: function(data)
{
$('#target1').html(data);
}
});
});
$(document).on('click',':button', function (evt) {
if(this.id=='botonDentro')
{
var url = "otroMas.php";
$.ajax({
type: "POST",
url: url,
data: $('#dentro').serialize(),
success: function(data)
{
$('#target2').html(data);
}
});
}
});
});

Why input value is NULL when using Ajax?(ASP.NET CORE)

I do not have access to input values when using Ajax in View(MVC) but I have access to input values when not use Ajax. actually values is empty when use Ajax
When I use Ajax:
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<input type="reset" value="send" id="ajax-button" class="btn btn-success btn-sm waves-effect waves-light submit-btn" />
</form>
Script:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
var data = $('#Form1').serialize();
$('#ajax-button').click(function () {
debugger
$.ajax({
type: "POST",
data: data,
url: url,
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
I added tag helpers
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, SmsWebClient
#using Microsoft.AspNetCore.Razor.TagHelpers;
Value is null before enter to ajax ,image:
Please Move the
var data = $('#Form1').serialize();
to below
$('#ajax-button').click(function () {
In fact, your code should be:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
$('#ajax-button').click(function () {
var data = $('#Form1').serialize();
debugger
$.ajax({
type: "POST",
data: data,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
In your code data set when docuement loaded and for this reason the value
is null
You must write like this
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<div class="form-group">
<button id="ajax-button">Submit</button>
</div>
</form>
And This ViewModel
public class RegisterVm
{
public string Name { get; set; }
public string Number { get; set; }
}
And finally this is the Ajax code
#section Scripts{
<script>
$(document).ready(function () {
var url = $('#Form1').attr("action");
var model = $('#Form1').serialize();
var token = $('input[name=__RequestVerificationToken]').val();
model.__RequestVerificationToken = token;
$('#ajax-button').click(function () {
$.ajax({
type: $('#Form1').attr("method"),
data: model,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
}
Your data are set when docuement loaded, it will not pass the value which you enter.
For a working demo, try code below:
<script>
$(document).ready(function () {
$('#ajax-button').click(function () {
var url = '#Url.Action("Register", "Home")';
var data = new FormData();
data.append('Name', $('#Name').val());
data.append('Number', $('#Number').val());
$.ajax({
type: "POST",
data: data,
url: url,
processData: false,
contentType: false,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>

JSON response print

I have a ajax request script with post method using body value, what I want is, to print the response value.
$('#my-form').submit(function () {
$.ajax({
url: 'https://apiurl.com/users',
type: 'post',
headers: {
'accept': 'application/json;charset=UTF8',
'content-type': 'application/json',
'api-key': 'judmkd895849438'
},
contentType: 'application/json',
data: { "firstname": $('#firstname').val(), "lastname": $('#lastname').val() },
success: function( data, textStatus, jQxhr ){
$('#response pre').html( JSON.stringify( data ) );
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
and the form script is:
<form id='my-form'>
<div><input type='text' name='firstname' id='firstname' placeholder='Firstname' /></div>
<div><input type='text' name='lastname' id='lastname' placeholder='Lastname' /></div>
<div><input type='submit' value='Submit' /></div>
</form>
<!-- where the response will be displayed -->
<div id="response">
<pre></pre>
</div>
but nothing display on screen, anyone know why?
thanks
As Roy stated, you'll need to prevent the browser from submitting the form. You'll have to prevent the default event from firing as you're handling it via an AJAX request.
$('#my-form').submit(function (event) {
event.preventDefault();
$.ajax({
url: 'https://apiurl.com/users',
...

How to send button value with form

I have a form and ajax.
I can't send with $(form).serialize();
How do I send the button value with the form?
html:
<form action="" id="ogrenci_arama_formu">
<input type="text" id="eposta" name="eposta">
<button id="ogrenci_ara" name="ogrenci_ara" value="true" class="btn btn-info">Öğrenciyi Ara</button>
<!--<input id="ogrenci_ara" type="hidden" name="ogrenci_ara" value="true">-->
</form>
ajax:
$("#ogrenci_arama_formu").submit(function (e) {
e.preventDefault();
console.log("form: ",$(this).serialize());
$.ajax({
url: "sayfalar/ogrenci_bilgileri.php",
type: 'post',
/*dataType: 'json',*/
data: $(this).serialize()
}).done(function(data) {
$("tbody").html(data);
}).fail(function(data) {
console.log("error",data);
});
});
output:
eposta=
try like store button value into a variable and send with form serialize like this
JAVASCRIPT-
$("#ogrenci_arama_formu").submit(function(e) {
e.preventDefault();
var btnValue = $(this).find('#ogrenci_ara').val();
console.log("form: ", $(this).serialize()+'&ogrenci_ara='+btnValue);
$.ajax({
url: "sayfalar/ogrenci_bilgileri.php",
type: 'post',
/*dataType: 'json',*/
data: $(this).serialize()+'&ogrenci_ara='+btnValue
}).done(function(data) {
$("tbody").html(data);
}).fail(function(data) {
console.log("error", data);
});
});

POSTING data from Angular UI bootstrap modal window to PHP

I have a angular-ui modal, that is controlled with below controller:
var emailModal = angular.module('myApp.emailModal', ['ui.bootstrap', 'ui.bootstrap.tpls']);
emailModal.controller('ModalCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) {
$scope.open = function () {
var modalInstance = $uibModal.open({
templateUrl: 'components/emailModal/emailModalView.html',
backdrop: true,
controller: 'modalInstanceCtrl'
});
}
}]);
emailModal.controller('modalInstanceCtrl', function ($scope, $uibModalInstance, $http) {
//create blank object to handle form data.
$scope.user = {};
//calling our submit function.
$scope.submitForm = function() {
//posting data to php file
$http({
method: 'POST',
url: 'components/emailModal/emailInsert.php',
data: $scope.user, //forms user object
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
//showing errors.
$scope.errorEmail = data.errors.email;
} else {
$scope.message = data.message;
}
});
};
});
This is the actual modal view:
<form name="userForm" ng-submit="submitForm()">
<div class="modal-header">
<h3 class="modal-title">Register</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label>E-Mail Address</label>
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Email address" />
<span ng-show="errorEmail">{{errorEmail}}</span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
Modal loads with no problem, bute once clicked to submit, nothing happens. I get no error once so ever in the console. What am I doing wrong? This is my PHP file, as well:
$errors = array();
$data = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);
// checking for blank values.
if (empty($_POST['email']))
$errors['email'] = 'E-Mail erforderlich.';
if (!empty($errors)) {
$data['errors'] = $errors;
} else {
$data['message'] = 'The data should now be inserted into database!';
}
// response back.
echo json_encode($data);
?>
EDIT 1.
The event is triggered in Dev Tools - Network.
This is what I get:
Request URL: http://localhost:63342/url-to/emailInsert.php
Request method: POST
Remote address: 127.0.0.1:63342
Status code: 200 OK
Version HTTP/1.1
The page is not reloading on submit, at all, there is no error in Dev Tools - Console. It gives a OK status even though the email has not been ineserted into input, therefore it should print an error, which it doesn't do.
Any help is greatly appreciated.