I have a form, when i click on submit i dont want the page to refresh, thats why i added AJAX to achieve this as you can see. The problem is that its not working.
<form id="formFooter" action="" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<h3>Background Color</h3>
<input class="form-control" placeholder="(e.g. 00ff00)" type="text" name="backgroundColor">
<h3>Font Color</h3>
<input class="form-control" placeholder="(e.g. 00ff00)" type="text" name="fontColor">
<h3>Opacity</h3>
<input class="form-control" placeholder="(Pick a value between 0 and 1 e.g. 0.3)" type="text" name="opacity">
<br/>
<br/>
<button class="form-control" id="run" type="submit" name="submit">Generate footer</button>
</form>
<div id="showData"> </div>
<script type="text/javascript">
$('#run').on("click", function (e) {
var formData = new FormData($('#myForm')[0]);
$.ajax({
url: "script.php",
type: 'POST',
data: formData,
success: function (data) {
$('#showData').html(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
Here is the script.php:
<?php
function footerPreview ()
{
echo "<h3>Preview:</h3>";
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
//style
$backgroundColor = $_POST['backgroundColor'];
$fontColor = $_POST['fontColor'];
$opacity = $_POST['opacity'];
echo "<div id='generated_footer_date' style='background-color:$backgroundColor; color:$fontColor; opacity: $opacity; ' >$trademark $date $company </div>";
}
// generate result for the head
function rawHead()
{
$head = htmlspecialchars('<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Raleway:200" rel="stylesheet">
</head>',ENT_QUOTES);
echo "<pre><h4>Put this code inside your head tags</h4>$head</pre>";
}
// generate result for the body
function rawBody ()
{
$body1of5 = htmlspecialchars('<div id="footer_date">',ENT_QUOTES);
$body2of5 = $_POST["trademark"];
$body3of5 = date("Y");
$body4of5 = $_POST["companyName"];
$body5of5 = htmlspecialchars('</div>',ENT_QUOTES);
echo "<pre><h4>Put this code inside your body tags</h4>$body1of5 $body2of5 $body3of5 $body4of5 $body5of5 </pre>";
}
// generate result for the CSS
function rawCSS ()
{
$opacity = $_POST['opacity'];
$backgroundColor = $_POST['backgroundColor'];
$fontColor = $_POST['fontColor'];
echo
"<pre>
<h4>Put this code in your websites stylesheet</h4>
color:$fontColor;
background-color:$backgroundColor;
opacity:$opacity;
width:100%;
text-align:center;
padding-top:15px;
height:50px;
font-family: 'Raleway', sans-serif;
right: 0;
bottom: 0;
left: 0;
position:fixed;
</pre>";
}
// Generate eveything by one click
if(isset($_POST['submit']))
{
footerPreview();
rawHead();
rawBody();
rawCSS();
}
?>
When i click on submit nothing happens. I want the script.php to be generate on the same page without refreshing.
You can make it very simple your Ajax Request as:
First of all no need to use FormDate here, because you don't have any file input in your <form>, so you can use serialize() data in your request as:
var formData = $("#myForm").serialize();
Second, you are just printing the HTML in your PHP, it means you just need to print html, so you can use dataType=HTML here as:
dataType: "html",
Third, one more thing will help you in debugging, add print_r($_POST) in your script.php file at top and check the console.
Modified Request:
$(document).ready(function(){
$("#run").click(function(){
var formData = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "script.php",
data: formData,
dataType: "html",
success: function(response)
{
$('#showData').html(response);
},
beforeSend: function()
{
//any loader
}
});
return false;
});
});
Update:
From your comment: yeah it shows after submit. It shows this : Array
( [trademark] => [companyName] => [backgroundColor] => [fontColor] =>
[opacity] => ) – Kevin Aartsen 6 mins ago
Look at this array, you don't have submit in the result of $_POST so you have two options to change this:
1) You can use count() function for checking if(count($_POST) > 0).
2) Or you can use <input type='submit' name='submit'> instead of <button type='submit' name='submit'>
$(document).ready(function() {
$('#run').on("click", function (e) {
e.preventDefault();
alert('inside ajax call');
var formData = new FormData($('#myForm')[0]);
$.ajax({
url: "script.php",
type: 'POST',
data: formData,
success: function (data) {
$('#showData').html(data);
alert('ajax call success');
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form id="formFooter" action="" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<h3>Background Color</h3>
<input class="form-control" placeholder="(e.g. 00ff00)" type="text" name="backgroundColor">
<h3>Font Color</h3>
<input class="form-control" placeholder="(e.g. 00ff00)" type="text" name="fontColor">
<h3>Opacity</h3>
<input class="form-control" placeholder="(Pick a value between 0 and 1 e.g. 0.3)" type="text" name="opacity">
<br/>
<br/>
<button class="form-control" id="run" type="submit" name="submit">Generate footer</button>
</form>
<div id="showData"> </div>
try above code and remove alert when it works for you :)
Related
I Have a form in PHP. when I am clicking the submit button I want to take two actions at the same time. how do I do that?
<script>
function myfunction(){
$.ajax({
type: 'post',
url: 'merchants.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
}
</script>
<div class="stdFormHeader"> New Merchant Registration</div>
<form action="" method="POST">
<label class="stdFormLabel">Merchant name : </label><input class="stdFormInput" type="text" name="merchantName" required><br>
<!-- <label class="stdFormLabel">Business Type : </label><select class="stdFormSelect" name="shopMarket" required>-->
<!-- <option value="shop">Shop</option>-->
<!-- <option value="market">Market Place</option>-->
<!-- </select><br>-->
<label class="stdFormLabel">Contact Person : </label><input class="stdFormInput" type="text" name="contactPerson" required><br>
<label class="stdFormLabel">Contact Number : </label><input class="stdFormInput" type="text" name="contactNumber" required><br>
<label class="stdFormLabel">Address : </label><textarea class="stdFormInputBox" name="address"></textarea><br>
<input class="stdFormButton" type="submit" name="submit" onclick="myfunction()" value="Apply">
</form>
Just do a submit again:
function myfunction(){
$.ajax({
type: 'post',
url: 'merchants.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
$.ajax({
type: 'post',
url: 'OtherFunction.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted again');
}
});
}
This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
form.php
<form action="#" method="POST" enctype="multipart/form-data" style="textalign: center;">
<label class="label" for="Fromdate">From Date</label>
<input type="text" id="datepicker" class="textBox" name="fromDate" />
<label class="label" for="Todate">To Date</label>
<input type="text" id="datepicker1" class="textBox" name="toDate" />
<input type="submit" name="searchby" id="searchby" value="Search" class="buttonLarge" />
<input type="submit" name="excel" value="Export To Excel" class="buttonLarge" />
</form>
datediff.php
<?php
if(($_POST['searchby'] == 'Search')){
?>
<script type="text/javascript">
var fromDate = $("#datepicker").val();
var toDate = $("#datepicker1").val();
$.ajax({
type: "POST",
url: "datediff.php",
data: { fromDate,toDate },
cache: false,
success: function (html) {
}
});
</script>
<?php
}
?>
Wrong json { fromDate,toDate }.
And yes it will submit if we press enter. For submitting it through ajax we have to prevent default functionality through event.preventDefault().
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
search();
}
});
$('#searchby').click(function(e){
e.preventDefault();
search();
});
function search()
{
$.ajax({
type: "POST",
url: "datediff.php",
data: { 'fromDate':$('#datepicker').val(), 'toDate':$('#datepicker1').val() },
cache: false,
success: function (html) {
}
});
}
Hi would you like to help me. im a php newbie. I want to insert employment information in my database and hide da div where the form placed.
HTML:
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<form name="empform" method="post" action="profile.php" autofocus>
<input name="employ" type="text" id="employ" pattern="[A-Za-z ]{3,20}"
placeholder="Who is your employer?">
<input name="position" type="text" id="position" pattern="[A-Za-z ]{3,20}"
placeholder="What is your job description?">
<input name="empadd" type="text" id="empadd" pattern="[A-Za-z0-9##$% ]{5,30}"
placeholder="Where is your work address?">
<input name="empcont" type="text" id="empcont" pattern="[0-9]{11}" title="11-digit number"
placeholder="Contact number">
<input name="btncancel" type="button" class="btncancel" value="Cancel"
style="width:60px; border-radius:3px; float:right">
<input name="btndone" type="submit" class="btndone" value="Done" style="width:60px; border-radius:3px; float:right">
</form>
</div>
</div>
PHP:
if (isset($_POST['btndone'])) {
$employ = $_POST['employ'];
$position = $_POST['position'];
$empadd = $_POST['empadd'];
$empcont = $_POST['empcont'];
$empdate = $_POST['empdate'];
$empID = $alumniID;
$obj - > addEmployment($employ, $position, $empadd, $empcont, $empdate, $empID);
}
JS:
<script>
$(function () {
function runEffect() {
var selectedEffect = "highlight";
$(".toggler").show(selectedEffect);
};
function runDisplay() {
var selectedDisplay = "highlight";
$("#empdisplay").show(selectedDisplay);
};
$(".btncancel").click(function () {
$(".toggler").hide();
return false;
});
$(".btndone").click(function () {
runDisplay();
$(".toggler").hide();
return false;
});
}
</script>
Hi this is what I'll do
var request = $.ajax({
url: "profile.php",
type: "POST",
data: $('#form').serialize()
});
request.done(function(msg) {
$('#form').hide();
});
request.fail(function(jqXHR, textStatus) {
alert( "Form failed" );
});
If you have some doubts with Jquery's Ajax visit this link
If you don't understand what jqXHR is, I suggest you visit this link http://www.jquery4u.com/javascript/jqxhr-object/
Execute on click
$('#form').submit(function(){
var request = $.ajax({
url: "profile.php",
type: "POST",
data: $('#form').serialize()
});
request.done(function(msg) {
$('#form').hide();
});
request.fail(function(jqXHR, textStatus) {
alert( "Form failed" );
});
});
Try This
HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<form id="empform" name="empform" method="post" action="profile.php" autofocus>
<input name="employ" type="text" id="employ" pattern="[A-Za-z ]{3,20}"
placeholder="Who is your employer?">
<input name="position" type="text" id="position" pattern="[A-Za-z ]{3,20}"
placeholder="What is your job description?">
<input name="empadd" type="text" id="empadd" pattern="[A-Za-z0-9##$% ]{5,30}"
placeholder="Where is your work address?">
<input name="empcont" type="text" id="empcont" pattern="[0-9]{11}" title="11-digit number"
placeholder="Contact number">
<input name="btncancel" type="button" class="btncancel" value="Cancel"
style="width:60px; border-radius:3px; float:right">
<input id="submit"name="btndone" type="submit" class="btndone" value="Done" style="width:60px; border-radius:3px; float:right">
</form>
</div>
</div>
<script>
$(document).ready(function() {
//$("#form").prev
$('#submit').click(function(event) {
//alert (dataString);return false;
event.preventDefault();
$.ajax({
type: "POST",
url: 'profile.php',
dataType:"html",
data: $("#empform").serialize(),
success: function(msg) {
alert("Form Submitted: " + msg);
//alert($('#form').serialize());
$('div.toggler').hide();
}
});
});
});
</script>
</html>
PHP
profile.php
<?php
if (isset($_POST)) {
$employ = $_POST['employ'];
$position = $_POST['position'];
$empadd = $_POST['empadd'];
$empcont = $_POST['empcont'];
$empdate = $_POST['empdate'];
$empID = $alumniID;
$obj - > addEmployment($employ, $position, $empadd, $empcont, $empdate, $empID);
}
?>
Iam not sure about your fields
echo $empdate = $_POST['empdate'];
$empID = $alumniID;
they are not in form but works!...
You should do an ajax call to save your data and then hide the div, someting like this :
$('form[name="empform"]').submit(function(e) {
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$('div.toggler').hide();
});
});
Okay, I'll try to be as clear as I can with this.
I have a page with a team's roster that you can add and delete from. When you decide to add a player, you click the "Add Player" button which, using Jquery-UI, loads a dialog modal with a form. You can fill in the form and submit and it works great. I've also added a "Search" button that, when clicked, loads another modal that lets you search a DB of exists players. When it retrieves search results it loads them in an OL. Now this is where it gets tricky:
I would like to have a button called "Use player info" that, when clicked, closes the search modal and auto-fills the the form fields with the selected player's information.
Here is the code for the search modal:
Script (in the head):
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word==''){
} else {
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
HTML
<div id="search" align="center">
<div style="width:500px">
<div style="text-align:center; padding-top:10px" class="title">Player Search</div>
<div style="margin-top:20px; text-align:left">
<form method="get" action="">
<div style="margin:0; padding:0; float:left">
<input type="text" name="search" id="search_box" class='search_box'/>
</div>
<div style="margin:0; padding:0; float:left; padding-left:8px; font-size:16px">
<input type="submit" value="Search" class="search_button" />
</div>
</form>
</div>
<div style="width:480px; padding-left:10px; padding-right:10px;">
<div id="flash"></div>
<ol id="insert_search" class="update"> </ol>
</div>
</div>
</div>
Here is the php code for the actual search function:
<li><div id="all">
<div id="result"><div id="names"><div id="lnames"><?php echo $final_msg; ?></div><div id="fnames"> <?php echo $firstName ?></div></div><div id="dobs"><?php echo $DOB ?></div><div id="ids"><?php echo $ID ?></div>
<div id="add"><button type="button" id="add_player2" > Add Player </button></div></div>
</div></li>
And here is the code for the form modal I want he information to be put in:
<script>
$(function() {
$( "#search" ).dialog({
autoOpen: false,
width: 550,
modal: true,
resizable: false,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word=='')
{
}
else
{
$.ajax({
type: "GET",
url: "../../Search/searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<script>
$(function() {
$("#dialog-form").dialog({autoOpen:!1, height:380, width:350, modal:!0, buttons:{
"Search for Player":function() {
$( "#search" ).dialog( "open" );
},
"Add Player":function() {
$("#myForm").ajaxSubmit({success:function() {
window.location = ""
}});
$(this).dialog("close")
},
Cancel:function() {
$(this).dialog("close")
}
},
create:function () {
$(this).closest(".ui-dialog")
.find(".ui-button:contains(Search for Player)") // the first button
.addClass("green");
}});
$("#add-player").button().click(function() {
$("#dialog-form").dialog("open")
})
});
</script>
<div id="dialog-form" title="Add Player">
<form name="myForm" id="myForm" action="../../php/add_player_comp_script_test.php?id=<? echo $table ?>" method="post" enctype="multipart/form-data">
<fieldset>
<label for="last_name_add">Last Name</label>
<input type="text" name="last_name_add" id="last_name_add" class="text ui-widget-content ui-corner-all" />
<label for="first_name_add">First Name</label>
<input type="text" name="first_name_add" id="first_name_add" class="text ui-widget-content ui-corner-all" />
<label for="id_add">ID Number</label>
<input type="text" name="id_add" id="id_add" value="" class="text ui-widget-content ui-corner-all" />
<label for="jersey_add">Jersey Number</label>
<input type="text" name="jersey_add" id="jersey_add" value="" class="text ui-widget-content ui-corner-all" />
<label for="dob_add">DOB (YYYY-MM-DD)</label>
<input type="text" name="dob_add" id="dob_add" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
Thanks for any and all help!
I am assuming that this-
<li><div id="all">
<div id="result"><div id="names"><div id="lnames"><?php echo $final_msg; ?></div><div id="fnames"> <?php echo $firstName ?></div></div><div id="dobs"><?php echo $DOB ?></div><div id="ids"><?php echo $ID ?></div>
<div id="add"><button type="button" id="add_player2" > Add Player </button></div></div>
</div></li>
is the html in this success function-
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
If so, it would be better if you returned a json encoded array json_encode(), instead of html - eg.
[{"lname":"Jones","fname":"Joe","dob":"2000-01-13","id":"6"},
{"lname":"Jones","fname":"Jim","dob":"2001-04-04","id":"19"},
{"lname":"Jones","fname":"Bob","dob":"1999-10-23","id":"32"}]
php code on ../../Search/searchdata.php would be something like -
while($row = _fetched_array_) {
$players[] = array(
'lname' => $row['lname'],
'fname' => $row['fname'],
'dob' => $row['dob'],
'id' => $row['id']
);
}
// Return JSON Encoded Array
echo json_encode($players);
Then you can create links for each one, and on selecting the player it will add it to your form fields
success: function(html){
players = $.parseJSON(html); //create json array in format above
player_links = ''; // create blank variable
for (var i = 0; i < players.length; i++){ // loop through each of the returned players
// Echo Player First & Last Name and a link to add
player_links += '<li>' + players[i].lname + ' ' + players[i].fname + ' Add Player</li>';
}
$("#insert_search").show();
$("#insert_search").append(player_links);
$("#flash").hide();
// Bind .player_details click
$('.player_details').click(function () {
var pid = $(this).data('player');
$('#last_name_add').val(players[pid].lname);
$('#first_name_add').val(players[pid].fname);
$('#id_add').val(players[pid].id);
$('#dob_add').val(players[pid].dob);
$("#search").dialog("close");
});
}
I have created a simple example of this as a jsFiddle - http://jsfiddle.net/8jcLQ/
i have a newsletter form i use on my site using ajax with jquery. i want to show to a user a wait message.
what is the best option?
heres what i have so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
$.ajax({
type: "POST",
url: '/save.php',
data: $('#form').serialize(),
cache: false,
success: function(result) {
// my code when success
}
});
});
});
</script>
<div id="newsletter">
<form id="form">
<label for="email">Your Email*:</label>
<input name="email" value="" type="text" id="email" size="30" maxlength="255" />
<span id="submit">Submit</span>
</form>
</div>
thanks
Here's what you can do:
Create a div (message dialog) and show when the user press on submit and hides it when the ajax is completed.
I would also recommend to use the jQuery Validation plugin to validate the email.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
// validation
$.ajax({
type: "POST",
url: '/file.php',
data: $('#form').serialize(),
cache: false,
success: function(result) {
// do what ever you need
},
error: function (response, desc, exception) {
// alert some message
},
beforeSend: function() {
$('#loader').fadeIn(1000);
},
complete: function() {
$('#loader').fadeOut(1000);
},
});
});
});
</script>
<style type="text/css">
#loader { display: none; /* and other css youy need like border, position, etc... */ }
</style>
<div id="loader">loading ...</div>
<div id="newsletter">
<form id="form">
<label for="email">Your Email*:</label>
<input name="email" value="" type="text" id="email" size="30" maxlength="255" />
<span id="submit">Submit</span>
</form>
</div>
You can do it something like this.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
//Put the loding script here
$("#preloader").show();
$.ajax({
type: "POST",
url: '/save.php',
data: $('#form').serialize(),
cache: false,
success: function(result) {
// my code when success
//Stop the preloader if the process is done
$("#preloader").hide();
}
});
});
});
<div id="newsletter">
<form id="form">
<label for="email">Your Email*:</label>
<input name="email" value="" type="text" id="email" size="30" maxlength="255" />
<span id="submit">Submit</span>
<img src="preloader.gif" id="preloader" />
</form>
</div>
When the user hit the submit show your preloader image. After the process is done, hide it.