Popping an alert when Getting Information - php

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.

Related

On Dropdown Selection, how to fill complete form fields from Database

How to fill the complete form input fields from Database based on the value selected from the Dropdown
Example: In a Application, by selecting a client name it fills the complete form input fields with the details stored in the Database.
Sample Code:
<select name="client">
<option value="">-- Select Client Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
<input name="phone" type="text" value="">
<input name="email" type="text" value="">
<input name="city" type="text" value="">
<textarea name="address"></textarea>
All the about input fields need to be filled with values on client name selection.
EDIT:
I tried with AJAX but couldn't able get the particular variable from the file... below is my code:
<script>
$(document).ready(function() {
$('#client').change(function() {
alert();
var selected = $(this).find(':selected').html();
$.post('get_details.php', {'client': selected}, function(data) {
$('#result').html(data);
});
});
});
</script>
In the get_details.php file I am storing different values in different variables, but I didn't understand how to get them to individual variable to main page.
This is a just a basic jQuery example that calls itself (the top portion of the script is active when a $_POST is made), which I have named index.php as indicated in the url of the jQuery AJAX. You can use two separate pages to do this if you want. Just separate out the PHP from the HTML/Javascript and change the url: '/index.php':
<?php
// This is where you would do any database call
if(!empty($_POST)) {
// Send back a jSON array via echo
echo json_encode(array("phone"=>'123-12313',"email"=>'test#test.com','city'=>'Medicine Hat','address'=>'556 19th Street NE'));
// Exit probably not required if you
// separate out your code into two pages
exit;
}
?>
<form id="tester">
<select name="client" id="client">
<option value="">-- Select Client Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
<input name="phone" type="text" value="">
<input name="email" type="text" value="">
<input name="city" type="text" value="">
<textarea name="address"></textarea>
</form>
<!-- jQuery Library required, make sure the jQuery is latest -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: '/index.php',
type: 'post',
// This just sends the value of the dropdown
data: { client: $(this).val() },
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var Vals = JSON.parse(response);
// These are the inputs that will populate
$("input[name='phone']").val(Vals.phone);
$("input[name='email']").val(Vals.email);
$("input[name='city']").val(Vals.city);
$("textarea[name='address']").val(Vals.address);
}
});
});
});
</script>
When you made ajaxCall return data in json format like
json_encode(array("phone"=>'123-12313',"email"=>'test#test.com','city'=>'Medicine Hat','address'=>'556 19th Street NE'));
above shown
then parse it in jQuery and put the value in different selectors like
var Vals = JSON.parse(response);
// These are the inputs that will populate
$("input[name='phone']").val(Vals.phone);
above shown.

POST something using editable dropdown

I made an editable dropdown menu :
<html>
<body>
<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
<select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;" onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
<option></option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<input type="text" name="displayValue" placeholder="add/select a value" id="displayValue" style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;" onfocus="this.select()">
<input type="hidden" name="idValue" id="idValue">
</div>
</body>
</html>
I want to POST the value that was added, so as to include it in drop down for the next round.
I suggest you use jQuery for easy implementation. You can wrap them in a form and do the POSTing via jQuery Ajax then store that value somewhere for future use then append it to the next as the new option item.
POST via aJax
$(function() {
$('#form').on('submit', function(e) {
// do not reload the page
e.preventDefault();
// do the posting
var newValue = $('#displayValue').val();
$.post('http://MYURL.com/post.php', {
new_field: newValue
}, function(data) {
// success callback
$('#form > select').append('<option value="'+newValue+'">'+newValue+'</option>');
})
});
})
Basically, you post newValue to http://MYURL.com/post.php and handle that new data then the success callback will handle the inserting of the new value to your select.
the code is not tested, let me know if it did not work
Learn more about jquery.post() here and more about jquery here

PHP Ajax form store dropdown selection as variable

I have a php form where the user will select from a dropdown to see a data set. The data refreshes on the screen with the use of an ajax call. I am using the 'html' datatype so I can refresh the output into the appropriate div section.
The page refreshes with the correct data as expected, but I need to have the dropdown selection stored as a variable in php. I am not sure how to do this and spent the better part of a day doing research without success.
Here is the form:
<form action="" id="postForm" method="POST">
<select name="name" id="name">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" name="submit" id="submit" value="Go">
</form>
Here is the ajax:
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#Form').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
dataType : 'html',
url : '/?tmpl=component',
data: $('#postForm').serialize(),
success : function(data){
$('#waiting').hide(500);
$('#div-section-to-be-updated').html(data);
$('#message').text('Your data has been updated').show(500);
$('#message').hide(4000);
}
,
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#Form').show(500);
}
});
return false;
});
});
I want to store "name" as $name when the user clicks submit.
create session variable and store data in it.
session_start();
$_SESSION]['name'] = $_POST['name'];
Now you can simply access Session as a PHP variable.

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.

Simple PHP/AJAX question

Ok, so I am fairly new to webdeveloping, so probably a silly question:
I have this search form which does autocomplete for fooditems (gets values from a database column) and that works. Now when I press the submit button I want to load a block of code that displays the food-items' calories etc (also in the database on the same row as the food-item).
How can I accomplish such a thing. I kno this is a fairly broad question, but what i am really asking is, how can I make a small part of my website reload when pressing the submit button and using the input given in the text field as a parameter of some kind.
I don't need whole answers, just any tips getting to the right path would be greatly appreciated!
here my code for the input and button:
in head
<script type="text/javascript" src="jquery.js"></script>
<script>
function ok(){
$.post("test.php", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
}
</script>
in body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" onclick="ok()" />
</form>
or:
head:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script>
$("input[type='submit']").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
</script>
body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" />
</form>
jQuery and Ajax.
Change that input to a button
<button id="submit">Save</button>
For this I would do something like:
$("button#submit]").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
You need to first catch the click event .bind("click"). Then initiate an ajax call $.post which you will send data to. This data is received on the server via the POST array.
Like Josh said, jQuery is the way to go here.
You'll want to do 3 things:
Attach a click handler to a button like "onclick='doSomething();'"
In that function,use jQuery to do an async post to a script like
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
When this comes back, you can do something with that data(instead of the alert above), like $('#listnode').append... which would stick the HTML into your list
This is the general pattern, but you'll have to fit it to your scenario.
It is hard to answer your question from what little you have given us, but I will assume little knowledge.
Your input fields have to be inside a form tag. The form tag includes an action and a method. The method must be "POST" to send the data. The action can be any URL.
You simply have to name the URL of your php script that will handle the results.
It will find the data in $_POST['food'] etc. It has to build the reply page - the whole screen, with the food and data and the search form for the next submit if you want.
If you want to use AJAX to replace part of the screen, then you have a whole nother level of problems. The trick is to replace the content of a div tag with the requested data.

Categories