Get input field value in same page without refreshing page php - javascript

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";
}

Related

Submitting form with AJAX not working. It ignores ajax

I've never used Ajax before, but from researching and other posts here it looks like it should be able to run a form submit code without having to reload the page, but it doesn't seem to work.
It just redirects to ajax_submit.php as if the js file isn't there. I was trying to use Ajax to get to ajax_submit without reloading anything.
Is what i'm trying to do even possible?
HTML form:
<form class="ajax_form" action="ajax_submit.php" method="post">
<input class="input" id="license" type="text" name="license" placeholder="License" value="<?php echo htmlentities($person['license1']); ?>" />
<input class="input" id="license_number" type="text" name="license_number" placeholder="License number" value="<?php echo htmlentities($person['license_number1']); ?>" />
<input type="submit" class="form_button" name="submit_license1" value="Save"/>
<input type="submit" class="form_button" name="clear1" value="Clear"/>
</form>
in scripts.js file:
$(document).ready(function(){
$('.ajax_form').submit(function (event) {
alert('ok');
event.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize(),
success: function (data) {alert('ok');}
});
});
});
in ajax_submit.php:
require_once("functions.php");
require_once("session.php");
include("open_db.php");
if(isset($_POST["submit_license1"])){
//query to insert
}elseif(isset($_POST['clear1'])) {
//query to delete
}
I have "<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>"
in the html head
form.serialize() doesn't know which button was used to submit the form, so it can't include any buttons in the result. So when the PHP script checks which submit button is set in $_POST, neither of them will match.
Instead of using a handler on the submit event, use a click handler on the buttons, and add the button's name and value to the data parameter.
$(":submit").click(function(event) {
alert('ok');
event.preventDefault();
var form = $(this.form);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize() + '&' + this.name + '=' + this.value,
success: function (data) {alert('ok');}
});
});
Your ajax call is working perfectly. You have few conceptual error with your code -
form.serialize() will not attach submit button's info.
If you want to clear your form, you can do it using something like this
$('#resetForm').click(function(){
$('.ajax_form')[0].reset();
});
Lastly complete your task & return success or failed value to ajax call using echo like echo 'successful' or echo failed etc. Use an else condition with your code. It will be more clearer to you.
Remove the "action" and "method" attributes from the form. You shouldn't need them.

Onclick event with PHP, ajax and jQuery not working

I want to use an onclick event with PHP in order to accomplish the following. I would like to use ajax to avoid the page being refreshed. I want to create buttons on event click.
I don't know how to join the div buttons with the ajax result.
Here is my PHP file: Button.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dymanic Buttons</title>
<script type= "text/javascript" src ="jquery-2.1.4.min.js"></script>
<script type= "text/javascript" src ="test.js"></script>
</head>
<body>
<div>
<input type="submit" class="button" name="Add_Button" value="Add Button"</>
<input type="submit" class="button" name="Modify_Button" value="Modify Button"</>
<input type="submit" class="button" name="Delete_Button" value="Delete Button"</>
</div>
test.js contains this:
$(document).ready(function () {
$('.button').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue
};
$.post(ajaxurl, data, function (response) {
alert("action performed successfully");
});
});
});
And the other php that is ajax.php
<?php
if (isset($_POST['action'])){
switch($_POST['action']){
case 'Add_Button':
Add_Button();
break;
}
}
function Add_Button(){
echo '<input type="submit" class="button" name="Test_Button" value ="Test Button"</>';
exit;
}
?>
You're calling the <input>'s value, instead of it's name which you set it as.
Change your clickBtnValue to this:
var clickBtnValue = $(this).attr('name');
Since it has Add_Button/Modify_Button/etc.
To append the new button to your div, start by giving it an id, so that we can continue to call it:
<div id="my-buttons">
Now in your ajax request, simply jQuery.append() the html to the div:
$.post(ajaxurl, data, function (response) {
$('div#my-buttons').append(response);
});
You can add the result of request to your div with this:
$.post(ajaxurl, data, function (response) {
$("div").append(response);
alert("action performed successfully");
});
Note the value of your button is "Add Button", not "Add_Button"
You probably want to make sure that each component of your code is working first. The problem may be in your AJAX call, it should be similar to the following:
/** AJAX Call Start **/
// AJAX call to dict.php
$.ajax({
/** Call parameters **/
url: "ajax.php", // URL for processing
type: "POST", // POST method
data: {'action': clickBtnValue}, // Data payload
// Upon retrieving data successfully...
success: function(data) {}
});
Also, make sure you are using the correct routing to your PHP file and that your PHP file is returning a valid response.
EDIT: As per the jQuery Docs, I am fairly certain that the problem is within your AJAX call, specifically your $.post() setup. Please refer here for the proper setup is you want to keep your AJAX call structured as is instead of the way I suggested.
As per the jQuery Docs:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});

Prevent page reload and redirect on form submit ajax/jquery

I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.

$.ajax won't access url

I'm trying to send some data via jquery and $.ajax to a php file. When the page loads, a list of names is retrieved from "bewohner_func.php". This works.
At the end of the list is a form, which is used to add a new Name onto the list. It uses $.ajax to send the data, also to "bewohner_func.php", using a switch to differntiate from displaying or adding the data-. Problem is, when I try to send the form, the script does not include the php file. I can safely say that it's not the php file's fault, as I reduced it to an alert.
$(document).ready(function()
{
$("#bew_new").submit(function()
{
var frmData = $("#bew_new").serialize();
$.ajax({
url: "bewohner_func.php",
data: frmData,
success: function(msg)
{
$('#bewohnerliste').fadeOut(400);
$.get("bewohner_func.php", {'bew_new': '0'}, function(data){
$("#bewohnerliste").html(data);
});
$('#bewohnerliste').fadeIn(400);
}
});
return false;
});
});
This is the code for displaying, which does it's job fine:
$(document).ready(function()
{
$.get("bewohner_func.php", {'bew_new': '0'}, function(data){
$("#bewohnerliste").html(data);
});
});
The form:
<form id="bew_new" class="bew_form" action="bewohner_func.php" method="get">
<input name="anrede" size="6" value="Anrede" onFocus="if(this.value=='Anrede')this.value=''">
<input name="name" value="Name" onFocus="if(this.value=='Name')this.value=''">
<input name="wohnbereich" size="2" value="WB" onFocus="if(this.value=='WB')this.value=''">
<input type="submit" value="Neu anlegen">
</form>
It sounds like you are running your submit handler code on page load before form is loaded. If so, submit handler won't be bound to form if it doesn't exist.
You can delegate the handler to an eleemnt, or the document itself, that will be permanent asset in page
TRY:
$("#bewohnerliste").on('submit',"#bew_new",function(){
var frmData = $(this).serialize();
$.ajax......
})

How to put a jQuery code into one file which will be referenced by all pages?

I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.
I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var some_params= $("#param").val();
var dataString = 'Some url to send to ajax';
if( params validated ok )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.
And here is the form I am calling to display in the popup:
<?php
echo '<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
</p>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
<p>
Create Account | Reset Pass
</p>
';
?>
and here is the problemio.js contents with the jQuery to handle the login form submit:
// javascript library
// login_form
$(function()
{
$("#login_form input[type=submit]").click(function()
{
console.log("test");
alert("1");
// var name = $("#problem_name").val();
// var problem_blurb = $("#problem_blurb").val();
// var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
// if(name=='' || problem_blurb == '')
// {
// $('.success').fadeOut(200).hide();
// $('.error').fadeOut(200).show();
/// }
// else
// {
// $.ajax({
// type: "POST",
// url: "/problems/add_problem.php",
// dataType: "json",
// data: dataString,
// success: function(json)
// {
// $('.success').fadeIn(200).show();
// $('.error').fadeOut(200).hide();
//
/// // Here can update the right side of the screen with the newly entered information
// //alert (json);
//
// new_string = "<h2>Most Recently Added Problems</h2>";
// Have to figure out how to make this work with the DOM.
// }
// });
// }
return false;
});
});
Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.
Next, alter the following line:
$("input[type=submit]").click(function()
To instead say:
$("#loginform input[type=submit]").click(function()
And then set id="loginform" on your <form> tag.
You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:
$("#some_form_id").submit(function() {
// the code you have in the click event above goes here.
});
You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/
If you are not sure, just right-click this webpage and read its html code.
<script type="text/javascript" src="some.js"></script>
And also, binding the the function to form.submit is much better than to the submit button.
$('formid').submit(function(){blablabla;return false;})
If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.

Categories

Resources