I have a form with 5 fields.
Name
Last Name
Date of Birth
Occupation
Place of Birth
When user fills name and last name, I want the rest of the form to be filled from database without refreshing the page or user doing anything.
I am using php and jquery.
Here is my html page:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" name="name" id="name">
<input type="text" name="lastname" id="lastname">
<input type="text" name="occupation" id="occupation">
<input type="text" name="date_of_birth" id="date_of_birth">
<input type="text" name="place_of_birth" id="place_of_birth">
<script type="text/javascript">
$('#lastname').blur(function ()
{
var name = $("#name").val();
var lastname = $("#lastname").val();
$.ajax({
url: "get.php",
type: "POST",
data: "name="+name+"&lastname="+lastname,
success: function(data)
{
if (data == "Error")
{
alert("error-1"+data);
}
else
{
var fields = data.split(",");
if (fields.length < 3)
{
alert("error-2"+data);
}
else
{
$("#occupation").val(fields[0]);
$("#date_of_birth").val(fields[1]);
$("#place_of_birth").val(fields[2]);
}
}
},
error: function(xhr, status, error)
{
alert("error-3"+data);
}
});
});
</script>
</body>
</html>
Here is the php page:
<?php
$name= $_REQUEST['name'];
$lastname= $_REQUEST['lastname'];
if($name == "mike" && $lastname = "brown")
{
echo "cook,1980-10-10,NYC";
}
?>
It works now.
-- Edit #1
Maybe this example can help you to understand how to use it:
$.ajax({
url: "phppage.php",
type: "POST", // Or get as you like
data: "name="+name+"&lastname="+lastname,
success: function(data)
{
// As i said, here in "data" you have what the server returned
// You can return the last field delimited with a , and do something like:
if (data == "Error")
{
// If something went wrong in your Database or invalid "name" or "last name"
// You can return "Error" in the PHP page so the Javascript know something is wrong
// and handle this error
}
else
{
var fields = data.split(",");
if (fields.length < 3) {
// As above.
// Something went wrong or invalid response
}
else
{
// In fields array you have what server said.
// Here you can reload the page, change page do what you want
}
}
},
error: function(xhr, status, error)
{
// Error here
}
});
It pass name and lastname to the server and wait for a response like:
field1,field2,field3
The PHP page should be something like..
<?php
// Connect to the server
// Send query to the server
if ($isEverythingOK) {
echo $field1 . "," . $field2 . "," . $field3;
}
else {
echo "Error";
}
?>
Ajax - jQuery Ajax + PHP page
A php page where you pass the 5 fields, add it in the database and return something like "OK" if everything is OK or an error if something went wrong.
Example
$.ajax({
url : "URL to PHP page",
success : function (data) {
if (data === "OK") { /* all ok, here you can update the page to show the new field */ alert("OK"); }
else { /* Error */ alert("Error"); }
},
error : function (xhr, status, error) {
// Request error
alert("Error");
}
});
Related
I know that it may be so tricky!
In detail:
on the blog detailing page(blog-single.php/title) I have a subscription form this subscription form is working fine on another page with the same PHP action file and ajax
and blog-single.php/title is also working fine until I did not submit the form
On this page in the starting, I have bellow query
<?php
$query_head="SELECT * FROM blog_post WHERE friendly_url = '{$_GET['url']}' ";
$result_head= $fetchPostData->runBaseQuery($query_head);
foreach ($result_head as $k0 => $v0)
{
//----- some echo
}
?>
and my subscription form code:
<form action="" method="post" class="subscribe_frm" id="subscribe_frm2">
<input type="email" placeholder="Enter email here" name="email" id="subscribe_eml2">
<button type="button" id="subscribe2">Subscribe</button>
</form>
and ajax code is bellow:
$(document).ready(function() {
$("#subscribe2").click( function() {
subscribe_frm_val2 = false;
/*email validation*/
var emailReg2 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($("#subscribe_eml2").val().length <= 0) {
$("#subscribe_eml_Err2").html("Required field");
//console.log("Required");
subscribe_frm_val2 = false;
}
else if(!emailReg2.test($("#subscribe_eml2").val()))
{
$("#subscribe_eml_Err2").html("Enter a valid email");
}
else{
$("#subscribe_eml2").html("");
subscribe_frm_val2 = true;
//console.log("final else");
if(subscribe_frm_val2 == true)
{
console.log("frm true");
var form = $('#subscribe_frm2')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "updation/subscribe_action.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 6000000,
beforeSend: function(){
// Show image container
$("#submition_loader").show();
//alert ("yyy");
},
success: function (data) {
// console.log();
$(document).ajaxStop(function(){
$("#subscribe_eml_Err2").html(data);
});
},
complete:function(data){
// Hide image container
$("#submition_loader").hide();
}
});
}
else{
alert('Please fill all required field !');
}
}
});
});
When I submit my form above the first query is giving a warning like below:
Warning: Invalid argument supplied for foreach() in D:\xamp\htdocs\my\bootstrapfriendly\category.PHP on line 13
and after warning page doing misbehave
I think the error because of URL passing but I am not sure how to solve it
Please help me with solving it.
Thank's
I got the solution
its very simple just converted my relative URL into an absolute URL
I just created a PHP function for base URL
function base_url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
and then using this base URL function inside script like this
$.ajax({
----
url: "<?php echo base_url()?>/updation/subscribe_action.php",
-----
});
Trying to get jQuery to send the content of a textarea to update a record but it won't. When I change the value of the textarea so that it begins with a number then it sends fine. I can verify that the content is handed to the JS function successfully by using alert(), but it won't get to the PHP file. All other JS functions work fine.
Edited to add more code which may be relevant.
Javascript:
<script>
function add_vid(t) {
if ($('#vref').val().length <5) return;
var vref = $('#vref').val();
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { 'a':'add_vid', 't':'<?=$_SESSION['t']?>', 'vref':vref},
beforeSend:function(){
$('#add_vid_status').html('Adding...');
},
success:function(data){
if (data == 'added') {
$('#add_vid_status').html('Added');
$('#vid_list').prepend('<div align="center" class="vid">'+vref+'</div>');
$('#vref').val('');
}
else $('#add_vid_status').html('Error');
},
error:function(){
$('#add_vid_status').html('Error');
}
});
}
function del_vid(id) {
var confirmdel = confirm('Delete ?');
if (confirmdel) {
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { 'a':'del_vid', 't':'<?=$_SESSION['t']?>', 'id':id},
success:function(data){
if (data == 'deleted') {
$("#v"+id).hide(900);
}
},
error:function(){
//$("#"+msg_id+'_a').html('error');
}
});
}
return false;
}
function update_vid(id) {
vref = $("#update"+id).val();
alert(vref);
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { 'a':'update_vid', 't':'<?=$_SESSION['t']?>', 'id':id, 'vref':vref},
success:function(data){
alert(data);
if (data == 'updated') {
$("#if"+id).html(vref);
}
},
error:function(){
//$("#"+msg_id+'_a').html('error');
}
});
return false;
}
function move_vid(id,dir) {
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { 'a':'move_vid', 't':'<?=$_SESSION['t']?>', 'id':id,'dir':dir},
success:function(data){
pos = data.split('_');
pos_from = pos[0];
pos_to = pos[1];
//$("#if"+id).hide();
if ($("#pos"+pos_to).length) {//if the id2 is on page (and not on a different paginated page) - swap them on-screen
temp_html = $("#pos"+pos_from).html();
$("#pos"+pos_from).html($("#pos"+pos_to).html());
$("#pos"+pos_to).html(temp_html);
temp_html = null;
}
else $("#pos"+pos_from).html('<div>Video moved off page.<br> Reload to see the result.</div>');
//$("#if"+id).fadeIn(400);
},
error:function(){
//$("#"+msg_id+'_a').html('error');
}
});
return false;
}
</script>
HTML:
<textarea name="vref" cols="55" rows="3" id="vref" placeholder="Video embed code"></textarea>
<input type="button" value="Add" onclick="add_vid('<?=$_SESSION['t']?>')"> <span id="add_vid_status"></span>
<input type="button" value="update" onClick="update_vid(27)">
<textarea cols="65" rows="3" id="update27"><iframe src="http://player.vimeo.com/video/123456789?byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></textarea>
PHP code:
<?
session_start();
if ($_SESSION['auth'] != 1 || $_POST['t'] != $_SESSION['t']) exit();
elseif (isset($_POST['a'])) {
require_once('cfg.php');
db_connect();
if ($_POST['a'] == 'add_vid' && strlen($_POST['vref'])>4) {
//ADDS VIDEO TO DB AND ECHOES "added"
}
elseif ($_POST['a'] == 'del_vid' && is_numeric($_POST['id'])) {
//DELETES VIDEO AND ECHOES "deleted"
}
elseif ($_POST['a'] == 'update_vid' && is_numeric($_POST['id']) && strlen($_POST['vref']>4)) {
$id = (int)$_POST['id'];
//echo 'PHP: '.$_POST['vref']; (here i can test if the argument reaches.)
$vref = mysql_real_escape_string($_POST['vref']);
$q = mysql_query("UPDATE `videos` SET `vref`='{$vref}' WHERE `id`={$id}") or die ('update error: '.mysql_error());
if ($q) echo 'updated';
}
// CODE GOES ON...
}
?>
You've got a typo in your Ajax data object:
't':'<?=$_SESSION['t']?>'
You use the same type of quotes twice, so Javascript thinks that t is a variable, and doesn't recognise it. Changing your quotes like this fixes the error that your code was throwing:
't':'<?=$_SESSION["t"]?>'
Otherwhise, if you did mean for this to be a variable, you need to use it as following:
't':'<?=$_SESSION["'+ t +'"]?>'
After abandoning the update feature, yesterday when I wanted to copy the code for a similar project I noticed the glaring mistake in the PHP code where I am checking the string length: I had written strlen($_POST['vref']>4) instead of strlen($_POST['vref'])>4. After
correcting this it works perfectly.
I tried to simply the code as much as possible so you can recreate the scenario.
I do not understand why the data insert will fail since both $('#qcategory').val() and $('#qtype').val(); are all simply value =1.
The ajax will be always return error with undefined data.
I do not understand where is the data went wrong after the json passed into php.
Does it mean that once the json data is passed into php, as I decoded and return it from php?
What eaxactly is the data returned with print $users->addQ($user)?
It has been days I stuck on this problem. I must missed something really really important. Please help me figure this out! Will really really appreciated!
If you do not understand the question, please inform me about what you are not clear of.
Vote down does not really help what so ever if its because you are not able to resolve the problem. Thank You
quiz_controller.js
$(function() {
$(document).on("click", "input#done-add-question", function(){ addQuestion(this); });
});
function addQuestion(element) {
alert('add_question ran!');
$('#indicator').show();
var User = new Object();
User.qcategory = $('#qcategory').val();
User.qtype = $('#qtype').val();
$.ajax({
type: "POST",
url: ".../controller/quiz_controller.php",
dataType: "json",
data: {
//"page":page, //page: value in the url php : currentpage: value in js
action: 'add_question',
user: userJson
},
success: function(data, textStatus) {
alert('add_question works!');
$('#indicator').hide();
},//success: function(data) END
error: function(jqXHR, XMLHttpRequest, textStatus, errorThrown,data) {
alert('add question error!');
alert(" textStatus " + textStatus+" errorThrown " + errorThrown +" XMLHttpRequest " + XMLHttpRequest);
alert("now the data is "+data)
console.log('1'+jqXHR+" |t|t| " +textStatus+" |e|e| " + errorThrown +" |x|x| " + XMLHttpRequest);
console.log('data = '+data);
} //error END
});//$.ajax() END
}
quiz_controller.php
<?php
function __autoload($className){
$classNameUrl="../model/$className.php";
include_once($classNameUrl);
}
$users=new Quiz("localhost","us","pw","equizz");
/*$_POST['action'] ='add_question';
$_POST['user'] ="fs";*/
if(!isset($_POST['action'])) {
print json_encode(0);
print " empty! not ready!";
return;
}
if(get_magic_quotes_gpc()){
$userParams = stripslashes($_POST['user']);
} else {
$userParams = $_POST['user'];
}
switch($_POST['action']) {
case 'add_question':
$user = new stdClass;
$user = json_decode($userParams );
print $users->addQ($user);
break;
}
exit();?>
/model/Quiz.php
<?php
class Quiz {
private $dbh;
public function __construct($host,$user,$pass,$db) {
$this->dbh = new PDO("mysql:host=".$host.";dbname=".$db,$user,$pass);
}
public function addQ($user){
$sth = $this->dbh->prepare("INSERT INTO eq_question1(`qCatID`, `qTypID`) VALUES (?, ?)");
$sth->execute(array($user->qcategory, $user->qtype));
return json_encode($this->dbh->lastInsertId());
}
}//class Quiz END
?>
HTML
<form>
<h1>New Question Settings</h1>
<p>
<label for="qcategory" class="" data-icon="u" > Category </label><br/>
<select id="qcategory" name="qcategory" required="required">
<option value="1">bb</option>
<option value="2">cc Operators</option>
</select>
</p>
<p>
<label for="qtype" class="" data-icon="u" > Type </label><br/>
<select id="qtype" name="qtype" required="required">
<option value="1">ab</option>
<option value="2">cd</option>
>
</select>
</p>
<p class="add-question button">
<input id="done-add-question" type="submit" value="Submit" />
</p>
</form>
Erorr console.log returned by Chrome Inspector
userJson = {"qcategory":"1","qtype":"1"} quiz_controller.js:214
1[object Object] |t|t| |e|e| undefined |x|x| error quiz_controller.js:257
data = undefined
in your quiz_controller.js try the following:
$(function() {
$(document).on("click", "input#done-add-question", function(){ addQuestion(this); });
});
function addQuestion(element) {
var User = new Object();
User.qcategory = $('#qcategory').val();
User.qtype = $('#qtype').val();
var userJson = JSON.stringify(User);
$('#indicator').show();
$.post('controller/quiz_controller.php',
{
action: 'add_question',
user: userJson
},
$('#indicator').hide(),
"json"
);
}
in quiz_controller.php remove:
if(!isset($_POST['action'])) {
print json_encode(0);
print " empty! not ready!";
return;
}
if(get_magic_quotes_gpc()){
$userParams = stripslashes($_POST['user']);
} else {
$userParams = $_POST['user'];
}
Replace with:
if(!isset($_POST['action'])) {
print json_encode(0);
return;
}
if(isset($_POST['user'])) {
$userParams = $_POST['user'];
}
i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?
this is my index.php
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<form>
<h1>Insert Data Into mySQL Database</h1>
Name <input name="name" type="text" id="name"> <br><br>
Lastname <input name="lastname" type="text" id="lastname"><br><br>
Email <input name="email" type="text" id="email"><br><br>
<input type="button" name="Submit" value="Submit" onclick="insertData()">
</form>
<button type="button">get values</button>
<div id="jcontent"></div>
<script type="text/javascript">
/* * Checking the Login - * */
function insertData(){
var data_get = {
'name_form': $('#name').val().trim(),
'lastname_form': $('#lastname').val().trim(),
'email_form': $('#email').val().trim()
};
$.ajax({
url : 'insert_ac.php',
type : 'POST',
data : data_get,
timeout : 30000,
success : function(response_data, text, xhrobject) {
console.log(text);
if(text == "success"){
$('#jcontent').html('Data Inserted');
}
else if(text == "ERROR"){
$('#jcontent').html('data not inserted');
}
}
});
}
</script>
/*******************************************************/
this is my insert.php
<?php
mysql_connect('localhost','root','');
mysql_select_db('loginthree');
$table_name = "test_three";
$name_form=$_POST['name_form'];
$lastname_form=$_POST['lastname_form'];
$email_form=$_POST['email_form'];
$sql="INSERT INTO $table_name(name, lastname, email)VALUES('$name_form', '$lastname_form', '$email_form')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Success";
} else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?
Well firstly, insert a:
return false;
at the end of your insertData() function, in that way you prevent the refresh of the page so that the ajax call can load its data.
Second you are returning Success and you are trying to read success, it's case sensitive and your code will not reach that if.
Resolve these issues and get back to me
Make a PHP script (lets name it getvalues.php) to return the values from the database into JSON, such as:
$result = mysql_query("SELECT * FROM $you_table"); //mod query to match what you need to fetch
$array = mysql_fetch_row($result);
echo json_encode($array);
Then in your script above include jQuery and use something along the lines of the following to retrieve the data:
$(function ()
{
$.ajax({
url: 'getvalues.php',
data: "",
dataType: 'json',
success: function ( values )
{
var value1 = values[0]; //value1, value2, etc should represent the field names in your database
var value2 = values[1];
//and so on and so forth. each field in you DB should be one index in your values array
$('#output').html("<b>Value 1: </b>"+value1+"<b> Value 2: </b>"+value2);
}
});
});
This is a mailing list script. It works by itself without jquery but I am trying to adapt it to work with ajax. However, without success. When the $.sql part is commented out it returns the variables in the url string successfully. However, when I uncomment that part of the js file and introduce the PHP into things it simply refreshes the page with the email address still in the input box. By itself, the PHP works so I'm at a loss as to where I'm going wrong. Here's what I have... any help would be appreciated.
Form :
<form name="email_list" action="" id="maillist_form">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" value="Submit Form" class="email_submit"></p>
</form>
JQuery :
$(function() {
$('#maillist_form').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = $("#maillist_form").serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});
});
PHP :
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["sub"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add2.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// add record
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address - ".$_POST["email"]." - is already subscribed.";
}
}
}
?>
I won't put the include code in here because I'm assuming it is correct - unless the introduction of the jquery means this needs to be adapted as well.
Your AJAX is not catching back the result:
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function(response) {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block').html(response); //just an example method.
//Are you sure the selector is the same?
//Can also be $(this).html(response);
}
});
And as noted by gdoron, there's no "name" variable. Maybe you meant "email" and "sub", respectively?
PHP response, also, isn't echoed back. Just put:
echo $display_block;
You don't echo an data from the server, not trying to get data in the success callback, and the fadeIn callback just have a selector,.
You check for the wrong variable:
var email = $("input#email").val();
if (name == "") { // Didn't you mean email?
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") { // Didn't you mean sub?
$("input#sub").focus();
return false;
}
How can it work!?