passing values from javascript to php - javascript

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.

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

assign php output (ajax) to javascript variable

This is my first time using javascript please be respectful. I have a form which is submitting data via ajax. Everything works as intended, however I'm trying to assign what recd.php is echoing to recresponse so the correct error code is displayed in an alert. Any help or examples would be appreciated.
Form:
<form action="recd.php" method="post" id="GAMEAPPID">
<input type="text" name="GAMEAPPID" id="GAMEAPPID" />
<input type="submit">
</form>
Javascript:
<script>
$(function(){
$("#GAMEAPPID").on("submit", function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr("method"), // <-- get method of form
url: $(this).attr("action"), // <-- get action of form
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
$("#result").html("");
},
success: function(data){
$("#result").html(data);
if(recresponse === "0") {
alert("Incomplete.");
}
if(recresponse === "1") {
alert("Duplicate.");
}
if(recresponse === "2") {
alert("Failed");
}
if(recresponse === "3") {
alert("Thanks");
}
document.getElementById("GAMEAPPID").reset();
refreshMyDiv();
}
});
});
});
</script>
I try to answer. in your "recd.php", you should assign the recresponse to a element like <input type="hidden" id="myRS" value="<?= $myRS ?>" />
and then you can access the element in your javascript.

Passing data through ajax

I was following a tutorial to pass text to search through ajax, and it works good. Now I want to pass also checkboxes values. Can someone point me to the right direction? Right now I have:
function search(){
var term=$("#search").val();
if(term!=""){
$("#result").html("<img src='/img/spin.gif'/ style='margin-top: 30px;'>");
$.ajax({
type:"post",
url:"file.php",
data:"q="+encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
}
So, basically I figure the text is sent through the post variable "q". Let's say I have an array of checkboxes, how can I add that to the same post request?
you could use jQuery's serialize.
$('#form').submit(function(e) {
var data = $('#form').serialize();
$.post('form.php',data, function(status) {
if(status == 'success') {
// success
} else {
// error
}
});
e.preventDefault();
});
form.php
<?php
$search = $_POST['search'];
etc...
$.ajax({
type:"post",
url:"file.php",
data: {
q: encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
checkboxes: $('input[type=checkbox]').serialize()
}
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
It will be simpler for you, if you try to serialize your data.
You didn't write how your html looks like, so let's say you have a form like this:
<form id="form">
Search text: <input type="text" name="data[text]"/>
<input type="checkbox" name="data[option]" /> Option 1
<input type="submit" value="Search"/>
</form>
To send this form with ajax request, all you have to do is to serialize your form
$('#form input[type="submit"]').click(function(e) {
e.preventDefault();
$.post("file.php", $("#form").serialize(), function(){
console.log('success');
});
});
Then in your php script you can retrieve data from $_POST variable, for example $_POST['data']['text']

PHP Ajax Call Navigating to Action Page on Form Submit

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

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