auto-populate drop down selection wont update/display - php

So I have been trying to figure this out for a couple days now, to no avail. I am trying to populate an html form with values query'd from mysql using php. im using a heredoc to push the form with values populated to the webpage, but I can't get the drop down list to populate. If someone is willing to help, if you could include a method on how to populate the radiobutton too, because that is my next task after the drop down list >_<.
The most recent thing I have tried, and is in the code below is from this post:
How do I programmatically set the value of a select box element using javascript?
but it still isnt working on execution.
I've googled a ton, looked at multiple stackoverflow posts, and even tried to find a youtube tutorial on how to do it. I am frustrated now and would like to get this bugger figured out.
here is my html:
<!DOCTYPE html>
<html>
<head>
<Script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function searchDB(){
//alert ("running searchDB")
var $request;
// abort any pending request
if ($request) {
$request.abort();
}
// setup some local variables
var $form = $("#searchForm");
// let's select and cache all the fields
var $inputs = $form.find("uniqueID");
// serialize the data in the form
var serializedData = $form.serialize();
if (alphaNumericCheck()) {
//disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
$request = $.ajax({
url: "SearchandUpdateIsaiah.php",
type: "POST",
data: serializedData
});
// callback handler that will be called on success
$request.success(function (response, textStatus, jqXHR){
// log a message to the console
$("#display").html(response);
});
// callback handler that will be called on failure
$request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
$request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
}
};
//makes sure all values submitted in form only contain a-z, A-Z, or 0-9 and no spaces.
function alphaNumericCheck() {
var regex = /^[a-zA-Z0-9]+$/;
if (!regex.test($("#uniqueID").val()))
{
alert("Please fix search term");
return false;
}
/*else if (!regex.test($("#lName").val()))
{
alert("Please fix last name");
return false;
}*/
else
{
return true;
}
};
</script>
</head>
<body>
<br>
Search form
<form id="searchForm">
Insert a uniqueID: <input type="text" id="uniqueID" name="uniqueID">
</form>
<input type="button" id="search" name="search" value="Search">
<script> $("#search").click(function(){searchDB();});</script>
<div id="display"> </div>
</body>
and here is my php:
<?php
//Search the database function
SearchDB();
Function SearchDB(){
$search=$_POST['uniqueID'];
//------------------------------------------------------------------------
//----------------------connect to database-------------------------------
//------------------------------------------------------------------------
$dbhost = '**********';
$dbuser = '**********';
$dbpass = '**********';
//connection to database, stored as $conn
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Could not connect: ' . mysql_error());
//------------------------------------------------------------------------
//----------------------connect to database-------------------------------
//------------------------------------------------------------------------
mysql_select_db("test_db",$conn);
$likeSearch = $search.'%';
$sql = "SELECT * FROM alumni WHERE uniqueID = '$search' OR last_name LIKE '$likeSearch'";
$result = mysql_query($sql,$conn);
$resultsArray = array();
if (!$result) {
echo "worked";
$resultCount=0;
}else {
while ($row = mysql_fetch_assoc($result)) {
$resultsArray[] = array(
'uniqueID' => $row['uniqueID'],
'fName' => $row['first_name'],
'lName' => $row['last_name'],
'salary' => $row['salary'],
'company' => $row['company']
);
}
$resultCount = Count($resultsArray);
}
if ($resultCount>1) {
//return list of names
//echo $resultCount. "\n";
foreach ($resultsArray as $value){
$string = "First name: {$value[fName]} Last name: {$value[lName]} Unique ID: {$value[uniqueID]} \n";
$textReturn = $textReturn.$string;
};
$textReturn = $textReturn."Copy and paste the UniqueID of the student whose data you wish to retrieve.";
$c = <<<TEXT
</br> <textarea rows="{4*$resultCount}" cols="75">{$textReturn}</textarea>
TEXT;
echo $c;
}elseif ($resultCount===1) {
//return form of data
foreach ($resultsArray as $value){
$formFirstName = $value[fName];
$formLastName = $value[lName];
$formSalary = $value[salary];
$formCompany = $value[company];
};
$c = <<<TEXT
<!DOCTYPE html>
<html>
<head>
<Script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function submit(){
var $request;
// abort any pending request
if ($request) {
$request.abort();
}
// setup some local variables
var $form = $("#alumniForm");
// let's select and cache all the fields
var $inputs = $form.find("fName, lName, company, salary, submit");
// serialize the data in the form
var serializedData = $form.serialize();
if (alphaNumericCheck())
{
//disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
$request = $.ajax({
url: "main2.php",
type: "POST",
data: serializedData
});
// callback handler that will be called on success
$request.done(function (response, textStatus, jqXHR){
// log a message to the console
$("#ajaxInfo").html(response).show();
});
// callback handler that will be called on failure
$request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
$request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
}
else
{
}
};
//makes sure all values submitted in form only contain a-z or A-Z and no spaces.
function alphaNumericCheck() {
var $regex = /^[a-zA-Zs]+$/;
if (!$regex.test($("#fName").val()))
{
alert("Please fix first name");
return false;
}
else if (!regex.test($("#lName").val()))
{
alert("Please fix last name");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form id="alumniForm">
<h3>Alumni Form</h3>
<br/>
<input type='hidden' name='submitted' id='submitted' value='alumni'/>
Input name <br/>
First Name: <input type="text" name="fName" id="fName" value="{$formFirstName}">
Last Name: <input type="text" name="lName" id="lName" value="{$formLastName}">
<br>
Select user company name from a dropdown list <br/>
<script>
var element = document.getElementById('company');
element.value = {$formCompany};
$('#company').selectmenu('refresh');
</script>
<select name="company" id="company">
<option value=""></option>
<option value="Proctor & Gamble">Proctor & Gamble</option>
<option value="General Electric">General Electric</option>
<option value="PwC">PwC</option>
<option value="McDonalds">McDonalds</option>
</select>
<br>
Select user salary range using radio buttons
<br>
<input type="radio" id="salary" name="salary" value="LT30000">Less than $30,000<br>
<input type="radio" id="salary" name="salary" value="30000">$30,000-$40,000<br>
<input type="radio" id="salary" name="salary" value="40000">$40,000-$50,000<br>
<input type="radio" id="salary" name="salary" value="50000">$50,000-$60,000<br>
<input type="radio" id="salary" name="salary" value="60000">$60,000-$70,000<br>
<input type="radio" id="salary" name="salary" value="70000">$70,000-$80,000<br>
<input type="radio" id="salary" name="salary" value="80000">$80,000-$90,000<br>
<input type="radio" id="salary" name="salary" value="90000">$90,000-$100,000<br>
<input type="radio" id="salary" name="salary" value="GT100000">Greater than $100,000
</form>
<br/>
<input type="submit" id="submit" name="submit" value="ADD/UPDATE" onclick="javascript:submit()"/> <br/>
<br><textarea id="ajaxInfo" rows="4" cols="75"> display php return </textarea><br/>
</body>
</html>
TEXT;
echo $c;
}else {
echo "No results found \n";
};
mysql_close($conn);
}
?>
THANKSOMUCH!!

"auto-populate drop down selection wont update/display"
You're never using the PHP to update the selector neither is the javascript doing anything.
You create
select name="company"
But you never update it. That's why nothing happens.
Also:
$('#company').selectmenu('refresh');
Shouldn't do anything because you haven't declared the existance of #company, yet.

Related

Insert records to mysql database with php using Ajax

How to do coding of this Code With Using Ajax.Please Help.
I am Bignner here and i have written this code it's working but i want to use with ajax this because don't want to reload the page...?
PHP File
//Code For Making Form And getting Data…..
<html>
<body>
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
<form action="Form_Data.php" method="post">
ID: <input type="text" name="ID"><br><br>
NAME: <input type="text" name="NAME"><br><br>
PASSWORD: <input type="text" name="PASSWORD"><br><br>
CREDITS: <input type="text" name="CREDITS"><br><br>
E_mail: <input type="text" name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" name="MODIFIED_ON"><br><br>
<input type="submit">
</form>
</body>
</html>
//code for taking data from form data.
<html>
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`ID`,`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$ID','$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
$retval=mysql_query($query,$conn);
if ($query_run)
{ echo 'It is working';
}
mysql_close($conn);
?>
</html>
I have Tried Yet ... Is Blewo...
file for html and ajax
<html>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</HEAD>
<body>
<div id="status_text">
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
<form onsubmit="return false" method="post">
ID: <input type="text" id="ID" name="ID"><br><br>
NAME: <input type="text" id="NMAE" name="NAME"><br><br>
PASSWORD: <input type="text" id= "PASSWORD"name="PASSWORD"><br><br>
CREDITS: <input type="text" Id= "CREDITS"name="CREDITS"><br><br>
Email_ID: <input type="text" id="Email_ID"name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" id="CREATED_ON" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" id="MODIFIED_ON" name="MODIFIED_ON"><br><br>
<input type="submit" id="btn_submit" name="submit" value="Send">
</div>
<script>
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
//make the postdata
var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&REDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
});
$.ajax({
url : "Form_Data.php",
type: "POST",
data : postData,
success: function(data,status, xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}
});
</script>
</form>
</body>
</div>
</html>
code for query...
<html>
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`ID`,`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$ID','$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
$retval=mysql_query($query,$conn);
if ($query_run)
{ echo 'It is working';
}
mysql_close($conn);
?>
</html>
I have Solved It ... How To Use Ajax and MYSQL...
PHP CODE
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
// $retval=mysql_query($query,$conn);
if ($query_run)
{
echo 'It is working';
}
mysql_close($conn);
?>
HTML FILE....
<html>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</HEAD>
<body>
<div id="status_text">
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
ID: <input type="text" id="ID" name="ID"><br><br>
NAME: <input type="text" id="NAME" name="NAME"><br><br>
PASSWORD: <input type="text" id= "PASSWORD"name="PASSWORD"><br><br>
CREDITS: <input type="text" Id= "CREDITS"name="CREDITS"><br><br>
Email_ID: <input type="text" id="EMAIL_ID"name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" id="CREATED_ON" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" id="MODIFIED_ON" name="MODIFIED_ON"><br><br>
<input type="submit" id="btn_submit" name="submit" value="Send"/>
</div>
<script>
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
} }
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
// make the postdata
// var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&CREDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
// alert(postData);
var myData={"ID":ID,"NAME":NAME,"PASSWORD":PASSWORD,"CREDITS":CREDITS,"EMAIL_ID":EMAIL_ID,"CREATED_ON":CREATED_ON,"MODIFIED_ON":MODIFIED_ON};
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
$.ajax({
url : "Form_Data.php",
type: "POST",
data : myData,
success: function(data,status,xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}
});
});
</script>
</body>
</div>
</html>
change your script because your ajax was outside the click function
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
//make the postdata
var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&REDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
$.ajax({
url : "Form_Data.php",
type: "POST",
data : postData,
success: function(data,status, xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}
});
});
</script>
and change your php code to this
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
if(isset($_POST['NAME'])){
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`ID`,`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$ID','$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
$retval=mysql_query($query,$conn);
if ($query_run)
{ echo 'It is working';
}
}
mysql_close($conn);
?>
In this code I'm just submitting your two input fields, the rest you can add by yourself. Try this:
<html>
<body>
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
<form action="Form_Data.php" method="post">
NAME: <input id="name" type="text" name="NAME"><br><br>
PASSWORD: <input id="password" type="text" name="PASSWORD"><br><br>
<input type="submit" id="submit">
</form>
</body>
</html>
$("#submit").click(function() {
var name= $("#name").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "your_php_path.php",
data: 'name=' + name+ '&password=' + password,
success: function(result) {
alert(result);
}
});
});

jquery ajax loaded form submit sets serialized data into url

Im making some web appication which loads pages without refresching te page. This all works great but now i have a form on one of these pages. I want to submit the form without the page to refresh. But when i submit the form after i loaded it with ajax the url in the browser will change from
localhost/documents/projects/test/
to
localhost.documents/projects/test/?form_type=register&Username=&first_name=&surname_prefix=&surname=&surname=&email=
When i just put the form html in my index.php and submit it there it works fine.
I hope someone can tell me what im doing wrong and how to fix it.
part of index.php
<div class="message"></div>
<div id="content">
<div id="page">
<div class="form_container">
<form id="form">
<input type="hidden" name="form_type" value="register" />
<input class="type_text" type="text" name="username" maxlength="20" placeholder="username" />
<input class="type_text" type="text" name="first_name" maxlength="50" placeholder="First Name" />
<input class="type_text" type="text" name="surname_prefix" maxlength="20" placeholder="Surname Prefix" />
<input class="type_text" type="text" name="surname" maxlength="50" placeholder="Surname" />
<label class="label" for="birth_date">dd-mm-jjjj</label>
<input id="birth_date" class="type_text" type="text" name="birth_date" maxlength="10" placeholder="Birth Date" />
<input class="type_text" type="text" name="email" placeholder="Email Address" />
<input class="type_submit" type="submit" value="Register" />
</form>
</div>
</div>
pageHandler.js
$(document).ready(function() {
var request;
//page handler
//pageRequest('home');
$('.click').click(function(event) {
var temp = $(this).attr('id');
var pages = ['home','register'];
if($.inArray(temp, pages) !== -1) {
pageRequest(temp);
//$('.message').html(temp);
}
event.preventDefault();
});
function pageRequest(temp) {
var page = $('#page');
if(typeof ajax_request !== 'undefined') {
request.abort();
}
request = $.ajax({
type: "POST",
url: "core/posts.php",
data: 'temp=' + temp
});
request.done(function(data) {
page.fadeOut(function() {
page.html('');
page.html(data).fadeIn();
});
});
request.fail(function(jqXHR, textStatus) {
page.fadeOut(function() {
page.html('');
page.html(textStatus).fadeIn();
});
});
}
//form handler
$('#page').delegate( "#form", "submit", function(event) {
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
formRequest(serializedData);
event.preventDefault();
});
function formRequest(values) {
var message = $('.message');
if(typeof ajax_request !== 'undefined') {
request.abort();
}
request = $.ajax({
url: "core/posts.php",
type: "POST",
data: values
});
request.done(function(data) {
message.fadeOut(function() {
message.html('');
message.html(data).fadeIn();
});
});
request.fail(function(jqXHR, textStatus) {
message.fadeOut(function() {
message.html('');
message.html(textStatus).fadeIn();
});
});
}
});
posts.php
If(isset($_POST['temp'])) {
$temp = $_POST['temp'];
$url = '../content/templates/'.$temp.'.html';
if(file_exists($url)) {
$html = file_get_contents($url);
echo $html;
}
else {
echo 'Sorry, couldn\'t find the page.';
}
}
//form handler
if(isset($_POST['form_type'])) {
require_once('../admin/config/database.functions.php');
$function = new myDBFunctions();
switch($_POST['form_type']) {
case 'register' :
$username = $_POST['username'];
$firstname = $_POST['first_name'];
$surnamep = $_POST['surname_prefix'];
$surname = $_POST['surname'];
$birthdate = $_POST['birth_date'];
$email = $_POST['email'];
echo 'Thanks for your registration';
break;
case 'login' :
echo 'login';
break;
case 'password_recovery' :
echo 'password recovery';
break;
}
}
I have found the problem but not why it occured. I had a $_POST['username'] in my posts.php file while the the name of the html input field was Username. I have changed this and now the url in the browser doesn't change anymore. I'm happy I've found the problem but i still dont get why the data send by ajax would appair in the url.
"I want to submit the form without the page to refresh"
There are a few ways to do this, I think the easiest is to intercept and stop the form from actually submitting like a regular HTML form and instead make an ajax call with the data in the form fields.
To do this, you will need to intercept the submit event of the form, get the values of all the inputs in the form and make an ajax call with the data to the server:
<form id="myForm">
....
</form>
<script>
$('#form').on("submit", function(event) {
// stop the form from submitting
event.preventDefault();
// get data in the inputs of the form
var data = {};
var $inputs = $('#form').children("input, select, textarea");
inputs.each(function($element){
data[$element.attr('name')] = $element.val();
});
// submit data to the backend
request = $.ajax({
type: "POST",
url: "",
data: data
});
});
</scipt>

No alert in success function

I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>

Ajax won't post form data to PHP script

I got a form with some data that needs to be sent and I want to do it with ajax. I got a function that respond on an onclick event of a button. When I click the button I got some post data in firebug but it just doesn't reach my PHP script. Does anyone know what's wrong?
JS:
function newItem() {
var dataSet = $("#createItem :input").serialize();
confirm(dataSet); //Below this code box is the output of this variable to check whether it is filled or not
var request = $.ajax({
type: "POST",
url: "/earnings.php",
data: dataSet,
dataType: "json"
});
request.done(function(){
$('.create_item').children(".row").slideUp('100', 'swing');
$('.create_item').children("h2").slideUp('100', 'swing');
confirm("succes");
});
request.fail(function(jqXHR, textStatus) {
confirm( "Request failed:" + textStatus );
});
}
dataSet result when the form is completly filled in:
id=123&date=13-09-2013&amount=5&total=6%2C05&customer=HP&invoicenumber=0232159&quarter=1&description=Test
The PHP:
<?php
include('includes/dbconn.php');
function clean_up($string){
$html = htmlspecialchars($string);
$string = mysql_real_escape_string($html);
return $string;
}
if($_POST){
$date = clean_up($_POST['date']);
$amount = clean_up($_POST['amount']);
$total = clean_up($_POST['total']);
$customer = clean_up($_POST['customer']);
$invoicenumber = clean_up($_POST['invoicenumber']);
$quarter = clean_up($_POST['quarter']);
$description = clean_up($_POST['description']);
$sql = ("INSERT INTO earnings (e_date, e_amount, e_total, e_customer, e_invoicenumber, e_quarter, e_description)
VALUES ($date, '$amount', '$total', '$customer', $invoicenumber, $quarter, '$description')");
echo $sql;
if($mysqli->query($sql) === true){
echo("Successfully added");
}else{
echo "<br /> \n" . $mysqli->error;
}
}
?>
The form works fine without the ajax but with it it just doesn't work.
Your help is appreciated!
Try this snippet code bro...
<form id="F_login">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: '/earnings.php',
data: parm,
success: function (data,status,xhr) {
console.info("sukses");
},
error: function (error) {
console.info("Error post : "+error);
}
});
});
Reply me if you try this...
prevent your form submitting and use ajax like this:
<form id="createItem">
<input id="foo"/>
<input id="bar"/>
<input type="submit" value="New Item"/>
</form>
$('#createItem).on("submit",function(e){
e.preventDefault;
newItem();
});
Try this
<input type="text" id="foo"/>
<input type="text" id="bar"/>
<input type="button" id="btnSubmit" value="New Item"/>
<script type="text/javascript">
$(function() {
$("#btnSubmit").click(function(){
try
{
$.post("my php page address",
{
'foo':$("#foo").val().trim(),
'bar':$("#bar").val().trim()
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>

How to Inform user about ajax submission?

add.php - html markup.
dbadd.php - serverside script,
addpg.js - clientside including AJAX
RSV- form validator
I'm trying to do following: First validate the form (with RSV), if all things right, Then ajax submit (That's why i'm using myOnComplete). Inform user about submission. If user pressed for the first time save button then insert into db. Else update db.
The problems are:
It inserts data into db table but doesn't inform about succes or error
I can't figure out how to insert data into db If user pressed for
the first time save button or update data.
Tried all possible ways. There is no error. Please anyone help me to fix that.
addpg.js
function myOnComplete() {
return true;
}
$(document).ready(function () {
$("#add_form").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Name field required.",
"required,title,Title field required.",
"required,menu, Menu field required",
"required,parentcheck,Parentcheck required",
"if:parentcheck=1,required,parent,Parent required",
"required,content,Page content field required"
]
});
});
$("#submit_btn").click(function () {
CKEDITOR.instances.content.updateElement();
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
if (message != null) {
//do what you like with the message
}
if (err != null) {
//do what you like with the erro
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
});
dbadd.php
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
if ($new_id>0){
echo "{";
echo '"msg": "All right" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
add.php
<div id="add">
<form id="add_form" method="" action="">
<input type="text" name="name" id="name" size="40" value="" class="text-input" />
<input type="text" name="title" id="title" size="40" value="" class="text-input" />
<select name="menu" id="menu">
<option value="" selected="selected">sample</option>
<option value="1">sample 1</option>
<option value="2">sample 2</option>
<option value="0">sample 3</option>
</select>
<input type="radio" class="parentcheck" name="parentcheck" value="0"/>
<input type="radio" class="parentcheck" name="parentcheck" value="1"/>
<select name="parent" id="parent"></select>
<textarea id="content" style="width:100%" name="content"></textarea>
<input type="submit" name="submit" class="button" id="submit_btn" value="Save" />
</form>
</div>
<script type="text/javascript" src="../../core/includes/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/addpg.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/rsv.js"></script>
For the first problem:
Without actually running the code or seeing a live example, I can't say for sure, but it looks like you have the right idea and it's just a syntax/usage error. For example:
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
Someone please scold me if I'm wrong, but aren't "msg" and "err" found in the JSON (result) rather than in xResponse? result.msg (or result["msg"]) and result.err (or result["err"])
If so, also be aware that I -believe- you will get an 'undefined' error when trying to declare both of those variables since only one of them will be present. You might want to wrap them in try/catch blocks.

Categories