I'm playing around with Ajax, jQuery and PHP in an attempt to get familiar with the combination of them and how they integrate with each other. Here's my 1st attempt, it's a very simple form submission that does nothing special, just trying to see how ajax handles requests and responses.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<title>My 1st AJAX attempt</title>
<link href="http://www.ht-webcreations.com/test/styles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#wait').hide();
$("#emailContactus").submit(function(){
$('#wait').show(),
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'includes/ajax.php?action=emailContactus',
success: function(data) {
console.log("Success posting emailContactus"),
$('#wait').hide(),
$('#notifications').html(data).addClass('ajaxsuccess').show();
},
error: function (xhr, textStatus, errorThrown) {
console.log("Success posting emailContactus: "+ textStatus, errorThrown);
},
complete: function(data){
$('#wait').hide(),
$('#notifications').html(data).addClass('ajaxsuccess').show();
}
});
return false;
});
});
</script>
</head>
<body>
<div id="wait"><img src="http://www.ht-webcreations.com/test/loading_ajax.gif" width="80" height="80"></div>
<div id="notifications"></div>
<form name="emailContactus" id="emailContactus" method="post">
<table width="500" border="0" align="center" cellpadding="5" cellspacing="0">
<tr>
<td>name</td>
<td><label for="name"></label>
<input type="text" name="name" id="name"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="button" id="button" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
ajax.php:
<?
///////////////// AJAX REQUESTS /////////////////
switch($_REQUEST['action']){
case('emailContactus'): if($_POST['name']=='a') { echo $value = 'User is A'; } else { echo $value = 'User is NOT A'; }
break;
case('addContact'): echo 'Contact added!';
break;
default: break;
}
?>
The problem in this simple example (working demo here) is that though I expect the data response to be appended to the #notifications div, instead it's being outputted to the very top of the document, even before any HTML has been loaded. Please have a look and suggest what needs to be changed. Also, I will be glad to hear all your comments on my code as I would like to be pointed to the right direction from the start. Thanks!
Related
The following code is used for getting two values from two textboxes , calculate the sum using javascript and display the result in third textbox. When I click the button, I just want these textbox values (both input and result) to be inserted into mysql database. I want to do this in the same page. How can I get the javascript values to php for inserting them into database? It would be great if you could help.
Thanks
Jeny
Code:
<html>
<head>
<script language="javascript">
function getText3()
{
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
document.getElementById('in3').value=in3;
}
</script>
</head>
<body>
<form>
<table width="306" border="0">
<tr>
<td width="146">Enter A </td>
<td width="144"><input name="text" type="text" id="in1"/></td>
</tr>
<tr>
<td>Enter B </td>
<td><input name="text2" type="text" id="in2"/></td>
</tr>
<tr>
<td height="41" colspan="2"> <center>
<button type="button" onclick="getText3()"> Get calculated result</button></center> </td>
</tr>
<tr>
<td><strong>RESULT</strong></td>
<td><input name="text3" type="text" id="in3"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
For this you should use jQuery (http://jquery.com/)
Just send them to your php file like the following:
// JS:
var in1 = $('#in1').val();
var in2 = $('#in2').val();
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
$('#in3').val( in3 );
$.post('file.php', { one: in1, two: in2, three: in3 }, function(data) {
alert( data );
} )
PHP file get's them as normal POST params:
// file.php
echo $_POST['one'] . " + " . $_POST['two'] . " = " . $_POST['three'];
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script language="javascript">
function getText3()
{
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
document.getElementById('in3').value=in3;
$.ajax({
type: "POST",
url: "your_php_file_path.php",//you can get this values from php using $_POST['n1'], $_POST['n2'] and $_POST['add']
data: { n1: in1, n2: in2, add: in3 }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
You can Pass the JavaScript Values to a HIDDEN Value in FORM and then POST the form to the PHP Page. Below is an example of how to set hidden value.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function setPrice(el){
var prices=[30, 20, 10];
var p=el.options.selectedIndex;
el.form.elements['price'].value=prices[p];
}
</script>
</head>
<body>
<form>
<select name="category" onchange="setPrice(this);">
<option value="men">
Men
</option>
<option value="women">
Women
</option>
<option value="under18">
Under 18's
</option>
</select>
<input name="price" type="hidden" value="30">
</form>
</body>
</html>
Hope this will help you!
Okay, so I've been having a problem for the past four days, and a couple hours ago, I think I may have solved part of it (fancybox example #5, on their site, seems to be something that I want), however, I cannot get any part of it to work.
<? if($_GET['page'] != "startTime"){ ?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/./fancybox/jquery.mousewheel-3.0.2.pack.js"></script>
<script type="text/javascript" src="/./fancybox/jquery.fancybox-1.3.1.js"></script>
<link rel="stylesheet" type="text/css" href="/./fancybox/jquery.fancybox-1.3.1.css" media="screen" />
<script type="text/javascript">
$(document).ready(function() {
$("#startTime").fancybox({
'padding' : 0,
'scrolling' : 'no',
'titleShow' : false,
'onClosed' : function() {
$("#login_error").hide();}
})
});
$("#startTimeForm").bind("submit", function() {
if ($("#year").val().length < 4) {
$("#login_error").show();
$.fancybox.resize();
return false;
}
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "downTime.php?page=ajax",
data : $(this).serializeArray(),
success : function(data) {
$.fancybox(data);
}
});
return false;
});
</script>
<? } ?>
<? if($_GET['page'] == "ajax"){
var_dump($_POST); } ?>
<? if($_GET['page'] == "startTime"){?>
<div style="width:250px" class="new">
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="new">
<tr>
<form id="startTimeForm" method=post>
<p id="login_error">Please, enter data</p>
<tr>
<td>Enter Year</td>
<td><input class="czas" id="sec" name="year" type="text" size="5" maxlength="5" value="00" /></td></tr>
<tr>
<td colspan="2" align="center"><br /><input class="czas" type="submit" name="newTime" value="Set Start Time" /></td></tr>
</form>
I also had used a javascript function, below, and I'd eventually like that to work in the code above, but I cannot get the above to work properly. It just does nothing. Firebug also reports no errors.
<script>
function closeFB() {
<? $unix = mktime(0, 0, 0, 1, 1, $_POST['year']); ?>
$("#startTimeDiv").html("<div id='message'></div>");
$("#message").html("<p>Contact Form Submitted!</p>")
.append("<p>We will be in touch soon.<br><? echo $unix; ?></p>");
$.fancybox.close();
}
</script>
So, any help would be appreciated. Please tell me what I'm doing wrong.
The demonstration here worked to solve the problem. It created another problem, but that is for another question. I believe that was your demo, JFK, so thank you.
$.ajax({
type : "POST",
cache : false,
url : "downTime.php?page=ajax",
data : $(this).serializeArray(),
success : function(data) {
Instead of:
$.fancybox(data);
Try
$("#fancyboxdiv").fancybox(data);
}
});
Where fancyboxdiv is the name of your element that hosts the fancybox.
You will change the other functions to
$("#fancyboxdiv").fancybox().close()
etc..
Most JQuery UI components require a element to work off of as its parent and it will usually modify that element adding/removing elements to it and changing CSS to give appearance that is needed
i have a simple form where one one field is there which is random javascript file whose name ranges from 1 to 500000 so i have used rand function to populate its field without any issue
i want form to be automatically submitted after loading but i dont want pages to be refreshed and even i dont want field value to be changed after form is submitted. my code is very clear but dont know why it is not working
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<title>testing</title>
</head>
<body>
<script type="text/javascript" >
$(function() {
$("form1#form1").submit(function() {
var searchBox = $("#searchBox").val();
var dataString = 'searchBox='+ searchBox ;
if(searchBox=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "test34.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<form method="post" name="form1" id="form1" enctype="multipart/form-data">
<input type="text" class="status" name="searchBox" id="searchBox" value="<?= "".rand(1,2889889).".js"; ?>">
<input class="button" type="submit" value="Submit" /></form>
</body>
</html>
test34.php
<?php
include('connect.php');
$title23 = $_POST['searchBox'];
mysql_query("insert into test (title) values('$title23')");
echo $title23;
?>
but it is not submitting the form automatically please advise
Your selector should probably look like this $("form#form1") instead of $("form1#form1")
After you've bound your submit method to the form, try triggering the submit method by doing this.
return false;
});
$("form1#form1").trigger('submit'); // Here
});
I'm learning how to integrate JQuery, AJAX and PHP together.
My problem is that my success function isn't getting any value from the parameter and just getting a '0'. I'm not really sure what I'm doing wrong either, but I have just been following this tutorial JQuery & PHP Tutorial and just copied how he got the value from the PHP code using echoes and a parameter variable r.
I have tried searching for the solution, but I'm not sure if any of the results are relevant to what I am doing. I tried following some of their advice but none seems to work (the promise thing for jQuery)
I hope someone can enlighten me what I am doing wrong as I am eager to learn more PHP and jQuery.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function () {
jQuery("form").submit(function(e) {
var input = $("#input").val();
var url = 'input=' + input;
$.ajax({
type: "POST",
url: "process.php",
data: url,
success: function(r) {
$("#output").text(function(r) {
return r;
});
}
});
e.preventDefault();
});
});
</script>
<title>Insert title here</title>
</head>
<body>
<form action="process.php" method="post">
Inputs:<br />
<textarea rows="15" cols="60" id="input" name="input">Some text...
</textarea><br /><br />
Start:
<input type="text" id="start" name="start" />
End:
<input type="text" id="end" name="end" /><br />
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<p id="output">Output: Some Random Text</p>
</body>
</html>
PHP:
require 'parser.php';
$parser = new Parser();
#header('index.php');
$hash = $parser->parse($_POST['input']);
$keys = array_keys($hash);
foreach($keys as $key) {
echo "$key ->";
$dests = $hash[$key];
foreach($dests as $dest) {
echo " $dest";
}
echo "<br />";
}
?>
<script>
$(function () {
jQuery("form").submit(function(e) {
var input1 = $("#input").val();
var url = {'input' : input1}; // a little change to the data parameter
$.ajax({
type: "POST",
url: "process.php",
data: url,
success: function(r) {
// $("#output").text(r); //<--- changed to this
$("#output").html(r); // this is better as you output html
}
});
e.preventDefault();
});
});
</script>
for jquery text(), use the return value from the server directly. If you are outputting html use jquery html() instead
<html>
<head>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getsuggestion()
{
var seltxt=$('#selstate').val();
//alert(seltxt);
$.ajax({
type: "POST",
url: "getstate.php",
data:{state: seltxt },
dataType: 'json',
success: function(data){
//alert(data['test']);
if(data['test']==0)
{
$("#suggestion").text("");
alert("No suggestion");
}
$.each(data,function(key,value)
{
//alert(key);
if(key!="test")
{
str=str+value+",";
$("#suggestion").text(str);
}
});
},
error: function(error,txtStatus) { alert(txtStatus);}
});
}
</script>
</head>
<body>
<form name=f1 method=post>
<table>
<tr>
<td>Select State:</td>
<td><input type=text id=selstate onkeyup="getsuggestion();">
</td>
</tr>
<tr> <td></td>
<td><div id="suggestion"></div>
</td>
</tr>
</table>
</form>
</body>
</head>
</html>
Hi,I want to make a suggestion list.For that I've used text box for getting input from the user.But now I want the values, stored in database,to be retrieved in the form of list.Here I am getting values in text the format.How do I conver text box into list?Or what should I do to append list to the text box?
You can use autocomplete feature of jQuery UI.You can download from http://jqueryui.com/download
You should use something like jQuery UI-Autocomplete: http://jqueryui.com/demos/autocomplete/
It provides all the stuff needed to do as you ask and also the demos required for you to learn how to do it yourself.