Page gets reloaded in ajax - javascript

I'm trying to build a subscribe form.
The problem is that the page gets redirected, and the data doesn't get entered into db,
page gets redirected to
http://localhost/xampp/MY/SUB_FOLDERS/includes/parse.php?subscriber=sid%40patel&subscribe=subscribe
HTML CODE
<div id="subsc">
<form class="navbar-form navbar-right" action="includes/parse.php" mathod="post">
<div class="form-group">
<input type="email" placeholder="Email" class="form-control" name="subs" id="subs" required="required">
</div>
<input type="submit" class="btn btn-success" name="subscribe" id="subscribe" value="subscribe">
</form>
</div>
Ajax code:
<script type="text/javascript">
$(document).ready(function(){
$("#subscribe").click(function(){
username=$("#subs").val();
$.ajax({
type: "POST",
url: "includes/parse.php",
//data:dataString,
success: function(html){
if(html=='true')
{
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
}
else
{
$("#subsc").html("Error in subscribing");
}
},
});
return false;
});
});
</script>
PHP script for inserting data to database:
<?php include("connect.php");
if (#$_POST['subs']) {
$subscriber = mysql_real_escape_string(strip_tags($_POST['subs']));
$sendmessage = mysql_query("INSERT INTO subscriber VALUES('','$subscriber',now())");
echo 'true';
}
?>
PS: Name of rows in subscriber id, email, datetime

I guess there is one simpler approach here using your existing code itself...Instead of these lines:
$("#subscribe").click(function(){
username=$("#subs").val();
Use these lines:
$("#subscribe").click(function(e){
e.preventDefault();
. e.stopPropagation();
username=$("#subs").val();
This should stop the form post back even for submit button.
Hope this helps.

Add an id on your form:
<form id="myform" class="navbar-form navbar-right" action="includes/parse.php" method="post">
Change your Javascript to:
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit(function(event){
username=$("#subs").val();
$.ajax({
type: "POST",
url: "includes/parse.php",
//data:dataString,
success: function(html){
if(html=='true')
{
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
}
else
{
$("#subsc").html("Error in subscribing");
}
},
});
event.preventDefault();
});
});
</script>
This will prevent the default action of the form to submit the data and the apparent redirect. Also by handling the form's submit event you also handle the situation where the form may be submitted by other means.

First bind your subscribe button to a click event and Remove attribute action="includes/parse.php"
<input type="button" class="btn btn-success" name="subscribe" id="subscribe" value="subscribe">
jQuery('#subscribe').click(function(){
jQuery.ajax({
url:'YOUR URL',
type:'POST',
data:'subsribe=true&email='+jQuery('#subs').val(),
success:function(data){
if(data == 'true')
{
//enter code here
window.location.reload(true);
}else{
//enter code here
alert(data);
}
}
});
});
SERVER SIDE
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
if(isset($_POST)){
$subscriber = mysql_real_escape_string(strip_tags($_POST['subscriber']));
$query = "INSERT INTO subscribers('email','timestamp') VALUES('$subscriber',NOW())";
$sendmessage = mysql_query($query) or die(mysql_error());
echo 'true';
}
}

The simplest thing to do would be changing the type of your #subscribe element to button instead of submit.
<div id="subsc">
<form class="navbar-form navbar-right" id="SubsForm">
<div class="form-group">
<input type="email" placeholder="Email" class="form-control" name="subscriber" id="subs" required="required">
</div>
<input type="button" class="btn btn-success" id="subscribe" value="subscribe">
</form>
</div>
And JavaScript -
<script type="text/javascript">
$(document).ready(function(){
$("#subscribe").click(function(){
$.ajax({
type: "POST",
url: "includes/parse.php",
data:$('#SubsForm').serialize(),
success: function(html){
if (html=='true') {
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
} else {
$("#subsc").html("Error in subscribing");
}
},
});
});
});
</script>
More about $().serialize can be found here - http://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded
notation. It can act on a jQuery object that has selected individual
form controls....

Related

submit form button trigger when secondary button clicked

I'm trying to get a check box to trigger the submit button in a form. Basically, this is a touch screen game that takes users emails using a touch keyboard. The Enter button on the touch keyboard is what switches into the game. When I add document.getElementById("").submit in the javascript just resets everything. What I've done to try and work around this is to put a button next to it that is like an "opt-in" type of deal. When you click the button it copies the email address into the form. But I still need the submit button on the form to click without resetting the site or not updating the data.txt where the form info goes.
<body>
<script>
function myFunction() {
var x = document.getElementById("name").innerHTML;
document.getElementById("demo").innerHTML = x;
}
</script>
<span id="name">
<!-- Displaying name input from touch keyboard here -->
</span>
<form method="post" class="emailForm" id="demo" name="myForm">
<input type="text" name="subscriptions" id="formName"><br>
<input type="submit" name="mySubmit" id="submitBtn">
</form>
<div class="roundedB">
<input onclick="myFunction()" type="checkbox" value="None" id="roundedB" name="Submit" />
<label for="roundedB"></label>
</div>
</body>
<?php
if(isset($_POST['subscriptions']))
{
$data=$_POST['subscriptions'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
?>
What I want to achieve is to click the check button, the form fills and auto-submits to data.txt. Website does not reload.
Drat - started this before the noticing an accepted answer but will post this anyway as it might help.
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* This is where you would process the POST request somehow... */
$_POST['response']=date( DATE_ATOM );
$_POST['ip']=$_SERVER['REMOTE_ADDR'];
/* prepare data for saving */
$json=json_encode( $_POST );
/* write to file */
$file=__DIR__ . '/subscriptions-data.txt';
file_put_contents( $file, $json . PHP_EOL, FILE_APPEND );
/* send back a response of some sort to the ajax callback function */
exit( $json );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>submit form button trigger when secondary button clicked</title>
<script>
document.addEventListener( 'DOMContentLoaded', function(){
const xhr_callback=function(r){
console.info( r );
};
const ajax=function(url,payload,callback){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( this.status==200 && this.readyState==4 )callback( this.response );
}
xhr.open( 'POST', url, true );
xhr.send( payload );
};
const clickhandler=function(e){
if( this.checked ){
let payload=new FormData( document.forms.myForm );
ajax.call( this, location.href, payload, xhr_callback );
}
};
document.querySelector('input[type="checkbox"][name="submit"]').addEventListener( 'click', clickhandler );
});
</script>
</head>
<body>
<span id='name'>
<!-- Displaying name input from touch keyboard here -->
</span>
<form method='post' class='emailForm' name='myForm'>
<input type='text' name='subscriptions' value='geronimo#hotmail.com' />
<br />
<input type='submit' />
</form>
<div class='roundedB'>
<input type='checkbox' value='None' name='submit' />
<label for='roundedB'></label>
</div>
</body>
</html>
You can try with something like this
As you can see I used Jquery for that. You can make a trigger on change.
Then to send ajax request to server.
$('#myCheck').on('change',function() {
// ajax request
alert('Do your action');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Check me <input type="checkbox" id="myCheck">
Simple ajax
$('#myCheck').on('change', function() {
var data = JSON.stringify({
email: $('input#email').val()
});
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
Email: <input type="text" id="email" value="someone#email.com">
</form>
<form id="form2">
Check me <input type="checkbox" id="myCheck">
</form>
This one will give you error in alert, because there is not email.php file.
Here is code you need for that
index.php
$('#roundedB').on('change', function() {
var email = $('input#subscriptions').val();
$.ajax({
type: "POST",
data: {
'subscriptions': email
},
url: 'send.php',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<span id="name">
<!-- Displaying name input from touch keyboard here -->
</span>
<form method="post" class="emailForm" id="demo" name="myForm">
<label for="subscriptions">Email address</label>
<input type="text" name="subscriptions" id="subscriptions"><br>
</form>
<div class="roundedB">
<input type="checkbox" id="roundedB" name="Submit" />
<label for="roundedB"></label>
</div>
</body>
send.php
<?php
if(isset($_POST['subscriptions']))
{
$data=$_POST['subscriptions']."\n";
$fp = fopen('data.txt', 'a');
if(fwrite($fp, $data)){
print 'successful';
}else{
print 'error';
}
fclose($fp);
}

PHP - Submit button and get value without refresh

Hello I want to get the value of this input and fetch it using ajax no database at all. thank you. how can i do it with ajax?
<form method="POST">
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</form>
there is my inputs and here is the button.
<form action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt" onchange = "change()"></textarea><br><br><br>
<input class="btn btn-primary btn-lg" type="submit" name="btnSubcode" value="PROCESS"></input>
</div>
</div>
</div>
</div>
</form>
so the final output sould not refresh the page and the textarea value will be send to the textbox
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process.
http://malsup.com/jquery/form/#getting-started
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>
// prepare Options Object
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
};
// pass options to ajaxForm
$('#myForm').ajaxForm(options);
Firstly, rewrite your html code as below:
<form id="form" action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
<input class="btn btn-primary btn-lg js-form-submit" type="submit"></input>
</div>
</div>
</div>
</div>
</form>
Then, you can write JS something like this:
$(document).on('click','.js-form-submit', function (e) {
e.preventDefault();
var formData = $('#form').serialize();
var url = $('#form').attr('action');
$.ajax({
type: "POST",
cache: false,
url: url // Your php url here
data : formData,
dataType: "json",
success: function(response) {
//var obj = jQuery.parseJSON(response); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handling here');
}
});
});

Submit a form with a file without refresh

Hello guys i don't know to submit a form without page refresh.
This is my code:
My form:
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="submit" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Javascript:
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
How i can modify my code to submit along with text a file towards the mysql db?
Your first issue is in this line:
<button type="submit" name="action" ... />
You have two possibilities:
change type="submit" to type="button"
use event.preventDefault() in your $("#sendbutton21").click(function() {
After, your ajax call can be changed in order to include the file:
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'POST',
processData: false,
success: function(data) {
alert(data);
}
});
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
// for testing...
url = 'https://api.github.com/repositories';
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'GET',
processData: false,
success: function (data) {
console.log(data[0].id);
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="button" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Try https://jquery-form.github.io/form/ plugin to easily send form via ajax sample code:
$('#post123').ajaxForm(function() {
// SUCCESS CALLBACK
});
To submit a form without refresh, use event.preventDefault().
$("#sendbutton21").click(function(event) {
event.preventDefault();
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Instead of
$("#sendbutton21").click(function() {
use
$("#post123").submit(function() {

How to submit a form with input image into modal Bootstrap?

I have a modal form using bootstrap. The form contains some text inputs and a image input.
I submit the form with ajax, and all data is received at the PHP file correctly. Alas, the image isn't being uploaded.
What is my code problem?
<script>
$(document).ready(function () {
$("input#submit").click(function(){
$.ajax({
type: "POST",
url: "insert.php",
data: $('form.contact').serialize(),
success: function(msg){
$("#th").html(msg)
$("#form-content").modal('hide');
$("#pro").html(content);
},
error: function(){
alert("failure");
}
});
});
});
</script>
The form:
<form class="contact" name="contact" enctype="multipart/form-data">
<label for="inputNombre" class="sr-only">Título</label>
<input id="inputNombre" name="inputNombre" class="form-control" placeholder="Título" required="TRUE" autofocus="" type="text">
<br>
....
<div class="upload_pic1 inline">
<input id="imagen" name="imagen" type="file">
</div>
<div class="modal-footer">
Cerrar
<input id="submit" class="btn btn-success" type="submit" value="Crear">
</div>
</div>
</form>
EDIT:
insert.php
<?php
session_start();
if (!isset($_SESSION["name"]) && $_SESSION["name"] == "") {
// user already logged in the site
header("location: Login.html");
}
require_once('funt.php');
conectar('localhost', 'root', '', 'db');
if (isset($_POST['inputNombre'])) {
$nombre = strip_tags($_POST['inputNombre']);
....
//Here the var imagen
if(is_uploaded_file($_FILES['imagen']['tmp_name'])){
$rutaEnServidor='imagenes';
$rutaTemporal=$_FILES['imagen']['tmp_name'];
$nombreImagen=$_FILES['imagen']['name'];
$rutaDestino=$rutaEnServidor.'/'.$nombreImagen;
move_uploaded_file($rutaTemporal,$rutaDestino);
} else { //Always enter here, so is not uploaded
$rutaEnServidor='imagenes';
$rutaTemporal='/noPicture.png';
$rutaDestino=$rutaEnServidor.'/noPicture.png';
move_uploaded_file($rutaTemporal,$rutaDestino);
}
...
How can I change this and upload the picture with all data in form?
You can use FormData interface. Then you have to tell jQuery not to set content type, nor process data.
Check compatibility table for the FormData constructor first. It might suffice.
Otherwise read through this discussion, How can I upload files asynchronously?.

Repopulating div with new form/content using jQuery/AJAX

Are there any jQuery/AJAX functions that when a form (or anything for that matter) is displayed, upon pressing a button the div containing the original form is replaced by a new form? Essentially, a multi-part form without having to reload the page.
Can I use something like this?
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
//somehow repopulate div with a second form?
}
})
return false;
});
I've used this before for adding items to a list, but I've never used it to totally repopulate it with different content. How can I direct it to the second form?
edit - I got it to work, but only when I write '#form2' for the replacement. I alerted the response and I get {"formToShow":"show2"}. I tried doing response.formToShow but it's undefined.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
<div id="divName">
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1" value="1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2" value="2"/>
<input type="submit" name="submit2"/>
</form>
</div>
<script>
$('form#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'JSON',
url: 'receiving.php',
data: $(this).serialize(),
success: function(response) {
$('#form1').hide(); //hides
//$('#form2').show(); //this will show
$(response.formToShow).show(); //this does not display form 2
}
})
return false;
});
</script>
Here is receiving.php. When I view this page {"formToShow":"show2"} is displayed
<?php
echo json_encode(array("formToShow" => "#form2"));
?>
Check the JQuery Load Function
This is personal preference, but I'd never send HTML through the response and display it like that, what I'd do is:
Send a JSON array back from the server, such as { formToShow: "#form1" }
Then you can simply do this:
success: function(response) {
$('form').hide();
$(response.formToShow).show();
}
Obviously, using this method, you'd also have to have the second form in your markup like this:
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>
You'd also have to change (to pickup the array):
$.ajax({
type: 'JSON'
try this
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
$('#form1').hide();
$('#form2').show();
}
})
return false;
});
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="dispay:none;">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>

Categories