PHP Ajax Call Navigating to Action Page on Form Submit - javascript

I have this ajax call in my php code that still navigates to action page. I want the ajax call to stay on the same page and only update part of the page. What I'm doing wrong here:
<form method="post" id="holderSave" action="student_add_scene.php">
<h3> Save to Holder</h3><br/>
<div id="cutfrom">
<input placeholder="Cut from" name="from" id="from">
<button href="#" onclick="captureElapsed('elapseFrom', 'from');
return false;">capture</button>
</div>
<div id="cutto">
<input placeholder="Cut to" name="to" id="to" >
<button href="#" onclick="captureElapsed('elapseTo', 'to');
return false">capture</button>
</div>
<div id="savecapt">
<input placeholder="add label" id="label" name="label"/>
<input type='submit' value='Save' class='button'>
</div>
</form>
<script>
$('#holderSave').on("submit", (function (e) { // catch the form's submit event
e.preventDefault();
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
var posting = $.post( url, { from: $('#from').val(), label:$('#label').val(), to: $('#to').val()});
posting.done(function(response)){
$('#holderSave').html(response); // update the DIV
alert(response);
}
});
return false;
}));
</script>

This is a syntax error:
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
You seem to be trying to treat the object literal you pass to ajax as a function body. It isn't, so you can't just write statements in it.
Since you make the ajax request with $.post later, $.ajax is entirely pointless. Remove that line and it should work.
Fixed code. Aside from the pointless half-a-call to .ajax, you had a bunch of syntax errors which I've fixed while reformatting it.
Use your browser's developer tools console. Use http://jshint.com/
// Remove pointless ( from before the second argument of the call to on().
$('#holderSave').on("submit", function(e) {
e.preventDefault();
// Remove half a call to .ajax
var $form = $(this),
url = $form.attr('action');
var posting = $.post(url, {
from: $('#from').val(),
label: $('#label').val(),
to: $('#to').val()
});
posting.done(function(response) {
$('#holderSave').html(response);
alert(response);
// Remove line with extra } here
});
return false;
// Remove extra ) here
});

Change submit into button with id
<input type='button' id="save" value='Save' class='button'>
Trigger click event for button, serialize the form data and post the data via ajax
$(document).ready(function() {
$('#save').click(function(){ // catch the form's submit event
var form = $('#holderSave');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form .serialize(),
success: function( response ) {
console.log( response );
}
} );
});
});

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

Grails order of function execution

I have a formRemote that calls a function in my controller when it is submitted like this:
<g:formRemote name="editIndivRecForm" url="[controller: 'customer', action:'saveEditedIndividualRecord']" onSuccess="doResult();">
This form is submitted by clicking on a button. Rather, a button that is clicked called 'save' will do other things among clicking the form's submit button via Javascript. Here is the click handler for this button:
$('#save').click(function () {
$("#uniqueId").prop('disabled', false); // Have to enable before form submission else it doesn't go back as a param to controller.
$("#secondaryId").prop('disabled', false);
$("#submit").trigger("click"); // formRemote's submit button
$('#editIndivRecForm').reset;
<g:remoteFunction controller="customer"
action="remediationSearch"
update="content_area"
params="{rerender: true}"/>
});
The problem I'm running into is that I need the function of my controller called by the click handler remediationSearch to run AFTER the function of the controller called by the formRemote's submission saveEditedIndividualRecord is done executing. But it is happening the other way around. And for some reason the function onSuccess="doResult();" doesn't even execute otherwise I was going to move the following code into its body to make things work the way I want:
<g:remoteFunction controller="customer"
action="remediationSearch"
update="content_area"
params="{rerender: true}"/>
here is how doResult is now:
function doResult() {
console.log("done.");
}
the formRemote is submitted but the doResult function prints nothing to the console.
Seeing as all of the Grails AJAX related tags have been deprecated, I would recommend trying it this way:
Markup:
<form id="editIndivRecForm" onsubmit="return false;">
<!-- add fields here -->
<input type="text" id="uniqueId" value="${something}">
<input type="text" id="secondaryId" value="${something}">
<button id="save" type="button">
</form>
JavaScript:
// Function to update your content_area div
function updateContentArea() {
var params = { rerender: true };
var url = "${createLink(controller: 'customer', action: 'remediationSearch')}";
$.get(url, params, function(data) {
$("#content_area").empty().append(data);
});
}
$("#save").on('click', function() {
// Collect values from form and submit ajax request
// Using name and description for example fields here:
var data = {
name: $("#name").val(),
description: $("#description").val(),
uniqueId: $("#uniqueId").val(),
secondaryId: $("#secondaryId").val()
};
var url = "${createLink(controller: 'customer', action: 'saveEditedIndividualRecord')}";
// Submit the (first) AJAX request
$.ajax({
type: "post",
url: url,
data: data,
success: function() {
doResult();
$('#editIndivRecForm').reset();
updateContentArea();
}
});
}

passing values from javascript to php

HTML CODE
<form action="phpfile.php" method="post">
<input type="button" id="id1">
<input type="button" id="id2">
<input type="submit">
</form>
<div id="result"></div>
JAVASCRIPT CODE
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
});
Can you give me some tips on how I can send the qty1, qty2 and totalqty to my php file, after I click the submit button. Before I send it to the php file, I need to check first if the button is already clicked. If not, no qty will be send to the phpfile. I need to send the exact number of qty based on how many times you clicked the button.
The easiest solution would be to add qty as <input type="hidden" id="qty1" name="qty1" /> to your form. They will be invisible as your variables, and will be sent to the server as form fields. To access their values from Javascript, use $("#qty1").value()
You're looking for something called AJAX.
This is easy to implement using the jQuery library, but it's also available using regular JavaScript.
If you choose to use the jQuery implementation then your can look at the documentation.
Here's a basic example:
$.ajax({
type : 'post',
url : 'target.php',
dataType : 'json',
data : {
'foo' : 10
}
}).done(function()
{
$(this).addClass("done");
});
You then use the back-end to handle the response, let's for example assume that you send an object of parameters whera one key is named foo and the value is 10, then you could fetch it like this (if the code is PHP):
$foo = isset($_POST['foo']) ? $_POST['foo'] : "";
Using the ternary operator
try using jquery $.ajax or $.post function:
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
get_values(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
get_values(qty2);
});
function get_values(qty_val) {
$.post(
'get_values.php', // url of your php who will receive the values
{ post_variable_name: qty_val }, // your post variables here
function(data) {
// call back function
$("#result").html(data); // see what does your get_value.php echoes via html
console.log(data); // see it via console in inspect element
}
);
}
and in your php that will recieve the values, just retrieve using $_POST:
<?php
$qty_val = '';
if(isset($_POST['post_variable_name'])) {
$qty_val = $_POST['post_variable_name'];
echo $qty_val;
}
?>
HTML
<form>
<input name="id1" type="button" id="id1" />
<input name="id2" type="button" id="id2" />
<input type="submit" />
</form>
<div id="status"></div>
JS
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
});
$( "form" ).submit(function( event ) {
// prevent the default event
event.preventDefault();
// check first if the totalqty. You can add more checks here
if ( totalqty === 0 ) {
// usually show some kind of error message here
alert('No quantity selected!');
// this prevents the form from submitting
return false;
} else {
$.ajax({
type: 'post',
url: 'phpfile.php',
dataType: 'json',
data: {
quantity1: qty1,
quantity2: qty2,
totalQuantity: totalqty
}
}).done(function(data) {
console.log(data);
alert( "success" );
$('#status').html("Successfully saved!");
}).fail(function() {
console.log(data);
alert( "error" );
$('#status').html("Successfully saved!");
});
}
});
PHP
$qty1 = isset($_POST['quantity1']) ? $_POST['quantity1'] : "";
$qty2 = isset($_POST['quantity2']) ? $_POST['quantity2'] : "";
$total = isset($_POST['totalQuantity']) ? $_POST['totalQuantity'] : "";
Sorry, i can't test it, but it should work
For more detailed you could have a look to the jQuery Learning Center - Ajax where you can find useful examples to work with ajax and forms.

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.

Is there a way in JavaScript to retrieve the form data that *would* be sent with a form without submitting it?

If I have an HTML form, let’s say...
<form id='myform'>
<input type='hidden' name='x' value='y'>
<input type='text' name='something' value='Type something in here.'>
<input type='submit' value='Submit'>
</form>
... and then I use jQuery to respond to the form submission event, e.g.
$('#myform').submit(function() {
...
return false;
});
Now suppose I want to submit the form as an AJAX call instead of actually submitting it the “traditional” way (as a new page). Is there an easy way to get a JS object containing the data that would be sent, which I can pass into $.post()? So in the above example it would look something like...
{
x: 'y',
something: 'Type something in here.'
}
or do I have to bake my own?
See the serialize() method.
$('#myform').submit(function() {
jQuery.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function () {
//
}
});
return false;
});
As you're already using jQuery, use jQuery.serialize().
$('#myform').submit(function() {
var $form = $(this);
var data = $form.serialize();
// ...
});

Categories

Resources