jQuery Ajax passing input values from one modal to another - php

I have a modal for entering user information. A user should be linked to a building. After user information has been entered and submit button has been clicked, I am preventing the default action and am overlaying/showing a building modal over the user modal.
Code for doing so follows.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
}
});
$('#modalConnectBuilding').modal('show');
});
})(window.jQuery);
console.log() logs the input information correctly, however in 'modalConnectBuilding.php' the following does not work:
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
?>
Producing the following errors:
Undefined index: name_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: address_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: city_user in
C:\laragon\www\modals\modalConnectBuilding.php
My intent is to do a classic 'form action="./php/processConnectBuilding.php" method="post"' but would need access to the three undefined variables as seen above. Adding users and buildings works in isolation but not when connected in this way. Any help would be greatly appreciated and if you need any more info, please ask. Thank you!
Code for the form (within the modal) I'm submitting follows (please note, default action is being suppressed by preventDefault() so action attribute is never "called", also the form for connecting a building is basically the same, but the action attribute is not suppressed):
<form role="form" id="formAddUser" action="./php/processAddUser.php" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>

<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<form role="form" id="formAddUser" action="" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
</body>
</html>
<script>
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: 'tariffdetaildata.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function(data) {
alert(data)
}
});
});
</script>
tariffdetaildata.php
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];

Try this way I think you need to open the modal popup once you get the response back from the ajax.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
$('#modalConnectBuilding').modal('show');
$("#modalConnectBuilding .modal-body #name_user").val( name_user);
$("#modalConnectBuilding .modal-body #address_user").val( address_user);
$("#modalConnectBuilding .modal-body #city_user").val( city_user);
}
});
});
})(window.jQuery);

Related

PHP/AJAX: Insert BLOB into MySQL Database

I have some hard times to save a blob (image file) to my sql-database.
I have three files: a html form (form.php), an ajax script (ajax.js) and a php-file (save.php).
I think i have some errors in my ajax.js, but after a long google search i couldn`t find a good solution. There must be a problem with the blob handling in JS....
HTML Form:
<div id="editEmployeeModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form id="update_form" enctype="multipart/form-data">
<div class="modal-header">
<h4 class="modal-title">table bearbeiten</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="id_u" name="id" class="form-control" required>
<div class="form-group">
<label>Image</label>
<input type="file" id="image_u" name="image" class="form-control" required>
</div>
<div class="form-group">
<label>Überschrift 1</label>
<input type="text" id="header1_u" name="header1" class="form-control" required>
</div>
<div class="form-group">
<label>Überschrift 2</label>
<input type="text" id="header2_u" name="header2" class="form-control" required>
</div>
<div class="form-group">
<label>Text</label>
<input type="text" id="text_u" name="text" class="form-control" required>
</div>
<div class="form-group">
<label>Link</label>
<input type="text" id="link_u" name="link" class="form-control" required>
</div>
<div class="form-group">
<label>Link-Text</label>
<input type="text" id="linkText_u" name="linkText" class="form-control" required>
</div>
<div class="form-group">
<label>Datum</label>
<input type="date" id="datum_u" name="datum" class="form-control" required>
</div>
</div>
<div class="modal-footer">
<input type="hidden" value="2" name="type">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<button type="button" class="btn btn-info" id="update">Update</button>
</div>
</form>
</div>
</div>
</div>
In form.php i specified all my Inputs and for the image type=file
Ajax Code:
$(document).on('click','.update',function(e) {
var id=$(this).attr("data-id");
var image=$(this).attr("data-image");
var header1=$(this).attr("data-header1");
var header2=$(this).attr("data-header2");
var text=$(this).attr("data-text");
var link=$(this).attr("data-link");
var linkText=$(this).attr("data-linkText");
var datum=$(this).attr("data-datum");
$('#id_u').val(id);
$('#image_u').val(image);
$('#header1_u').val(header1);
$('#header2_u').val(header2);
$('#text_u').val(text);
$('#link_u').val(link);
$('#linkText_u').val(linkText);
$('#datum_u').val(datum);
});
$(document).on('click','#update',function(e) {
var data = $("#update_form").serialize();
$.ajax({
data: data,
enctype: 'multipart/form-data',
type: "post",
url: "save.php",
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$('#editEmployeeModal').modal('hide');
alert('Data updated successfully !');
location.reload();
}
else if(dataResult.statusCode==201){
alert(dataResult);
}
}
});
});
My PHP-Code:
if($_POST['type']==2){
$id=$_POST['id'];
$image= base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$header1=$_POST['header1'];
$header2=$_POST['header2'];
$text=$_POST['text'];
$link=$_POST['link'];
$linkText=$_POST['linkText'];
$datum=$_POST['datum'];
$sql = "UPDATE `tblTable` SET `image`='$image',`header1`='$header1',`header2`='$header2',`text`='$text',`link`='$link',`linkText`='$linkText',`datum`='$datum' WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
}
My Datbase-Connection works fine. I can write and read all other Data (Text and Date) to my local Database. I think my problem is in the ajax.js. How can i specify $('#image_u').val(image); that it must handle a blob file and not just normal text input. And do i have to modify these lines?
var data = $("#update_form").serialize();
$.ajax({
data: data,
enctype: 'multipart/form-data',
type: "post",
url: "save.php",

Using 2 recaptcha on same page and getting different values for both via AJAX

I have 2 Google Recaptcha's on same page in different forms (Login and Register Forms). I had to put both the forms on the same page due to the designing requirements which can't be changed. Now the problem is that the 1st form is the login form followed by the register form in the 2nd. Now, the recaptcha on the login form takes effect for register form as well. I mean that I can see recaptcha on both the forms but the one in register form doesn't work (which means it doesn't sends the correct value to the PHP page where the form will be processed). When I tried verifying the recaptcha on the login form and submitting the register form it worked. This means that the 1st loaded recaptcha (on the login form) is working for both which should not be. Both the recaptchas should work separately for each forms. Also, when I get the values of both the recaptchas via AJAX to send to the PHP page for the server side validation I am using captcha: grecaptcha.getResponse() for both. THIS CAN BE THE ACTUAL PROBLEM I GUESS. If I could get separate values for both maybe the things would have gone down well. Any help would be appreciated.
Here are my codes.
<div class="container">
<div class="row">
<div class="col-md-6">
<h3 class="com-reps cr-panel">Login Now</h3>
</div>
<div class="col-md-6">
<h3 class="com-reps cr-panel">Register Now</h3>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="login-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="uname" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="pass" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="login" value="Log In" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="register-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="name" class="form-control" placeholder="Full Name">
</div>
<div class="form-group">
<input type="text" id="username" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="password" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="password" id="cpass" class="form-control" placeholder="Confirm Password">
</div>
<div class="form-group">
<input type="text" id="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="text" id="dob" class="form-control" placeholder="Date of Birth">
</div>
<div class="form-group">
Sex
<input type="radio" id="sex" name="sex"> Male
<input type="radio" id="sex" name="sex"> Female
</div>
<div class="form-group">
<input type="checkbox" id="legal" name="legal"> I accept the Terms of Service and Privacy Policy.
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="submit" value="Register" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function(){
var dataString = {
uname: $("#uname").val(),
pass: $("#pass").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/login.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#login").val("Please wait...");
$(".login-message").hide();
},
success: function(html){
$('.login-message').html(html).fadeIn();
if($('.login-message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
window.location.replace("index.php");
}, 500);
}else{
$("#login").val("Log In");
}
}
});
return false;
});
$("#submit").click(function(){
var dataString = {
name: $("#name").val(),
uname: $("#username").val(),
pass: $("#password").val(),
cpass: $("#cpass").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sex: $("input[name='sex']:checked").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/register.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").val("Please wait...");
$(".register-message").hide();
},
success: function(html){
$('.register-message').html(html).fadeIn();
$("#submit").val("Register");
}
});
return false;
});
});
</script>
I got the solution. In case someone comes looking for this it will help them.
In both HTML Forms replace
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
to
<div id="recaptcha1"></div> and <div id="recaptcha2"></div> respectively.
Then replace your script calling from
<script src="https://www.google.com/recaptcha/api.js></script>
to
<script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
And insert these code in your <script></script>. Note that this should be outside of $(document).ready(function() { and above your next form submission AJAX codes.
var recaptcha1;
var recaptcha2;
var myCallBack = function() {
recaptcha1 = grecaptcha.render('recaptcha1', {
'sitekey' : 'YOUR_SITE_KEY'
});
recaptcha2 = grecaptcha.render('recaptcha2', {
'sitekey' : 'YOUR_SITE_KEY'
});
};
Next and last thing, change the captcha: grecaptcha.getResponse() in your form submission AJAX code to captcha: grecaptcha.getResponse(recaptcha1) and captcha: grecaptcha.getResponse(recaptcha2) respectively (for both AJAX codes of login and register forms in my case). For full form submission code please refer to the code in my question above. Just replace the captcha: part here as said.
Done! Now you can proceed to server side validation in your language (PHP or ASP whatever).

Post edit form data and get it in controller using angularjs

I want to post edit form data to codeigniter controller using angularjs
this is my angularjs controller where i collect and post form data
$scope.editlist = function(id){
$http({
method:'post',
url:'http://localhost/Angular_demo/admin/index.php/welcome/get_edit_data/'+
id
}).then(function success(response){
$scope.sid = parseInt(response.data[0]['id']);
$scope.firstname = response.data[0]["first_name"];
$scope.lastname = response.data[0]['last_name'];
$scope.email = response.data[0]['email'];
});
}
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:'id='+ id + '&first_name='+firstname+
'&last_name='+lastname+'&email='+email,
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
My view where i bind and post form data
<form name="editItem" class="form-horizontal">
<input ng-model="sid" type="hidden" placeholder="Name" name="name"
class="form-control" />
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">First
Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="firstname"
id="inputEmail3" placeholder="First name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Last
Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="lastname"
id="inputEmail3" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-
label">Email</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="email"
id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
<button type="submit" ng-disabled="editdata.$invalid"
class="btn btn-primary create-crud" data-dismiss="modal" ng-
click="saveEdit(sid,firstname,lastname,email)">Submit</button>
</div>
</div>
</form>
This is my codeigniter controller where i want to get form data
public function update_data(){
$requests = json_decode(file_get_contents('php://input'), TRUE);
$ids= array('id' =>$requests['id']);
echo json_encode($ids);
}
When i submit my form data will show null in my controller,so please help how to get form data in controller.
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:'id='+ id + '&first_name='+firstname+
'&last_name='+lastname+'&email='+email,
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
This should be like this:-
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:{"id": id,"first_name":firstname,
"last_name":lastname,"email":email}
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
Since the codeigniter code uses json_decode, the $http service should use a JavaScript object to post the data:
$scope.saveEdit = function(id,firstname,lastname,email) {
var url = 'http://localhost/Angular_demo/admin/index.php/welcome/update_data';
var data = {
id: id,
first_name: firstname,
last_name: lastname,
email: email,
};
$http.post(url, data
).then(function success(response){
console.log(response.data);
});
}
The AngularJS framework will automatically encode the JavaScript object as a JSON string.

dont refresh the page when you submit the form

hii guys im new to web programing and im creating a website
in this website i want to add a contact us form in the footer of the page like this
<form action="footer_contactus1.php" method="post">
<div class="row">
<div class="form-grope col-lg-4">
<label><span class="glyphicon glyphicon-user"></span>Name</label><br>
<input name="cuname" type="text" class="form-cotrol">
</div>
<div class="form-grope col-lg-4">
<label><samp class="glyphicon glyphicon-envelope"></samp>Email</label><br>
<input name="cuemail" type="email" class="form-cotrol">
</div>
<div class="form-grope col-lg-4">
<label><i class="glyphicon glyphicon-earphone"></i>Phone Number</label><br>
<input name="cutele" type="tel" class="form-cotrol">
</div>
<div class="form-grope col-lg-12">
<br>
<label><span class="glyphicon glyphicon-paste"></span>Message</label><br>
<textarea name="cumessage" class="form-cotrol" rows="6" style="width: 100%;" ></textarea>
</div>
<div class="form-grope col-lg-12">
<br>
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</form>
and when i click the submit button i want the php file to get executed so the inputs got inserted into the database
the php file
<?php
$pdo = new PDO('mysql:host=localhost;dbname=mywsite_db', 'root', '');
$req = $pdo->prepare('INSERT INTO message (id_message,nom,email,tele,message)
VALUES(null,?,?,?,?)');
$req->execute(array($_POST['cuname'],$_POST['cuemail'],$_POST['cutele'],$_POST['cumessage']));
header('Location: HomePage.php');
?>
i wanted this form to get submited without refreshing the page by ajax
i tried different tutorials and nothing worked can you plzz gives me the correct ajax script for my form so i can submit it to the php file and insert the data on the database then a message (alert) pop up telling me that the data has been inderted without refreshing the page plzz
<form action="footer_contactus1.php" method="post" id="myForm1">
...
</form>
<script type="text/javascript">
var frm = $('#myForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('The data has been inserted');
}
});
ev.preventDefault();
});
</script>

How to submit form on one page to a different page using ajax call in jquery

I have a page called page2.php. It has a form that allows you to search via jquery ajax call. The code is below. My question is, I have a different form on page1.php. How can I submit the form on page1.php to go to page2.php and have it execute the page2.php code below using the data from the form on page1.php? I know this is most likely simple, having a brain fart right now.
$(function() {
$.validate({
form: '#form_search',
validateOnBlur: false,
errorMessagePosition: 'top',
onSuccess: function(form) {
var formval = $(form).serialize();
var formurl = '/page2.php?a=search';
$('#form_results').html('<div class="form_wait_search">Searching, please wait...<br><img src="/images/search-loader.gif"></div>');
$.ajax({
type: 'POST',
url: formurl,
data: formval,
success: function(data){
var json = $.parseJSON(data);
$('#form_errors').html(json.message);
$('#form_results').html(json.results);
}
});
return false;
}
});
});
UPDATE
Here is the forms Im referring to.
On page1.php this is like a module on the right side bar. Just a form that I want to post to page2.php
<div class="scontent_box1">
<strong class="box_title"><i class="fa fa-search fa-flip-horizontal"></i> Find Locations</strong>
<form method="post" action="/page2.php">
<div class="form-group">
<label>Street Address</label>
<input type="text" class="form-control" name="ad" placeholder="Enter Street Address...">
</div>
<div class="form-group">
<label>City, State or Zip Code</label>
<input type="text" class="form-control" name="ct" placeholder="Enter City, State or Zip Code...">
</div>
<button type="submit" class="btn btn-default blue_btn">Search</button>
</form>
</div>
Now here is the form on page2.php that executes the ajax code above. I want page1.php to submit to page2.php and envoke the same jquery code above.
<div class="row no_gutters">
<div class="search_page">
<div id="form_errors"></div>
<form method="post" id="form_search">
<div class="form-group">
<label for="ad">Street Address<span class="reqfld">*</span></label>
<input type="text" class="form-control" data-validation="required" id="ad" name="ad" placeholder="Enter Street Address..." value="">
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="ct">City, State or Zip Code<span class="reqfld">*</span></label>
<input type="text" class="form-control input-sm" data-validation="required" id="ct" name="ct" placeholder="Enter City Name..." value="">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-xs-12">
<button type="submit" class="btn btn-default blue_btn btn-block">Search Locations</button>
</div>
<div class="col-md-8"></div>
</div>
</form>
</div>
<div id="form_results"></div>
</div>

Categories