POST Showing Undefined with JQuery - php

I'm new to jQuery and I keep getting undefined as data when I submit the form. I looked online and tried serialize(), the $.ajax function, $.post function, amongst other methods to no avail.
I'm trying to accomplish a form submit without a page refresh. The code works fine if I comment out the script to remain on the page after form submission.
index2.php
<script>
function newlock() {
$("#new-lock").load("new-lock.php");
}
</script>
<h3>Lock Settings</h3>
<div>
New Lock
</div>
//code in between
<div id="tabs-1">
<div id="new-lock"></div>
</div>
insert_new_lock.php
require "connect.php";
$name = $_POST['name'];
echo $name;
$IP = $_POST['IP'];
echo $name;
$sql="INSERT INTO door_lock (lock_IP, lock_name)
VALUES
('$name','$IP')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
mysql_close($conn);
?>
new-lock.php
<!doctype html>
<html lang="us">
<h2 align = "center"> Please enter information for the new lock </h2>
<table border="0" align= "center">
<form id="newlockform" action="insert_new_lock.php" method="post">
<tr><td>Lock Name:</td> <td><input type="text" name="name"></td></tr>
<tr><td>Lock IP:</td> <td><input type="text" name="IP"></td></tr>
<tr><td><input type="reset" value="Clear"> <input type="submit" name="submitted" value="Submit"></td></tr>
</form>
</table>
</html>
<script>
$("#newlockform").submit(function() {
var name = $("#name").val();
var IP = $("#IP").val();
var dataString = 'name=' + name + '&IP=' +IP;
$.post('insert_new_lock.php', dataString, function(data) {
$("#tabs-1").html(data).fadeIn('100');
$('#name,#IP').val('');
}, 'text');
return false;
});
</script>
Any help would be appreciated! :D

You do not have any id set on your form fields, so
var name = $("#name").val();
is going to return null, which you then submit as an empty string. The form fields should loo like
<input type="text" name="whatever" id="name" />
^^^^^^^^^^^
for your JS code to work.

Related

How to display the results from a separate PHP file in an HTML page?

I need to display the sum in the HTML form page itself. A part of the code is given below in my PHP file:
<?php
while($row = mysqli_fetch_array($search_result)):?>
<?php
$sum=$sum+$row['value'];
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['time'];?></td>
<td><?php echo $row['value'];?></td>
</tr>
<?php endwhile;?>
In my HTML form I have a total button. When I click that, I need to display the sum value. How can I do that?
<form action="php_html_table_data_filter3.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button type="button">Total</button><br><br>
</form>
As I assume that you want to show total, if it is correct then follow below method
$sum = 0;
while($row = mysqli_fetch_array($search_result)):?>
$sum+= $row['value'];
<?php endwhile;?>
echo $sum;
or
if you want to show result without reloading the page. you have to code in ajax request.
We use ajax in html page to access the content from the php page :
HTML:
<html>
<script src="jquery.min.js"></script> // script download
<form action="php_html_table_data_filter3.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button type="button" id="total">Total</button><br><br>
Your sum:<span id="sum"></span>
</form>
</html>
<script>
$( "#total" ).click(function() {
$.ajax({
url : "phptest.php",
type: "POST",
success: function(data)
{
$('#sum').html(data);
}
});
});
</script>
PHP: here your php code
<?php
echo "10";
?>
You need to use PHP SESSIONs, and play with the information you're sending in the POST request. Basically, both buttons will need to be of type submit so that they both send the request to the process (process.php). Then you can use sessions to set your results.
Do it in this manner:
index.php
<?php session_start(); ?>
<form action="process.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button name="total_btn" type="submit">Total</button>
</form>
<div id="results">
<?= (!empty($_SESSION["table"])) ? $_SESSION["table"] : "" ?>
<br>
<?= (!empty($_SESSION["sum"])) ? "Sum: " . $_SESSION["sum"] : "" ?>
</div>
<?php
session_destroy();
process.php
<?php
session_start();
$sum = 0;
$table = "<table>";
while ($row = mysqli_fetch_array($search_result)) {
$sum += $row['value'];
$table .= "<tr>
<td>{$row['id']}</td>
<td>{$row['time']}</td>
<td>{$row['value']}</td>
</tr>";
}
$table .= "</table>";
if (isset($_POST['total_btn'])) {
$_SESSION["sum"] = $sum;
}
$_SESSION["table"] = $table;
header('Location: index.php');
if i understood your problem correctly, then u need Ajax call. GET or POST based on your preferences.on that your HTML code will be separate from php code basically php code will respond to Ajax call and give you out put.
Modified code- Test.html
<form action="php_html_table_data_filter3.php" method="post">
From:<input type="text" name="valueToSearch1"><br><br>
To:<input type="text" name="valueToSearch2"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<button type="button" id="gettotal">Total</button><br><br>
</form>
<script>
$("#gettotal").click(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',//based on your choice or requirement
url: 'calculate.php',
success: function(response) {
//here u decide where to show output value
alert(response);
},
error: function(result) {
alert('error');
}
});
});
</script>
calculate.php
<?php
$sum = 0;
while($row = mysqli_fetch_array($search_result))
{
//calculate your total and send back as JSON obj.
$sum=$sum+$row['value'];
}
echo json_encode($sum);
?>

Submit page but dont refresh

I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
I heard this is possible with ajax, but i have no idea how in this case i already tried to look on the internet..
if you have a type="submit" inside a form, it will submit the form by default. Try to use <input type="button" instead. Then you can use ajax on the button action, that will run without refreshing the page.
Here's an example of how to use ajax:
function sendAjax() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$(".result").html(JSON.stringify(data))
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="button" onclick="sendAjax()" value="callAjax" />
<div class="result"></div>
</form>
Add
return false;
to your jQuery-function at the end. With this you can avoid the submit.
Then you need to add an ajax-function, which sends the data from your form to the php-script you already use.
This is just an example:
$.ajax({
url: "YOUR-PHP-SCRIPT"
}).done(function (content) {
// ADD HERE YOUR LOGIC FOR THE RESPONSE
}).fail(function (jqXHR, textStatus) {
alert('failed: ' + textStatus);
});
So you have to do $.ajax post request to the php. Something like this:
<script>
$('.form-control').click(function() {
$.post(url, {data}, function(result) {
footerPreview();
}, 'json');
});
</script>
So footerPreview will be called when your php returns result.
//add in javascript
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
$("button.form-control-generate").show();
}
you can create an index.php:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" id="tm">
<option val=""></option>
<option val="©">©</option>
<option val="™">™</option>
<option val="®">®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" id="cn" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit" id="generate">
Generate
</button>
</form>
<div class="output" id="output">
</div>
<script type="text/javascript">
$('#generate').on('click', function(e){
e.preventDefault();
var companyname = $('#cn').val();
var trademark = $('#tm').val();
$.ajax({
url: 'process.php',
type: 'post'.
data: {'company':companyname,'trademark':trademark},
dataType: 'JSON',
success: function(data){
$('#output').append("<div id='footer_date'>"+data.trademark + " " + data.date + " " + data.company + " </div>");
},
error: function(){
alert('Error During AJAX');
}
});
})
</script>
and the process.php:
<?php
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["company"];
$date = date("Y");
$array = array(
'trademark' => $trademark,
'company' => $company,
'date' => $date
);
echo json_encode($array);
?>
Be sure that the index.php and the process.php will be under the same folder.. ex.public_html/index.php and public_html/process.php

How to send data from one page to another without page load?

I have two page one customform.php and another is preview.php.
I want to send some data which are values of some text-fields on customform.php using jquery post method. But I dont want the page to load. So I have used some JQuery code for this work. But now working for me.
the html code on customform.php is:
<form action="#" method="post">
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="button" value="preview" id="preview">
</form>
The jQuery code on customform.php is:
$('#previewph').click( function() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
alert("Mail: " + v1 + " Message: " + v2);
$.post( "http://www.lexiconofsustainability.com/lex_tmp2/preview/" ,{ name : v1 , title :v2 });
window.open("http://www.lexiconofsustainability.com/lex_tmp2/preview/", '_blank');
});
And on the preview.php I want to retrieve value form post method and echo them.
<?php
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
?>
Simply Try this
<form action="#" method="post" >
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="submit" value="preview" id="preview" onclick="senddata()" >
</form>
<div id="message"></div>
function senddata() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
$.post("http://www.lexiconofsustainability.com/lex_tmp2/preview/", { name : v1 , title :v2 },
function(data) {
document.getElementById("message").innerHTML = data;
});
}
You can use AJAX for this..
The jQuery code on customform.php should be:
$('#previewph').click( function() {
var v1 = $('#text1').val();
var v2 = $('#text2').val();
$.post("preview.php", {name:v1, title:v2}, function(data)
{
alert(data);
});
});
preview.php
<?php
if(isset($_POST['name'])&&($_POST['title']))
{
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
}
?>

Replace a div with another div in ajax/javascript?

<div class="col" style="border-right:none; color: #FFFFFF;">
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<span>
<span class="style2">Enter you email here</span>:
</span>
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit" style="height:30px;"/>
<?php
if($_POST['email']!="")
{
mysql_connect("localhost","","");
mysql_select_db("");
error_reporting(E_ALL && ~E_NOTICE);
$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
if(!$sql)
die(mysql_error());
mysql_close();
}
?>
</form>
</div>
After the user got subscribed, I want to replace my subscription form and display the echo statement.
This code is running totally fine and is very good too; just want some more advantage with it.. ..
it shows like this
But i want to show it like this
my code now
<div class="col" style="border-right:none; color: #FFFFFF;">
<script>
var form = $('#form1');
$.ajax{
type:form.attr('method'),
url:form.attr('action'),
data:$("#form1").serialize(),
success: function(data){
if(data=="You have been successfully subscribed."){
$(".col").html("<div>Welcome</div>")
}
}
</script>
<form id="form1" method="post" action="index.php">
<span><span class="style2">Enter you email here</span>:</span>
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit" style="height:30px;"/>
<?php
if($_POST['email']!="")
{
mysql_connect("localhost","","");
mysql_select_db("");
error_reporting(E_ALL && ~E_NOTICE);
$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
if(!$sql)
die(mysql_error());
mysql_close();
}
?>
</form>
</div>
The ajax is used as agent between html and php, The details entered in html form is supplied to php through ajax and the result obtained from php is sent back through ajax.This can be done by php itself, but the use of ajax create a non-flickering page i.e a portion of webpage is updated without a full request.
var form = $('#form1');
$.ajax{
type:form.attr('method'),
url:form.attr('action'),
data:$("#form1").serialize(),
success: function(data){
if(data=="You have been successfully subscribed."){
$(".col").html("<div>Welcome</div>")
}
}
HTML code:
<HTML>
<BODY>
<div class="col">
<form id="form1" action="index.php" method="POST">
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit" style="height:30px;"/>
</form>
</div>
</body>
</html>
Update ajax code
var form = $('#form1');
$.ajax{
type:form.attr('method'),
url:form.attr('action'),
data:$("#form1").serialize(),
success: function(data){
if(data=="You have been successfully subscribed."){
$(".col").html("<div>Welcome</div>")
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
}
edit your php code like this;
if($result){
<script>
$(".class").hide(); // get input class name
</script>
echo "You have been successfully subscribed.";
}
after you submit the ajax you can simply hide the email input and button
$("#email").hide();
==========================================
<form id="form-search" method="post" onsubmit="return myFunction()" action="<?php echo $_SERVER['PHP_SELF'];?>">
then somewhere in your page
<script>
function myFunction(){
$("#email").hide();
$(".style2").hide();
$(".submit").hide();
return true;
}
</script>

How to add dynamic textbox (row) and save to database using PHP

I have here my Javascript code that adds dynamic textbox (row) my problem is how can I save the values from the dynamic textbox to database using PHP script? Hope you can help me guys.. Thanks!
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
My HTML code:
<form method="POST" action="#"> <table width="1024" border="0" cellspacing="6" cellpadding="0"> <tr>
<td width="195"><div class="user"><input type="text" name="user_a" id="user" tabindex="6"/></div></td>
<td width="410"><div class="reported"><input type="text" name="user_b" id="reported" tabindex="7"/></div></td>
<td width="399"><div class="reported"><input type="text" name="user_c" id="reported" tabindex="8"/></div></td>
<td width="10"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td> </tr> </table> </form>
You have to use just name of the text box which is added by dynamically.
$('form').submit(function() {
var data=($(this).serialize());
return false;
});
This function get all the elements value and create one string which is store in data, now data will pass in ajax call.
$('form').submit(function() {
var data=($(this).serialize());
$.ajax({
type: "POST",
url: "your_some.php",
data: data,
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
<html>
<head>
<title>Dynamic Form</title>
<script language="javascript">
<?php $i = 1; ?>
function changeIt()
{
//alert(i);
//var i = 1;
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext[<?php echo $i;?>]'><input type='text' name='mytext[<?php echo $i+1;?>]'><input type='text' name='mytext[<?php echo $i+2;?>]'><br>";
<?php $i = $i+3; ?>
}
</script>
</head>
<body>
<form name="form" action="http://localhost/try.php" method="post">
<!--<input type="text" name=t1>-->
<input type="button" value="test" onClick="changeIt()">
<div id="my_div"></div>
<p class="submit"><button type="submit">Register</button></p>
</body>
try.php(this is the file where you will be catching values and then inserting into sql
)
<?php
$var = $_POST['mytext'];
echo $var[1].$var[2];
?>

Categories