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.
Related
I have the following HTML form in signup.php:
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
I am trying to submit the form using ajax, without page refresh:
<!-- include files -->
<?php include 'assets/config.php';?>
<?php if(isset($_SESSION["CUSTOMER_ID"])){
header('Location: myaccount.php'); } ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('assets/login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
I am posting the form to do_signup_check.php and running a query to see if the user is already registered. echo 1 for a positive result and 0 for a negative result:
Do_Signup_Check.php:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn)); }
if(mysqli_num_rows($check) > 0){
echo '1';
}else{
echo '0';
}
?>
If the result is 0 then the ajax should load my page do_signup.php.
But alas it is not getting this far. It was working and then i switched off the computer and came back to it and now it won't work.
Please can someone show me where I've gone wrong?
if(result == 0){ here result is not using in success function:
you must need to pass resultant variable here:
success: function () {
as:
success: function (result) {
Now, you can use your condition if(result == 0){
Second, i suggest you to pass dataType: 'html' in your ajax request.
Edit:
You are using <?php if(isset($_SESSION["CUSTOMER_ID"])){ line in your code, if you are not using session_start() in your code then this check will not work.
For this line data:{"name":name,"email":email}, i didnt see name and email in your code, where you define these 2 variables which you are using in your ajax params.
Problem: How can I update a form's select input values and text input fields based on a MySQL query after select input's onchange event is fired?
What I've tried:
I have tried to use AJAX with post and get data types, calling a php file that runs the query and echoes the results. Nothing displays. Any errors I have gotten along the way are usually small things that result in server 500 error. I have placed console.log statements in the function that runs the JQuery AJAX request. The change event was detected, the ajax success was called. I also tried using .load(), with GET and POST, no luck either. I have other features that implement AJAX, and I've tried modifying them to fit this scenario and have been unsuccessful.
I also tried to only use a select input that when changed would use AJAX request and .load function to display the other inputs which would be formatted on the php side and echoed to page with selected and values reflecting the db result.
What I want:
I would like a simple example of a form with a select input with three options, text type input, and a submit button. The form is a client backend form to send updates to the MySQL db. Each input represents a filed in the db. The idea is that when the user changes the select inputs selected value, a query is done that uses the selected value for only returning one result. Each field of that one records values in db should now be reflected in the form. First, tell me if this is the correct way to approach this problem, and if not show me how you would.
Example index.php:
<form action="editForm.php" method="POST" enctype="multipart/form-data">
<select id="contact_name" name="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" name="age" placeholder="Age" required>
<input type="text" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
When on change event for #contact_name is fired I need to update the fields with the values the db has.
How would you implement this? Thanks in advance.
Update: as requested here is my JQuery code, but I know my example doesn't use the same names.
<script type="text/javascript">
$(document).ready(function(){
$('#currency_select').on('change', function (e) {
$.ajax({
type: 'post',
url: 'getCurrentValues.php',
data: {currency: 'EUR'},
success: function () {
console.log('ajax was submitted');
}
});
});
});
</script>
Here is my understanding of how to do this:
First, detect event and pass data via ajax for the query to retrieve record. This is in the document ready function to ensure DOM is ready.
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function () {
console.log('ajax was submitted');
}
});
};
editForm.php:
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
$age = $row['age'];
}
<input type="text" name="age" value="<?php echo $age; ?>">
<?php
}
?>
your index:
<select id="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<form action="editForm.php" id="form" method="POST" enctype="multipart/form-data">
<select name="contact_name" id="contact_form" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" id="age" name="age" placeholder="Age" required>
<input type="text" id="race" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
$("#contact_name").on("change", function() {
var selected = $(this).val();
$("#form").load("formdata.php?contact="+selected); //normaly you do that with an id as value
OR
$.ajax({
type:"POST",
url:"formdata.php",
data: {user: selected},
dataType: "json",
success: function(response){
if(response.status == "success") {
$("#age").val(response.age);
$("#race").val(response.race);
$("#veteran_status").val(response.status);
} else {
alert("No data found for this user!");
}
});
});
and in your formdata.php file
//make your db-query
then either make the actual input fields which will be displayed if you use load
OR make something like if you use the ajax version
if($result) {
echo json_encode(array("status" => "success",age" => $result["age"], "race" => $result["race"], "status" => $result["status"]));
} else {
echo json_encode(array("status" => "failed"));
}
also you can delete the action, method and enctype in your form, as this will be set in the ajax function ;)
I would advice you to use the userid as the value in your select field, and you will also need to either also fill the contact_name IN the form OR make an hidden input field so that you can submit the form and know whos data this is..
just echo the $age variable in your editForm.php file and in the AJAX call success function alert the response. like so-
editForm.php
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
echo $age = $row['age'];
}
}
?>
Ajax file
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function (response) {
alert(response);
console.log(response);
}
});
};
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
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.
How can i display an alert message or alert box when getting the information(not submitting)
i have few form structures(text type) in my html when i enter the id in one of the form and press get button all the other forms will be filled based on the form submitted.
for the above i am using json and jquery
Ex:
Jquery
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='name']").val(json.name);
$("input[name='age']").val(json.age);
$("#institution").val(json.institution);
}, "json");
});
json:
$abc_output = array('title' => $row['title'],'name' => $row['name'],'age' => $row['age'], 'institution' => $row['institution']);
echo json_encode($abc_output);
now the problem is all the id's will not be having information so when the user enters some id with no information pop up or alert box need to be submitted saying no id.
How can i do that?
Note: as it is get info the result will be displayed on the same page, if its submit i could have echoed id not found in DB in the server side php(script_1.php) which is not the case here.
Html:
id: <input type="text" name="id"/>
<div id="hidden" style="display: none;">
<p>Title:<input type="text" name="title"/></p>
<p>name:<input type="text" name="rno"/></p>
<p>age:<input type="text" name="age"/></p>
Institution: <select id="institution" name="institution">
<option value="None">-- Select --</option>
<option value="ab">ab</option>
<option value="bc">bc</option>
</select>
</div>
<br/>
<input type="button" id="button1" value ="Get Info" onclick="document.getElementById('hidden').style.display = '';"/>
</form>
<div id="age"></div>
</body>
</html>
It may be helpful to set up an AJAX error handler, to handle things like session timeouts, json 'parseerror', etc.
$(document).ajaxError(function() {
alert( "Triggered ajaxError handler." );
});
This can help you to determine if the problem is with the success callback not being called.
You didn't post your opening <form> tag, but i'm assuming it has an id of 'myForm' (which you won't need).
I checked your javascript, and found a syntax error (a missing });). Try this:
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]').val() }, function(json) {
$("input[name='title']").val(json.title);
$("input[name='name']").val(json.name);
$("input[name='age']").val(json.age);
$("#institution").val(json.institution);
}, "json");
});
});
Notice I removed #myForm from the part that passes the values to php. The form itself does not have a value, the individual fields do.