Submiting a form from a single page webapp using Ajax Call - php

Does anyone know about a good tutorial where submiting a form from a sing page is explained? I have a few page views in my html code and one of them is a form with three fields (Name, Email and Message) what I am trying to achieve is to submit the form data via Ajax without using a process.php directly.
This is the Form:
<section class="hidden" id="view-forms">
<header>
<button class="left arrow" data-vin="view-home" data-sd="sr">
<div class="label">All Contacts</div>
</button>
<h1>Message</h1>
<button class="right bold green" data-vin="view-done" data-sd="sl">
<div class="label">Send</div>
</button>
</header>
<div class="scrollMask"></div>
<div class="scrollWrap">
<div class="scroll">
<div class="content">
<input placeholder="Name" type="text" />
<input placeholder="Email" type="email" />
<textarea placeholder="Your Message" rows="5"></textarea>
</div>
</div>
</div>
</section>
This is the confirmation page after message has been sent:
<section class="hidden" id="view-done">
<header>
<h1>That's it!</h1>
<button class="right bold" data-vin="view-home" data-sd="popout">
<div class="label">Done</div>
</button>
</header>
<div class="scrollMask"></div>
<div class="scrollWrap">
<div class="scroll">
<div class="content">
<h2>Message sent!</h2>
</div>
</div>
</div>
</section>
Please, let me know if any of you have already implemented something like this. Thank you.

You could submit to the same PHP page. You just need an if statement to separate the code that generates the page from the code that submits your form. That being said, you should probably just create a second PHP script to handle the form submission. If you wanted to implement it using the if statement, I would add a piece of information to your GET/POST request which would be something like:
'formSubmission='+true
Okay, for the more details, look at this tutorial, it goes over the basics. In your case, try this (NOTE: I haven't tested any of this). Also, add an ID to each of the elements (I assumed they would be the same as your current name attributes and that the textarea would have the ID message).
function()submitForm(){
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var message = document.getElementById('message').value;
var requestData = 'name='+name+'&email='+email+'&message='+message+'&formSubmission='+true;
//I'm assuming that you're using a POST request (this depends on the length of the message
var AJAXObj = new XMLHttpRequest();
//don't forget to replace currentURL.php with the name of the page that will handle the submission
AJAXObj.open('POST', 'currentURL.php', true);
AJAXObj.setRequestHeader('Content-type','application/x-www-form-urlencoded');
AJAXObj.send(requestData);
AJAXObj.onreadystatechange = function (){
var AJAXObj = event.target;
if(AJAXObj.readyState == 4 && AJAXObj.status == 200){
var responseText = AJAXObj.responseText;
//things that you might want to do with your responseText
}
}
}
Now here's the PHP:
if(isset($_POST['formSubmission'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//code that handles the form data that has now been passed to PHP
}
Just a thought, don't submit to the same PHP page that you're currently on. Create a new file and paste the code into that. It'll be cleaner.

Related

How do I get the value of textarea that is created in while loop

I have the problem, that I can't access the value my textareas which are created in a while loop of php. I guess that they are not registered in the DOM. Same is for the button that is attached to it.
So I do know, that I have to access the button via jquery with the special event listener because of this dynamically creation. I get all the IDs that I need, but I am not able to get the value of the textarea, even that I can get its correct ID, as it somehow seems to be just empty.
As I can't post a php fiddle in here, here is an example of how it works.
include"connection.php";
$stuff="here is the query";
for ($n = 1; $n <= 13; $n++) {
$xy=$con->query($stuff);
while($row=mysqli_fetch_assoc($xy))
{
$value = $row['value'];
echo"<div id='$n' class='antworten'>$value<br>
<div id='notizcontainer$n' class='antwortcontainer'>Notizen:</div>
<div class='antwortcontainer' id='notizerstellen$n'>Notiz erstellen:<br>
<textarea id='notizfeld' class='textarea'></textarea><br>
<button id='absenden' class='notizabsenden'>Notiz absenden</button></div>
</div>";
}
}
jQuery:
$(document).on('click', '.notizabsenden', function(){ //do this bc its not registered and .click() is not working, also I need the click event on the button class to know on which button the event is going on
var parentid = $(this).parent().attr('id'); //get parentid of button
var notizid = $('#'+parentid).find('textarea').attr('id'); //find id of textarea of parent
var notiz = $('#'+notizid).val(); //this should give me the text of the textarea... but it returns empty/blank
console.log(notizcontainer); //this turns out correct
console.log(parentid); //this turns out correct
console.log(notiz); //this returns empty/blank as if the textarea has nothing in it... which it does
The issue is because the HTML in your PHP loop is re-using the same id for multiple elements when they have to be unique. To fix that problem, remove the id attributes from all repeated content.
To address the issue of accessing the textarea content, you need to use DOM traversal to find the textarea related to the button which was clicked. To do that you can use a combination of closest() and find(), like this:
$(document).on('click', '.notizabsenden', function(e) {
const $btn = $(e.currentTarget);
const notiz = $btn.closest('.notizerstellen').find('.notizfeld').val();
console.log(notiz);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<!-- generated by your PHP loop... -->
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Lorem ipsum</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Dolor sit</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Amet consectetur</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>

How do I change a CSS Style attribute once a condition is met? PHP, JS, CSS

Good Day!
I am having a difficulty when it comes to showing a pop-up box in my webpage. I would like to show it when it meets a certain condition inside my php code, which is under the Condition.php. I have included the js file, which removes a certain class to make the box visible. How would I execute the JS code inside the Condition.php when it meets a certain condition?
Here are my codes:
Condition.php
<?php
// Defined variables and additional codes section
if (strlen($str) == 4) {
// Show the popup box
}
// Additional Codes
?>
ConfirmCheck.js
$(document).ready(function () {
$('#confirm').click(function () {
$('.popup').removeClass("hide");
});
});
Check.php
<form class="frm" action="Condition.php" method="POST">
// Additional Codes here
<input type="submit" name="checkOutBtn" value="CONFIRM" id="confirm">
</form>
<?php include 'box.php';?>
<script src='ConfirmCheck.js'></script>
Box.php
<div class="popup hide" id="popupID">
<div class="box">
<div class="form">
<h1>SUCCESS!</h1>
<form action="home.php">
<div class="form-group">
<p class="paragraph">
Your order has been successfully placed!
</p>
<button class="homepageBtn" onclick="home.php">GO TO THE HOME PAGE</button>
</div>
</form>
</div>
</div>
</div>
To do what you require simply put the if condition inside box.php and remove condition.php as it serves no purpose having an entire PHP page for a single condition.
box.php
<div class="popup <? if (strlen($str) != 4) { ?>hide<? } ?>" id="popupID">
<div class="box">
<div class="form">
<h1>SUCCESS!</h1>
<form action="home.php">
<div class="form-group">
<p class="paragraph">
Your order has been successfully placed!
</p>
<button class="homepageBtn" onclick="home.php">GO TO THE HOME PAGE</button>
</div>
</form>
</div>
</div>
</div>
I guess the problem is that you've set the action of your form to Condition.php but included the box design and code on check.php.
Note that #confirm is and input of type submit so after its pressed it will redirect you to the page specified at the action of the form.
I can suggest two possible fixes to that:
[least suggested] display the confirmation box on the Condition.php page
[most suggested] use AJAX!
The first fix requires you to move the markup and styles for box to the Condition.php file and design a whole confirmation/post action page
The second fix is better because by sending the Data to the server using AJAX you're not only going to stay on the same page (check.php) but you can also sort of hide the address to Condition.php which is supposed to be a backend file(from what i understood)
The structure should look something like this:
check.php:
<div class="frm">
// Additional Codes here
<buttin name="checkOutBtn" id="confirm">CONFIRMM</button>
</form>
<?php include 'box.php';?>
<script src='ConfirmCheck.js'></script>
ConfirmCheck.js:
$(document).ready(function () {
$('#confirm').click(function () {
// code to get all of your fields and put them in a js object: FDATA
$.ajax({type:'POST', url:'Condition.php', data: FDATA,
success:function(){
$('.popup').removeClass("hide");
}});
});
});
Condition.php:
<?php
// Defined variables and additional codes section
if (strlen($str) == 4) { //success
echo "success message";
}else{ // failed
header('HTTP/1.0 400 Bad Request');
die("bad request");
}
// Additional Codes
?>
The request goes back and forth between check.php and Condition.php in the background and your code gets notified through a callback whether or not to show the box.

Firefox saves password but chrome not saving password for login form

For my login form firefox saves but chrome not prompting the "save password" box. I have tried by adding autocomplete="on" but it is not working. Can any one suggest me the answer. I didn't want to use any extention.My code is given below.
<form spellcheck="false" autocomplete="on" id="login-form" action="/user/login/do-login" method="post">
<div class="separator-bar"></div>
<div class="credentials-container">
<div class="username-container">
<div class="label">Email/Username: </div>
<div class="field">
<input class="wx-input" type="text" name="<?php echo $this->escape(App_Api_User::ARG_USERNAME)?>" value="<?php if(isset($this->username)) {echo $this->username;}?>" spellcheck="false"/>
</div>
</div>
<div class="password-container">
<div class="label">password: </div>
<div class="field">
<input class="wx-input" type="password" name="<?php echo $this->escape(App_Api_User::ARG_PASSWORD)?>"/>
</div>
</div>
</div>
<div class="separator-bar bottom"></div>
<div class="forgot-password-container">
<div class="text">forgot password: </div>
<div class="password-page button"><a class="loginForgotPassword" href="#">CLICK HERE</a></div>
</div>
<div class="submit-container">
<input class="login button disabled" type="submit" name="submit" value="GO" />
</div>
<div id="infoMessageContainer">
</div>
<div class="general-error"></div>
</form>
$('body').on('click', '.submit-container .login', function(e) {
if ($(this).hasClass('disabled')) {
e.preventDefault();
e.stopPropagation();
}else{
var self = this;
self.submit();
}
});
_success: function()
{
window.location.href = '/user';
}
All browsers use heuristics for knowing when to save passwords. I'm familiar with Firefox and Chrome. The heuristic they use seems to be:
The form must have a password field
The text input just before the password field is assumed to be the user name
Only those two input fields are saved. Firefox then prompts you that
it can remember your changed password when you fill out a form with two password fields.
Here is a list of things that I typically see break these algorithms:
Sites that use autocomplete=off (specifically requesting that
browsers not remember passwords)
Separating login into multiple pages where the user name is entered on one page and the password is entered on the next.
Using Javascript to copy the contents of these fields into hidden
fields in a hidden form and then submitting the hidden form rather
than the visible form
Requiring more than two fields to be filled out such as
User name, SSN, and password
Username, password, and PIN
Changing the names of the username and password fields
periodically (causes firefox to no longer be able to fill in the
password, even when it is remembered).
I have made lots of changes and then finally works with below block of code.
Hope it will help someone. You need to submit form with this code.
var winNav = window.navigator,
isIOSChrome = winNav.userAgent.match("CriOS");
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
//Use below if statement, if you want to run only in chrome
if(isChrome || isIOSChrome){
$('#login-form').submit(function () {
if(-1 !== this.action.indexOf('/login')) {
var jForm = $(this);
$.post(this.action, $(this).serialize(), function (data) {
if (data.success == true) {
jForm[0].action = '/user';
jForm.submit();
}
});
return false;
}
});
}

Appending content to page right after database submit

<div class="accordion" id="accordion2">
<?php $info= mysql_query("SELECT id, title, description FROM event"); ?>
<?php while ($row = mysql_fetch_array($info, MYSQL_NUM)): ?>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse<?php print $row[0]; ?>"><?php print $row[1]; ?></a><span class="delete" id="<?php print $row[0]; ?>">×</span>
</div>
<div id="collapse<?php print $row[0]; ?>" class="accordion-body collapse">
<div class="accordion-inner">
<div class="row-fluid">
<div class="span6">
<?php print $row[2]; ?>
</div>
<div class="span6 ppl">
<ul>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
I have a pretty simple way of printing out my twitter bootstrap accordion.
I have this displayed on my page and I also have a form on top of the accordion itself from where I can submit another one into the database using ajax. Here is the form:
<form class="form">
<fieldset>
<legend>Stuff</legend>
<input class="class1" type="text" placeholder="xx">
<input class="class2" type="text" placeholder="xx">
<input class="class3" type="password" placeholder="xx">
<textarea maxlength="320" rows="5" class="class4" placeholder="xx"></textarea>
<div class="submit btn">Add</div>
</fieldset>
</form>
Here is the jQuery:
$(".form .submit").bind("click", function() {
var title = $(".form input.class1").val();
var email = $(".form input.class2").val();
var stuff1 = $('.form input.class3').val();
var stuff2 = $('.form textarea.class4').val();
if (title && email) {
var data = {title: title, email: email, stuff1: stuff1, stuff2: stuff2};
$.post("action.php", data, function() {
$(".form input, .form textarea").val("");
alert('done');
});
}
else {
alert('something went wrong');
}
});
And finally my action.php file:
<?php require('access.php');
if ($_POST['title'] && $_POST['email']) {
$title = $_POST['title'];
$email = $_POST['email'];
$stuff1 = $_POST['stuff1'];
$stuff2 = $_POST['stuff2'];
mysql_query("INSERT INTO events (title, email, stuff1, stuff2) VALUES('$title', '$email', '$stuff1', '$stuff2')");
}
Everything works, but like the title says, I want the information entered to be prepended to the accordion div as a new accordion group (without refreshing the page). My brain refuses to work with me on this, since to me it seems that if I submit the values, I have to make another request to the database to get the freshly generated id of the new event to have my accordion layout working.
Wat do?
And sorry for using a deprecated way of using mysql :O
So mysql functions aside, all you are looking to do is to prepend some html to an element. You already have a callback function on your post and so all you need to do is to make it actually do something i.e.
$.post('action.php', data, function() {
var newID = 123; // get this from the response text
$('div.accordion-inner').prepend('<div class="row-fluid"><div class="span6">'+newID +'</div><div class="span6 ppl"><ul></ul></div></div>');
});
This will attempt to prepend the div as specified to div.accordion-inner
Just replace the prepended with whichever html you are looking for.
And as an additional note, http://php.net/manual/en/function.mysql-insert-id.php will get you the PRIMARY KEY value for the last INSERT performed on your MySQL connection

Linking page in a div with html forms and php

So I have this html code
<div id="wrap">
<div id="header">
</div>
<div id="content">
<form method="POST" action="code.php">
Name:
<input type="text" name="name" size="50">
<input type=submit value="Get Code">
</form>
</div>
<div id="footer">
</div>
Is it possible to load the code.php after the user clicks submit into the #content div?
Essentially, what I want is when the user clicks the submit button, the code.php after processing is loaded onto the same #content div.
So let say in my code.php, after processing the inputted data, I come up with this lilne of code,
<?php
some processing code here;
$name = 'john';
echo $name;
?>
So then after hitting submit, user would see
<div id="content">
john
</div>
Hope I didn't complicate my question by repeating myself, please let me know if this is possible with javascript, php or whatever.
Thanks for the read!
#JohnP yes, $.load is a good solution. However, you'll need to send the form data in the request:
UPDATED [3] for sending a POST with multiple fields and checkboxes:
$('form').submit(function(){
// create an object to send as a post
var form = this,
fields = form.elements,
el,
post = {};
for (var i = fields.length; i--; ) {
el = fields[i];
if (el.name) {
switch (el.type) {
case 'checkbox':
case 'radio':
post[el.name] = (el.checked) ? el.value : '';
break;
default:
post[el.name] = el.value;
}
}
}
// send the form data in the load request...
$('#content').load(this.action, post);
return false;
});
This will send the data as a POST.
Since you've tagged jQuery, I'll use a jQuery example
$(document).ready(function(){
$('form').submit(function(){
$('#content').load('code.php');
return false;
})
})
This makes a couple of assumptions here
This assumes that code.php is in the same path that you are in now.
There is only one form in the page.
As #johnhunter points out, this example obviously won't work with post. You can send the post data along with the method. See here for usage : http://api.jquery.com/load
EDIT
Here's a fiddle example : http://jsfiddle.net/jomanlk/J4Txg/
It replaces the form area with the content from jsfiddle/net/echo/html (which is an empty string).
NOTE 2 Make sure to include the code in $(document).ready() or include it at the bottom of the page. It goes without saying you need jQuery in your page to run this.
You might want to check out jquery form plugin http://jquery.malsup.com/form/#
in simple way use
<div id="content">
if(isset($_POST['submit'] && !empty($_POST) )
{
// do your all post process
$name ='John';
echo $name;
}
else {
<form method="POST" action="$_SERVER['PHP_SELF']">
<label for="uname" >Name:</label><input type="text" name="uname" id="uname" size="50">
<input type=submit value="Get Code" name="submit">
</form>
}
</div>

Categories