Popular Posts
- Bootstrap Progress Bar example using jQuery and PHP
- How to get device Unique ID | device ID in Phonegap
- Jquery popup using colorbox iframe load external page
- How to Git Init Repository
- Attractive login form with css and bootstrap
- Shaking Up The Web With CSS3 (How To Make Links Shake)
- CodeIgniter Insert Data into Database
- Extracting URL Data with Jquery and Ajax
- Voting system Using jQuery Ajax and Php Codeigniter Framework
- How to display Indian Rupee symbol in websites
Contact Form
ajax,
functions,
javascript,
Jquery
Why We Forgot to Use These Jquery Functions
6:40 AM Admin 0 Comments
While Using Jquery AJAX Functions to post and get the parameters to certain URLs, We always forgot this kind of methods are there in jquery and it will reduce our code structure and size.
Send form data using Ajax requests
Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
Request the test.php page and send some additional data along (while still ignoring the return results).
jQuery.post()
Description: Load data from the server using a HTTP POST request.
Examples:
Request the test.php page, but ignore the return results.
|
Request the test.php page and send some additional data along (while still ignoring the return results).
|
Pass arrays of data to the server (while still ignoring the return results).
|
Send form data using Ajax requests
|
Alert the results from requesting test.php (HTML or XML, depending on what was returned).
|
Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
|
jQuery.get()
Description: Load data from the server using a HTTP GET request.
Examples:
Request the test.php page, but ignore the return results.
|
Request the test.php page and send some additional data along (while still ignoring the return results).
|
Pass arrays of data to the server (while still ignoring the return results).
|
Alert the results from requesting test.php (HTML or XML, depending on what was returned).
|
Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).
|
Extracting URL Data with Jquery and Ajax
About the Functionality
For Extracying the URL Data we need the HTML file (for to send the request and get the response from the php file) and The PHP file(to get the request and process that and send back to the HTML page ) that request and response will be done using the Jquery Ajax Request , PHP file_get _Contents() function in PHP side.
At First the URL will be pasted in the text box that URL will be send to the PHP file as a Request using Jquery Ajax Functionality and the PHP file get the Whole SIte details from that link and it will give the response to the jquery request that function will get the title, image, description name of the website everything from the response and then it will show in the div #linkbox in Ajax
Basically Why we are using the PHP for getting the file request means that is a server side script but javascript or jquery is not a server side script that need to be get the whole site details thats why the reason we are using the PHP file here.
Javascript and HTML Code
$('#content').keyup(function(){} - content is the ID of the textbox. Using $(this).val() getting the textbox value.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var content=$(this).val();
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
// Filtering URL from the content using regular expressions
var url= content.match(urlRegex);
if(url.length>0)
{
$("#linkbox").slideDown('show');
$("#linkbox").html("<img src='link_loader.gif'>");
// Getting cross domain data
$.get("urlget.php?url="+url,function(response)
{
// Loading <title></title>data
var title=(/<title>(.*?)<\/title>/m).exec(response)[1];
// Loading first .png image src='' data
var logo=(/src='(.*?).png'/m).exec(response)[1];
$("#linkbox").html("<img src='"+logo+".png' class='img'/><div><b>"+title+"</b><br/>"+url)
});
}
return false;
});
});
HTML code
<textarea id="contentbox"></textarea> <div id="linkbox"></div> </script>
Why used urlget.php
Ajax origin policy we could not access the cross domain data with ajax request $.get("http://www.yahoo.com",function(response){ });. So that using local file(urlget.php) accessing the cross domain data.
urlget.php
Contains PHP code using file_get_contents function loading the URL data. Eg:urlget.php?url=http://yahoo.com<?php
if($_GET['url'])
{
$url=$_GET['url'];
echo file_get_contents($url);
}
?>
CSS
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
#contentbox
{
width:458px; height:50px;
border:solid 2px #dedede;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
margin-bottom:6px;
}
.img
{
float:left; width:150px; margin-right:10px;
text-align:center;
}
#linkbox
{
border:solid 2px #dedede; min-height:50px; padding:15px;
display:none;
}
Ajax fetch multiple values from php code
Send the single value from index.html file through ajax and get multiple values as a reply from ajax.php file using string concatenation and javascript split() function
...................................................................................................................................................................
index.html
...................................................................................................................................................................
<div class="first">
<label >member</label>
<select name='member' id='member' onchange='change(this.value);'>
<option value=''>----Select----</option>
</select>
<label>father</label>
<input type="text" name='father' id='father' readonly ></input>
<label>last name</label>
<input type="text" name='father' id='last_name' readonly ></input>
</div>...................................................................................................................................................................
javascript
...................................................................................................................................................................
<script type="text/javascript">
function change(ele) {
var element = ele;
var info = "id="+element;
$.ajax({
type: "GET",
url: "ajax.php",
data: info,
success: function(result){
var split = result.split('@');
var one = split[0];
var two = split[1];
$("#last_name").attr("value",one);
$("#father").attr("value",two);
}
});
}
</script>
...................................................................................................................................................................
ajax.php
...................................................................................................................................................................
<?php
include "includes/db_connect.php";
$result='';
$a='';
if($_GET)
{
if(isset($_GET['id']))
{
$id=$_GET['id'];
$select = mysql_query("select * from member where id='$id'");
while($row = mysql_fetch_array($select))
{
$last_name = $row['last_name'];
$a=$last_name;
}
$select = mysql_query("select * from group where id='$id'");
$row1 = mysql_fetch_array($select);
$father= $row1['father'];
$b=$father;
$result=$a.'@'.$b;
echo $result;
}
?>
...................................................................................................................................................................
Here at ajax.php file get the id and fetch two different value from two different table and send the two values using string concatication function by spliting the value ,here am using @ to slpit the two values
At the index.html file if ajax success the result value ll get and split the values using the @ symbol and assign the value to the corresponding text boxes.
i hope you understand the tutorial .. :)
Ajax delete list lively PHP
jquery.js
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script><script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
dbconfig.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "root";
$mysql_database = "post";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>
dbconfig.php
<?php
// This is a sample code in case you wish to check the username from a mysql db table
if(isset($_POST['update']))
{
$update=addslashes($_POST['update']);
include("dbconfig.php");
if(strlen($update)>0)
{
$query = "insert into {$prefix}updates(message,post_date)VALUES ('$update',NOW())";
mysql_query( $query);
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta content="en-us" http-equiv="Content-Language">
<title>Tutorials</title>
<script type="text/javascript">
String.prototype.parseURL = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
return url.link(url);
});
};
</script>
<style type="text/css">
body {
color: #000000;
background-color:#CCCCCC;
background:#cccccc fixed repeat top left;
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size:14px;
}
a
{
color:#FF6633;
}
.what
{
font-family:Arial, Helvetica, sans-serif;font-size:1.30em; padding-left:10px;
}
.content
{
padding-left:10px; background-color:#fff; border-bottom:dashed #0066CC 1px;
}
</style>
</head><body>
<table align="center">
<tbody>
<tr>
<td width='455' valign="top">
<form action="" method="post">
<table width="100%" bgcolor="#FFFFFF">
<tr>
<td>
<span class="what">What are you doing?</span>
<a href="http://twitter.com/foxscan" target="_blank" style="color:#0066CC; font-size:12px">My twitter profile</a> <a href="http://9lessons.blogspot.com" target="_blank" style="color:#000; font-size:12px">9Lessons tutorials </a> </td>
</tr>
<tr><td> <textarea rows="3" cols="55" maxlength="145" class="box" name="update" id="update" ></textarea> </td></tr>
<tr>
<td align="right">
<input type="submit" value=" Update " id="mybut" class="update_button" />
</td></tr>
</table></form>
</td></tr><tr><td>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<?php
include("dbconfig.php");
$query4="select * from updates order by ms_id desc";
$result4 = mysql_query($query4);
while($row=mysql_fetch_array($result4))
{
$message=stripslashes($row["message"]);
?>
<tr class="record">
<td width="51"><img src="foxscan.jpg" width="50" height="50"/></td>
<td width="7" align="right" ></td>
<td width="376" class="content">
<strong style="color:#006699;">foxscan/</strong>
<script type="text/javascript">
var test = "<?php echo $message; ?>";
document.write(test.parseURL());
</script>
</td>
<TD width="28" bgcolor="#FFFFFF"><a href="#" id="<?php echo $row["ms_id"]; ?>" class="delbutton"><img src="trash.png" style="background:#FFFFFF"/></a></TD>
<?php
}
?>
</table>
</div>
</td> </tr>
</tbody>
</table>
</div>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script></body></html>
delete.php
<?php
// This is a sample code in case you wish to check the username from a mysql db table
include("dbconfig.php");
if($_GET['id'])
{
$id=$_GET['id'];
$sql = "delete from {$prefix}updates where ms_id='$id'";
mysql_query( $sql);
}
?>
onkeyup with javascript like ajax
Sample Code:
...................................................................................................................................................................<script>
function balance(str) { var val = str;
// this fucntion reduce the value by 100 and show the result in result text box
var result = 100 - val;
document.getElementById("bal_show").value =result;
}
</script>
...................................................................................................................................................................
<div class="first">
<label for="">balance</label>
//onkeyup() function is used to send the each value to that function on every key press
<input type="text" id="receipt" onkeyup="balance(this.value)">
<label for="">result</label>
//here is the result textbox this ll show the balance without any submit button or without any action //like ajax.
<input type="text" id="bal_show" >
</div>
...................................................................................................................................................................
...................................................................................................................................................................
PHP validation With AJAX
<?php
// If the form was submitted, scrub the input (server-side validation)
// see below in the html for the client-side validation using jQuery
$name = '';
$gender = '';
$address = '';
$email = '';
$username = '';
$password = '';
$output = '';
if($_POST) {
// collect all input and trim to remove leading and trailing whitespaces
$name = trim($_POST['name']);
$gender = trim($_POST['gender']);
$address = trim($_POST['address']);
$email = trim($_POST['email']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$errors = array();
// Validate the input
if (strlen($name) == 0)
array_push($errors, "Please enter your name");
if (!(strcmp($gender, "Male") || strcmp($gender, "Female") || strcmp($gender, "Other")))
array_push($errors, "Please specify your gender");
if (strlen($address) == 0)
array_push($errors, "Please specify your address");
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
array_push($errors, "Please specify a valid email address");
if (strlen($username) == 0)
array_push($errors, "Please enter a valid username");
if (strlen($password) < 5)
array_push($errors, "Please enter a password. Passwords must contain at least 5 characters.");
// If no errors were found, proceed with storing the user input
if (count($errors) == 0) {
array_push($errors, "No errors were found. Thanks!");
}
//Prepare errors for output
$output = '';
foreach($errors as $val) {
$output = "<p class='output'>$val</p>";
}
}
?>
<html>
<head>
<!-- Define some CSS -->
<style type="text/css">
.label {width:100px;text-align:right;float:left;padding-right:10px;font-weight:bold;}
#register-form label.error, .output {color:#FB3A3A;font-weight:bold;}
</style>
<!-- Load jQuery and the validate plugin -->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<!-- jQuery Form Validation code -->
<script>
// When the browser is ready...
$(function() {
// Setup form validation on the #register-form element
$("#register-form").validate({
// Specify the validation rules
rules: {
name: "required",
gender: "required",
address: "required",
email: {
required: true,
email: true
},
username: "required",
password: {
required: true,
minlength: 5
}
},
// Specify the validation error messages
messages: {
name: "-->Please enter your name",
gender: "-->Please specify your gender",
address: "-->Please enter your address",
email: "-->Please enter a valid email address",
username: "-->Please enter a valid username",
password: {
required: "-->Please provide a password",
minlength: "-->Your password must be at least 5 characters long"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
</head>
<body>
<?php echo $output; ?>
<!-- The form that will be parsed by jQuery before submit -->
<form action="./" method="post" id="register-form" novalidate>
<div class="label">Name</div><input type="text" id="name" name="name" value="" /><br />
<div class="label">Gender</div><select style="width:155px;" id="gender" name="gender" />
<option selected value="">--select--</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select><br />
<div class="label">Address</div><input type="text" id="address" name="address" value="" /><br />
<div class="label">Email</div><input type="text" id="email" name="email" value="" /><br />
<div class="label">Username</div><input type="text" id="username" name="username" value="" /><br />
<div class="label">Password</div><input type="password" id="password" name="password" /><br />
<div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" /></div>
</form>
</body>
</html>
PHP AJAX Image Upload
In this tutorial let us learn about how to upload an image file using PHP and AJAX. We are using jQuery AJAX to send image file to the server side PHP script.
Steps for PHP AJAX Image Upload,
- Add jQuery library
- Create HTML for image upload form
- Send file data to PHP via AJAX
- Write PHP script to upload image
PHP Example to Upload Image
HTML code for the form containing file input is,
<form id="uploadForm" action="upload.php" method="post"> <label>Upload Image File:</label><br/> <input name="userImage" type="file" class="inputFile" /> <input type="submit" value="Submit" class="btnSubmit" /> </form>
On submit, the AJAX call will be triggered to send form’s file input to the PHP pageupload.php. The script is,
<script type="text/javascript"> $(document).ready(function (e){ $("#uploadForm").on('submit',(function(e){ e.preventDefault(); $.ajax({ url: "upload.php", type: "POST", data: new FormData(this), contentType: false, cache: false, processData:false, success: function(data){ $("#targetLayer").html(data); }, error: function(){} }); })); }); </script>
This AJAX call includes several options URL, Type, data and more. we are sending image file data by instantiating FormData. The success/failure handlers are triggered based on the result of the upload request.
Note
- Import jQuery library before calling jQuery AJAX handler.
- Find PHP script and css by extracting the source code zip added with this tutorial.
Output
Initially the form will be,
After uploading image via AJAX, we are loading the image to the target layer in the left side of the above form.
Multiple Ajax Requests with Jquery
Javascript Code
Contains javascript and HTML code. $.when( yahoo(), bing()) is the method to call multiple ajax requests. Here $.when calling two functions called yahoo() and bing() callback objects$.done(yahoo_data, bing_data)
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".search_input").keyup(function()
{
var search_input = $(this).val();
var keyword= encodeURIComponent(search_input);
// Yahoo Search API
var yahoo_url='http://boss.yahooapis.com/ysearch/web/v1/'+keyword+'?appid=APP_ID&format=json&callback=myData';
var bing_url='http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&Appid=APP_ID&query='+keyword+'&sources=web&web.count=10';
// Yahoo API
function yahoo()
{
return $.ajax({
type: "GET",
url: yahoo_url,
dataType:"jsonp",
success: function(yahoo_data)
{
}
});
}
// Bing API
function bing()
{
return $.ajax({
type: "GET",
url: bing_url,
dataType:"jsonp",
success: function(bing_data)
{
}
});
}
// Multiple Ajax Requests
$.when( yahoo(), bing()).done(function(yahoo_data, bing_data)
{
var yahoo=yahoo_data[0].ysearchresponse.resultset_web;
var bing=bing_data[0].SearchResponse.Web.Results;
// Yahoo results
if(yahoo)
{
$("#yahoo_result").html('');
$.each(yahoo, function(i,data)
{
var title=data.title;
var dis=data.abstract;
var url=data.url;
var dispurl=data.dispurl;
var final="<div class='webresult'><div class='title'><a href='"+url+"' target='_blank'>"+title+"</a></div><div class='desc'>"+dis+"</div><div class='url'>"+dispurl+"</div></div>";
$("#yahoo_result").append(final); // Result
});
}
// Bing results
if(bing)
{
$("#bing_result").html('');
$.each(bing, function(i,data)
{
var title=data.Title;
var dis=data.Description;
var url=data.Url;
var DisplayUrl=data.DisplayUrl;
var final="<div class='webresult'><div class='title'><a href='"+url+"' target='_blank'>"+title+"</a></div><div class='desc'>"+dis+"</div><div class='url'>"+DisplayUrl+"</div></div>";
$("#bing_result").append(final); // Result
});
}
});
});
});
</script>
// HTML code
<input type="text" class='search_input' />
<div>
<div id="yahoo_result"></div>
<div id="bing_result"></div>
</div>
CSS
#yahoo_result, #bing_result
{
float:left;
width:450px;
}
.search_input
{
border:2px solid #333;
font-size:20px;
padding:5px;
width:350px;
font-family:'Georgia', Times New Roman, Times, serif;
-moz-border-radius:5px;-webkit-border-radius:5px;
}
reference : http://www.9lessons.info/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".search_input").keyup(function()
{
var search_input = $(this).val();
var keyword= encodeURIComponent(search_input);
// Yahoo Search API
var yahoo_url='http://boss.yahooapis.com/ysearch/web/v1/'+keyword+'?appid=APP_ID&format=json&callback=myData';
var bing_url='http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&Appid=APP_ID&query='+keyword+'&sources=web&web.count=10';
// Yahoo API
function yahoo()
{
return $.ajax({
type: "GET",
url: yahoo_url,
dataType:"jsonp",
success: function(yahoo_data)
{
}
});
}
// Bing API
function bing()
{
return $.ajax({
type: "GET",
url: bing_url,
dataType:"jsonp",
success: function(bing_data)
{
}
});
}
// Multiple Ajax Requests
$.when( yahoo(), bing()).done(function(yahoo_data, bing_data)
{
var yahoo=yahoo_data[0].ysearchresponse.resultset_web;
var bing=bing_data[0].SearchResponse.Web.Results;
// Yahoo results
if(yahoo)
{
$("#yahoo_result").html('');
$.each(yahoo, function(i,data)
{
var title=data.title;
var dis=data.abstract;
var url=data.url;
var dispurl=data.dispurl;
var final="<div class='webresult'><div class='title'><a href='"+url+"' target='_blank'>"+title+"</a></div><div class='desc'>"+dis+"</div><div class='url'>"+dispurl+"</div></div>";
$("#yahoo_result").append(final); // Result
});
}
// Bing results
if(bing)
{
$("#bing_result").html('');
$.each(bing, function(i,data)
{
var title=data.Title;
var dis=data.Description;
var url=data.Url;
var DisplayUrl=data.DisplayUrl;
var final="<div class='webresult'><div class='title'><a href='"+url+"' target='_blank'>"+title+"</a></div><div class='desc'>"+dis+"</div><div class='url'>"+DisplayUrl+"</div></div>";
$("#bing_result").append(final); // Result
});
}
});
});
});
</script>
// HTML code
<input type="text" class='search_input' />
<div>
<div id="yahoo_result"></div>
<div id="bing_result"></div>
</div>
{
float:left;
width:450px;
}
.search_input
{
border:2px solid #333;
font-size:20px;
padding:5px;
width:350px;
font-family:'Georgia', Times New Roman, Times, serif;
-moz-border-radius:5px;-webkit-border-radius:5px;
}




