Submit page but dont refresh - php

I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<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" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
I heard this is possible with ajax, but i have no idea how in this case i already tried to look on the internet..

if you have a type="submit" inside a form, it will submit the form by default. Try to use <input type="button" instead. Then you can use ajax on the button action, that will run without refreshing the page.
Here's an example of how to use ajax:
function sendAjax() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$(".result").html(JSON.stringify(data))
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="button" onclick="sendAjax()" value="callAjax" />
<div class="result"></div>
</form>

Add
return false;
to your jQuery-function at the end. With this you can avoid the submit.
Then you need to add an ajax-function, which sends the data from your form to the php-script you already use.
This is just an example:
$.ajax({
url: "YOUR-PHP-SCRIPT"
}).done(function (content) {
// ADD HERE YOUR LOGIC FOR THE RESPONSE
}).fail(function (jqXHR, textStatus) {
alert('failed: ' + textStatus);
});

So you have to do $.ajax post request to the php. Something like this:
<script>
$('.form-control').click(function() {
$.post(url, {data}, function(result) {
footerPreview();
}, 'json');
});
</script>
So footerPreview will be called when your php returns result.

//add in javascript
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
$("button.form-control-generate").show();
}

you can create an index.php:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" id="tm">
<option val=""></option>
<option val="©">©</option>
<option val="™">™</option>
<option val="®">®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" id="cn" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit" id="generate">
Generate
</button>
</form>
<div class="output" id="output">
</div>
<script type="text/javascript">
$('#generate').on('click', function(e){
e.preventDefault();
var companyname = $('#cn').val();
var trademark = $('#tm').val();
$.ajax({
url: 'process.php',
type: 'post'.
data: {'company':companyname,'trademark':trademark},
dataType: 'JSON',
success: function(data){
$('#output').append("<div id='footer_date'>"+data.trademark + " " + data.date + " " + data.company + " </div>");
},
error: function(){
alert('Error During AJAX');
}
});
})
</script>
and the process.php:
<?php
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["company"];
$date = date("Y");
$array = array(
'trademark' => $trademark,
'company' => $company,
'date' => $date
);
echo json_encode($array);
?>
Be sure that the index.php and the process.php will be under the same folder.. ex.public_html/index.php and public_html/process.php

Related

Post form with ajax tab loading

I have a page with a POST form, when I submit the form the details are updated in a database.
And I have another page where I use AJAX TAB, which means I load the first page with AJAX, when I do this and use the Form, the details are not updated in the database.
I would appreciate help.
<?php
if( isset($_POST['newcst']) )
{
/*client add*/
//getting post from user add form
$c_name = $_POST['c_name'];
$c_adress = $_POST['c_adress'];
$c_idnum = $_POST['c_idnum'];
$c_phone = $_POST['c_phone'];
$c_mail = $_POST['c_mail'];
echo $c_num;
//insert client into SQL
$wpdb->insert('se_clients',array(
'c_name' => $c_name,
'c_adress' => $c_adress,
'user_id'=>$cur_id,
'c_num'=>$c_idnum,
'c_phone'=>$c_phone,
'c_mail'=>$c_mail,
));
}
?>
<html>
</head>
<body>
<div id="newcst">
<form action="" method="post">
<label>Full name:</label>
<input type='text' name='c_name' /><br><br>
<label>ID: </label>
<input type='text' name='c_idnum' /><br><br>
<label>PHONE:</label>
<input type='text' name='c_phone' /><br><br>
<label>ADRESS: </label>
<input type='text' name='c_adress' /><br><br>
<label>EMAIL: </label>
<input type='text' name='c_mail' /><br><br>
<input name="newcst" type="submit" value="create">
</form>
</div>
</body>
</html>
Ajax tab:
$(document).ready(function() {
$("#nav li a").click(function() {
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$("#nav li a").removeClass('current');
$(this).addClass('current');
$.ajax({ url: this.href, success: function(html) {
$("#ajax-content").empty().append(html);
}
});
return false;
});
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$.ajax({ url: 'invoice', success: function(html) {
$("#ajax-content").empty().append(html);
}
});
});
hover(), click(), bind(), on() and others works only after reloading page.
So you can use live()
or
$(document).on('click', 'element', function () {
...
});
I found the solution, you need to add the PHP code that is responsible for entering data to the database on the main page that contains the AJAX and not the page with the form itself.

submit button refreshing page

I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<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" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
If you don't want to post the form you can use the preventDefault(); function.
$("button.form-control").click(function(event) {
event.preventDefault();
$("button.form-control-generate").show();
});
$("button.form-control").click(function(event) {
event.preventDefault();
setTimeout(function(){$("button.form-control-generate").show();},100);
});
Try It Once
Submit your form as
$('.form').on('submit', function(e){
$("button.form-control-generate").show();
e.preventDefault();
this.submit();
})
instead of using the click event. With button of type submit the submit() action is triggered automatically so you can show your button in the submit handler and then prevent the default action to refresh the page.
UPDATE:
Instead of using php you can do the same with jquery as well.
$('.form').on('submit', function(e){
e.preventDefault();
var date = new Date();
date = date.getYear() + 1900;
var data = $(this).serializeArray();
var str = data[0].value + date + data[1].value;
$('#output').text(str);
$('.form-control-generate').show();
})
.form-control-generate {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<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" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output"></div>
#ShubhamKhatri almost had it right
The problem is, he thought this was an on submit event, I don't believe it should be. I believe you have the type="submit" on the wrong button. Surely preview wouldn't submit the form? You want to submit on generate, no?
so a slight change to the markup - added an id to preview to make life simple
<button class="form-control" id="preview">
Preview
</button>
<br/>
<button class="form-control-generate" type="submit" name="submit">
Generate
</button>
and a slight modification to the code in #ShubhamKhatri answer
$("#preview").click(function(e) {
e.preventDefault();
var date = new Date();
date = date.getYear() + 1900;
var data = $('.form').serializeArray();
var str = data[0].value + ' ' + date + ' ' + data[1].value;
$('#footer_date').text(str);
$('.form-control-generate').show();
});
et voilà

Passing variable data between jQuery and PHP using AJAX shorthand

I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>

How to send data from one page to another without page load?

I have two page one customform.php and another is preview.php.
I want to send some data which are values of some text-fields on customform.php using jquery post method. But I dont want the page to load. So I have used some JQuery code for this work. But now working for me.
the html code on customform.php is:
<form action="#" method="post">
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="button" value="preview" id="preview">
</form>
The jQuery code on customform.php is:
$('#previewph').click( function() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
alert("Mail: " + v1 + " Message: " + v2);
$.post( "http://www.lexiconofsustainability.com/lex_tmp2/preview/" ,{ name : v1 , title :v2 });
window.open("http://www.lexiconofsustainability.com/lex_tmp2/preview/", '_blank');
});
And on the preview.php I want to retrieve value form post method and echo them.
<?php
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
?>
Simply Try this
<form action="#" method="post" >
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="submit" value="preview" id="preview" onclick="senddata()" >
</form>
<div id="message"></div>
function senddata() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
$.post("http://www.lexiconofsustainability.com/lex_tmp2/preview/", { name : v1 , title :v2 },
function(data) {
document.getElementById("message").innerHTML = data;
});
}
You can use AJAX for this..
The jQuery code on customform.php should be:
$('#previewph').click( function() {
var v1 = $('#text1').val();
var v2 = $('#text2').val();
$.post("preview.php", {name:v1, title:v2}, function(data)
{
alert(data);
});
});
preview.php
<?php
if(isset($_POST['name'])&&($_POST['title']))
{
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
}
?>

Get the results of a form to a div without opening the results new page

How can I get the results of the result.php into the welcome div using ajax or any other method to prevent loading a new page?
<div id="welcome">
<form action="result.php" method="post">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="">Anyplace</option>
.
.
.
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="">Anything</option>
.
.
.
</select>
<input type="submit" class="button" value="Ok Go!"/>
<input id="current" name="current" type="hidden"/>​
</form>
</div>
If you are doing this through AJAX, then there is no need for the <form> codes. The <form> codes are only useful if you are posting to a different page and expecting the view to change/refresh anyways.
Also, using <form> codes in this example will cause the page to refresh (and values inserted by jQuery to be lost) for the additional bit with the "Set value for hidden field CURRENT" button. Not that it likely matters in your real world app, but just FYI.
Ajax goes in your javascript code, and looks like this:
$('#mySelect').change(function() {
var sel = $(this).val();
//alert('You picked: ' + sel);
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'theOption=' + sel,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that the data ECHO 'd from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:
$('#myDiv').html(whatIgot);
Presto! Your DIV now contains the data echoed from the PHP file.
Here is a working solution for your own example, using AJAX:
HTML MARKUP:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').on('click', function(e){
e.preventDefault(); //prevent default action
var ct = $('#city').val();
var dt = $('#date').val()
var ty = $('#type').val();
var curr = $('#current').val();
$.ajax({
url: 'result.php',
type: 'POST',
data: 'ct=' +ct+ '&dat=' +dt+ '&t=' +ty+ '&curr=' +curr,
success: function(response){
$('#welcome').html(response);
}
});
});
$('#mycurr').click(function(){
var resp = prompt("Please type something:","Your name");
$('#current').val(resp);
});
}); //END $(document).ready()
</script>
</head>
<body>
<div id="welcome">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="sumwhere">Anyplace</option>
<option value="anutherwhere">Another place</option>
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="sumthing">Anything</option>
<option value="anutherthing">Another thing</option>
</select>
<input type="submit" id="mybutt" class="button" value="Ok Go!"/>
<input type="submit" id="mycurr" class="button" value="Set value for hidden field CURRENT"/>
<input id="current" name="current" type="hidden"/>
</div>
</body>
</html>
PHP Processor file: result.php
$ct = $_POST['ct'];
$date = $_POST['dat'];
$typ = $_POST['t'];
$cu = $_POST['curr'];
if ($date == '') {
$date = 'Some other date';
}
$r = '<h1>Results sent from PHP</h1>';
$r .= 'Selected city is: [' .$ct. ']<br />';
$r .= 'Selected date is: [' .$date. ']<br />';
$r .= 'Selected type is: [' .$typ. ']<br />';
$r .= 'Hidden field #CURRENT is: [' .$cu. ']<br />';
$r .= '<h2>And that\'s all she wrote....</h2>';
echo $r;
You can do something like this using jQuery Ajax
Use following code inside your head tag or footer
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript>
$('document').ready(function(){ //after page load
$('.button').on('click', function(e){
e.preventDefault(); //prevent default action
$.ajax({
'url': 'result.php',
'type: 'POST',
'success': function(response){
$('#welcome').html(response);
}
});
});
});
</script>
valit's the action="result.php" who makes your page reload
You shloud try to give an id to your form, and using a simple ajax call :
$("#formId").submit(function() {
$.ajax({
url: 'result.php',
success: function(response) {
$("#welcome").setValue(response); // update the DIV
}
});
return false; // prevent form submitting
});
Cheers

Categories