PHP code doesnt work together with JS function on "onclick" - javascript

i have a button in which i want it to perform 2 task; php and js.
The php part : generate different text everytime the button is pressed.
The js part : disabling the button for 5 secs and then enabling it back.
HTML
<button onclick = "disable();" class=btnGenerate type="submit" id="submit" name="submit" >GENERATE</button>
PHP
if(isset($_POST['submit'])){
$num=mt_rand(1,10);
$result=mysqli_query($con,"SELECT * from quote_table where id=$num");
$row = $result->fetch_assoc();}
JS
<script>
function disable(){
document.getElementById("submit").disabled = true;
setTimeout(function() { enable(); }, 5000); }
function enable(){
document.getElementById("submit").disabled = false;
}</script>
The PHP part only works when i delete the "onclick = "disable();" on the html but it doest seem to work when i add it. Can a button carry out PHP and JS at a single click ? Thanks in advance.

A disabled button can't be a successful control.
Don't depend on the name/value of the submit button being submitted in the form data if you are going to disable it.
Replace isset($_POST['submit']) with some other condition.

If you trigger a form submission, unless you're using AJAX the page will simply reload, rendering the enable() method moot unless
you're using it to re-enable the button on fail condition or on
successful return of data via AJAX.
It's sounds to me like you're trying to get data via request to the server, without reloading the page, and then re-enable the submit button after the data is returned. In that case you need to use AJAX.
HTML
<form action="/" method="post" id="form">
<button class=btnGenerate type="submit" id="submit" name="submit" >GENERATE</button>
</form>
JS
<script>
document.getElementById('submit').addEventListener('click', function(event){
event.preventDefault(); // prevents browser from submitting form
var form = document.getElementById('form');
var submit = document.getElementById('submit');
// using JQuery ajax
$.ajax(form.action, {
data: form.serialize(),
beforeSend: function() { // runs before ajax call made
// disable submit button
submit.disabled = true;
},
success: function(response) {
console.log(response);
// deal your return data here
},
error: function(error) {
console.log(error);
// deal with error
},
complete: function() { // runs when ajax call fully complete
// renable submit button
submit.disabled = false;
}
});
});
</script>

Related

Get input field value in same page without refreshing page php

I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}

AJAX call not working - PHP, MySQL, jQuery/Ajax

I have the following problem:
What i'm trying to accomplish is:
User clicks on a submit/image type button
Ajax call handles the submit, calls another PHP script to update a record in a MySQL table, all without reloading the page ( obviously )
My PHP code is working fine without the AJAX, as it will reload and update the record. but somehow the ajax call is not working and/or returning any error.
My code:
$(function() {
$('#like_form').submit(function(event) {
event.preventDefault(); // Preventing default submit button
var formEl = $('#like_form');
var submitButton = $('input[type=submit]', formEl);
$.ajax({
async: true,
type: 'POST',
url: formEl.prop('action'),
accept: {
javascript: 'application/javascript'
},
beforeSend: function() {
submitButton.prop('disabled', 'disabled');
}
}).done(function(data) {
submitButton.prop('disabled', false);
$("#like").fadeOut();
$("#like").fadeIn();
});
});
});
<!-- LIKE een gebruiker -->
<form action="" id="like_form" method='POST' enctype="multipart/form-data">
<input onmouseover="this.src='img/heart2.png'" onmouseout="this.src='img/heart.png'" name='like' id="like" src='img/heart.png' type="image" />
</form>
my PHP (just in case):
<?php
include_once "dbconnection.php";
//if like button (submit button) clicked
if ($_POST){
$conn = DatabaseConnection::getConnection();
$sql = "UPDATE dating_members
SET likes = likes + 1
WHERE member_id = 3";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
?>
I figured out what the problem is, Kind of silly I didn't notice but better late than never.
I had to 'include' the JS script at the end of my PHP page in order to catch my onsubmit function and therefore disable the default event a.k.a submit button submitting my form and page reload / POSTs to the other PHP file.
Everything is working fine now

Ajax before HTML form submission (asynchronously)

<form target="_blank" method="POST" action="somePage.php" id="myForm">
<input type="hidden" name="someName" value="toBeAssignedLater"/>
<button type="submit">Proceed</button>
</form>
At the beginning, the value of someName is not determined yet, I want to execute an Ajax to get and assign the value to it before the form is actually submitted.
I tried:
$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
});
});
But the form would have already submitted before the Ajax is finished, how can I ensure the form would be submitted after the Ajax is finished.
I want to keep the form submit event initiated by the user instead of code, such as $("#myForm").trigger('submit');, since I don't want the new window tab to be blocked by browsers.
$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
// submit form without triggering jquery handler
$this[0].submit();
});
// cancel the current submission
return false;
});
Why don't you ajax the value at page load and than submit the data?
$(function(){
someAjaxFunction(function (data) {
$('input[name="someName"]').val(data.value);
});
$("#myForm button").on('click',function(){
$(this).submit();
});
});
or place the ajax call on click event and submit whan the values is updated:
$(function(){
$("#myForm button").on('click',function(e){
e.preventDefault();
$.ajax({
url:url, //other params
success:function(data){
//thing to do before submit
$('input[name="someName"]').val(data.value);
$(this).submit();
}
});
});
});

[jQuery]Page refreshes after appending html with .html()

So I'm trying to get some data from the server with php but as soon as it's loaded onto the page it seems to reload the page and make it disappear again.
My html:
<form id="searchForm">
<input name="searchValue" type="text" id="search">
<input type="submit" name="Submit" value="Zoek op klant" onclick="getKlanten()">
</form>
<div id="klanten">
</div>
My js:
function getKlanten(){
var value = $("#search").val();
$.ajax({
url:'includes/getKlanten.php',
async: false,
type: 'POST',
data: {'searchValue':value},
success: function(data, textStatus, jqXHR)
{
$('#klanten').html(data);
},
error: function () {
$('#klanten').html('Bummer: there was an error!');
}
});
}
Can anyone help? It gets put into the div but then instantly disappears again.
Firstly, avoid inline click handlers. The page reloads because by default a form submits the form content to the url specified in action attribute.
Instead attach an event to the form and use preventDefault to avoid the page from refreshing. Do something like this
$('#searchForm').on('submit', function(e){
e.preventDefault();
// your ajax request.
});
Or attach an event to input button like this
$('input[type="submit"]').on('click', function(e){
e.preventDefault();
// your ajax request
});
Read more about preventDefault here

Disable form inputs after ajax submission

I have a form that submits via Ajax. After the user sends the form, the text changes displaying the form was sent successfully and then shows the form filled out. I want to display the form but I don't want them to re-submit the form so I want to disable the inputs as well as the submit button. I tried adding: $('#submit_btn').className +=" disabled" to the ajax script but it just made the page refresh without submitting anything.
The ajax script is as follows:
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
var email = $("inputemail").val();
var phone = $("inputphone").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://www.green-panda.com/website/panda/webParts/contact-form.php",
data: dataString,
success: function() {
$('#myModalLabel').html("<h3 class='text-success' id='myModalLabel'>Contact Form Submitted!</h3>")
$('#myModalSmall').html("<p class='muted'>Your submiessions are below. We will be contacting you soon, you may now close this window.</p>")
$('#submit_btn').className +=" disabled"
.hide()
.fadeIn(1500, function() {
$('#message').append("<i class='icon-ok icon-white'></i>");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
How could I possibly disable the inputs and button after a successful form submission?
http://jsfiddle.net/gY9xS/
Actually it's a lot simpler than what you're trying to do, you don't need to disable the inputs, simply cancel the submit after the ajax request:
$('form').submit(function(){
return false;
});
Put it inside the success handler of your ajax request.
If you want to disable the submit button, replace this wrong thing:
$('#submit_btn').className +=" disabled"
With:
$('#submit_btn').prop("disabled", true);
In my application, i just disabled the submit button and shows some progress message
function submitForm(formObj) {
// Validate form
// if (formObj.email.value === '') {
// alert('Please enter a email');
// return false;
// }
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
return true;
}
<form class="form-login" accept-charset="UTF-8"
method="POST" action="/login" onsubmit="return submitForm(this);">
......
<input type="submit" id="login-submit" name="submit" value="Log In">
</form>

Categories

Resources