I am using a single form in two different scenarios - Create and Edit.
I do something like
<?php
if($status == 'new')
echo '<button id="btnSubmit" type="submit" class="btn">Submit!</button>';
else
echo '<button id="btnEdit" type="submit" class="btn">Edit!</button>';
?>
What I want to achieve on my javascript end is to validate the form and call the correct web service according to which button is pressed. I am using the jQuery Validation Plugin found here.
Javascript
$('#myForm').validate({
submitHandler: function(data) {
$.ajax({
url: "service1.php"
...... other AJAX stuff ..........
});
}
}
$('#btnSubmit').click(function() {
// call service1.php
});
$('#btnEdit').click(function() {
// call service2.php
});
The method for validate can be a single function and you can set a flag(For example you will get an id in the edit page) to identify edit page or add page. So that you can check the flag in submit handler and submit the form to where it needs to be submitted. I'm not familiar with PHP and i hope this might help you.
Based on Marikkani's suggestion, I have implemented the below and it works. Hope it helps someone with a similar problem using Javascript and PHP.
In my form file I used a hidden div to store the type (new or edit).
<input type="hidden" id="type" value="<?php echo $type; ?>" />
Thereafter, in my javascript file I retrieve this value and check before calling the respective ajax.
$('#resForm').validate({
submitHandler: function(form) {
var type = $('#type').val();
if(type == 'new') {
$.ajax({
url: "service1.php"
.... other AJAX stuff
});
} else { // type is edit
$.ajax({
url: "service2.php"
.... other AJAX stuff
});
}
}
});
Related
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";
}
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
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.
I'm trying to confirm deleting something, but I can't seem to get it to work.
When the button for 'deleteReply' I'm getting an alert message, but as far as I can tell nothing else is happening. I'm trying to simply echo the posted variable but it doesn't seem to work.
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
On my delete processing page I just have
$echo $_POST['replyID'];
Why do you have
if(isset($_POST['deleteReply'])){
?>
Before the javascript function? Did you expect to trigger the javascript code based on the $_POST['deleteReply'] var?
You have to keep in mind that php is processed server-side and outputs an HTML page. Your javascript code will only run in the client after all the php has run.
A much more elegant solution would be asking for a confirmation BEFORE sending the AJAX request.
And also, your ajax call doesn't seem to do what you're expecting. You're manually setting 2 parameters to send to your PHP which will have no use for it if you do the confirmation server-side.
A parameter should be something like the Reply ID of the reply you want to delete, and send the request to a different php file for handling.
I'd suggest you rewrite your code as Marian Zburlea is doing for you.
EDIT
Ok, if you want a simple confirm window, try this:
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('delete.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
EDIT
If you have multiple delete buttons, the best way to do this would be storing the replyID as the parameter to pass to your function. Echo your delete buttons in your php like this:
echo '<input type="button" value="Delete" onclick="deleteSomething(\'' . $replyID . '\')" />';
This way, the $replyID will be stored in the page's HTML, which will be passed to the deleteSomething(replyID) function which you now have to define (preferably in the document's head after the JQuery lib):
<script type="text/javascript">
function deleteSomething(replyID)
{
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
}
</script>
Note that I removed the ID from the buttons to don't generate dupplicate IDs and they are no longer needed, as I've added a function call in the onclick event instead of binding an anonymous function to their IDs as you were doing previously.
<input type="button" id="deleteSomething" value="Delete" />
<div id="yesno" style="display:none;">
<input type="button" id="buttonYes" value="Yes" />
<input type="button" id="buttonNo" value="No" />
</div>
<script type="text/javascript">
// Here you attach a click event to the button Yes with id buttonYes
$('#deleteSomething').click(function() {
$('#yesno').css('display', 'block');
});
$('#buttonNo').click(function() {
$('#yesno').css('display', 'none');
});
$('#buttonYes').click(function() {
$.ajax({
beforeSend: function(e) {
// Code to process before calling AJAX
},
url: "pathToPHPFile.php",
dataType: "json",
type: "POST",
data: {
parameter: 'Yes',
},
success: function (m) {
console.log(m);
alert(m.text);
},
error: function (e) {
console.log("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
// This is a separate php file named pathToPHPFile.php
if(isset($_POST['parameter']) && $_POST['parameter'] == 'Yes'){
/* here you put the code that deletes the message */
$response['text'] = 'messageDeleted'
echo json_encode($response);
}
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.