Implementing JCrop in ajax upload - php

I'm trying to develop image crop using JQuery.
I use ajax to upload the image. after the image success fully uploaded. I load the uploaded image using jquery to its container.
$("#image_upload").html("<img src='" + data.path + "' width=\"460\" id=\"cropbox\" alt=\"cropbox\" />");
but the image selection doesnt work. why it could be happened ?
this is my code:
<style type="text/css">
#preview {
width: 150px;
height: 150px;
overflow: hidden;
}
</style>
<script type="text/javascript" src="<?php echo base_url()?>asset/jqupload/js/ajaxfileupload.js">
</script>
<script type="text/javascript" src="<?php echo base_url()?>asset/jcrop/jquery.Jcrop.pack.js">
</script>
<link rel="stylesheet" href="<?php echo base_url()?>asset/jcrop/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript">
function ajaxFileUpload(){
$("#loading").ajaxStart(function(){
$(this).show();
}).ajaxComplete(function(){
$(this).hide();
});
$.ajaxFileUpload({
url: '<?php echo site_url()?>/upload/do_upload',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
success: function(data, status){
if (typeof(data.error) != 'undefined') {
if (data.error != '') {
$("#image_upload").html(data.error);
$("#image_upload").fadeIn("slow");
}
else {
$("#image_upload").html("<img src='" + data.path + "' width=\"460\" id=\"cropbox\" alt=\"cropbox\" />");
$("#image_upload").fadeIn("slow");
$("#orig_h").val(data.width);
$("#orig_w").val(data.height);
//alert("<a href='" + data.path + "' />");
}
}
},
error: function(data, status, e){
$("#image_upload").html(e);
$("#image_upload").fadeIn("slow");
}
})
return false;
}
$(document).ready(function(){
$(function(){
$('#cropbox').Jcrop({
aspectRatio: 1,
setSelect: [0, 0, $("#oring_w").val(), $("#oring_h").val()],
onSelect: updateCoords,
onChange: updateCoords
});
});
function updateCoords(c){
showPreview(c);
$("#x").val(c.x);
$("#y").val(c.y);
$("#w").val(c.w);
$("#h").val(c.h);
}
function showPreview(coords){
var rx = $("#oring_w").val() / coords.w;
var ry = $("#oring_h").val() / coords.h;
$("#preview img").css({
width: Math.round(rx * $("#oring_w").val()) + 'px',
height: Math.round(ry * $("#oring_h").val()) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
});
</script>
<!-- begin main content -->
<div id="templatemo_content_area">
<h1 class="content_title">Label Info<hr/></h1>
<div id="templatemo_bi_full">
<h2>Label Setting</h2>
<div id="container">
</div>
<!--container-->
<br/>
<h2>Avatar</h2>
<div class="info">
</div>
<div id="avatar_container">
<form name="form" action="" method="POST" enctype="multipart/form-data">
<ul>
<li class="leftHalf ">
<label class="desc" for="lbl_type">
Change Your Avatar
</label>
<div>
<div id="avatar">
<img src="<?php echo $avatar?>" width="130" height="130" />
</div>
<div id="avatar_upload">
<input id="fileToUpload" name="fileToUpload" class="field field" value="" size="30" tabindex="5" type="file" /><input id="buttonUpload" name="buttonUpload" class="btTxt submit" type="submit" value="Upload" onclick="return ajaxFileUpload();"/><img id="loading" src="<?php echo base_url()?>asset/jqupload/images/loading.gif" style="display:none;">
</div>
</div>
</li>
</ul>
<ul id="crop_container">
<li class="leftHalf ">
<label class="desc" for="lbl_name">
Avatar for crop
</label>
<div id="image_upload">
<img src="<?php echo $avatar?>" width="450" height="130" id="cropbox" name="cropbox" />
</div>
</li>
<li class="rightHalf ">
<label class="desc" for="lbl_type">
Crop Display
</label>
<div id="preview">
<img src="<?php echo base_url() . 'files/' ?>" alt="thumb" />
</div>
</li>
<div class="info">
</div>
<li class="buttons ">
<input name="saveForm" class="btTxt submit" type="submit" value="Crop and Save" />
</li>
</ul>
<input type="text" id="x" name="x" />
<input type="text" id="y" name="y" />
<input type="text" id="w" name="w" />
<input type="text" id="h" name="h" />
<input type="text" id="oring_w" name="oring_w" />
<input type="text" id="oring_h" name="oring_h" />
</form>
</div>
<div class="cleaner">
</div>
</div>
<div class="cleaner">
</div>
</div>
<!-- end main content -->
Help me please ....

It doesn't work because you get your image via ajax call. When you call the jcrop function on document.ready the image doesn't exist. You need to put the jcrop code in the success function of the ajax call, after you add the image in DOM. Should be something like this (not tested):
$.ajaxFileUpload({
url: '<?php echo site_url()?>/upload/do_upload',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
success: function(data, status){
if (typeof(data.error) != 'undefined') {
if (data.error != '') {
$("#image_upload").html(data.error);
$("#image_upload").fadeIn("slow");
}
else {
$("#image_upload").html("<img src='" + data.path + "' width=\"460\" id=\"cropbox\" alt=\"cropbox\" />");//it is important to add the jcrop code after this line
$("#image_upload").fadeIn("slow");
$("#orig_h").val(data.width);
$("#orig_w").val(data.height);
$('#cropbox').Jcrop({
aspectRatio: 1,
setSelect: [0, 0, $("#oring_w").val(), $("#oring_h").val()],
onSelect: updateCoords,
onChange: updateCoords
});
}
}
},
error: function(data, status, e){
$("#image_upload").html(e);
$("#image_upload").fadeIn("slow");
}
})

None of the above worked for me .If you are also facing this issue try this
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: 1,
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
jcrop_api.setSelect([ 100,100,200,200 ]);
});

Or you could use .live function of the jQuery to add jCrop to any specified element (image) as soon as those are added to DOM.
Check this: http://api.jquery.com/live/

Related

How to select area of an image for cropping?

I am working on image cropping in PHP Codeigniter, below is my code that I have tried. When I gave the path of the image, the code worked fine, means I can select the area of the image to crop. But when I tried the same code with user uploaded image( user upload image and then crop), I cannot select image area of uploaded image. How to select image area of an image uploaded by user? I am using JCrop plugin.
imagecrop
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
<title>Jcrop Dynamic Avatar JS/PHP Demo</title>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="stylesheet" type="text/css" href="css/jquery.Jcrop.css">
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript" src="js/cropsetup.js"></script>
</head>
<body>
<div id="wrapper">
<div class="jc">
<input type='file' name="userfile" size="20"
onchange="readURL(this);"/>
<img src="#" id="target" alt="[Jcrop Example]" />
<div id="preview-pane">
<div class="preview-container">
<img src="#" class="jcrop-preview" alt="Preview" />
</div>
</div>
<div id="form-container">
<form id="cropimg" name="cropimg" method="post" action="crop.php"
target="_blank">
<input type="hidden" id="x" name="x">
<input type="hidden" id="y" name="y">
<input type="hidden" id="w" name="w">
<input type="hidden" id="h" name="h">
<input type="submit" id="submit" value="Crop Image!">
</form>
</div>
</div>
</div>
<script>function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#target')
.attr('src', e.target.result)
.width(200)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}</script>
</body>
</html>
PHP code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
if(!isset($_POST['x']) || !is_numeric($_POST['x'])) {
die('Please select a crop area.');
}
$src = 'images/cropimg.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
exit;
}
?>
This is Javascript code:
$(function($){
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
bgOpacity: 0.5,
aspectRatio: xsize / ysize
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
jcrop_api = this;
$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c) {
if (parseInt(c.w) > 0) {
var rx = xsize / c.w;
var ry = ysize / c.h;
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
}
});
The jQuery pluging ImageSelectArea worked for me !
http://odyniec.net/projects/imgareaselect/
Code is provided below:
<html>
<link rel="stylesheet" href="css/imgareaselect.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/jquery.imgareaselect.js"></script>
<body>
<form action="crop.php" method="post" enctype="multipart/form-data">
Upload Image: <input type="file" name="image" id="image" />
<input type="hidden" name="x1" value="" />
<input type="hidden" name="y1" value="" />
<input type="hidden" name="w" value="" />
<input type="hidden" name="h" value="" /><br><br>
<input type="submit" name="submit" value="Submit" />
</form>
<p><img id="previewimage" style="display:none;"/></p>
</body>
<script>
jQuery(function($) {
var p = $("#previewimage");
$("body").on("change", "#image", function(){
var imageReader = new FileReader();
imageReader.readAsDataURL(document.getElementById("image").files[0]);
imageReader.onload = function (oFREvent) {
p.attr('src', oFREvent.target.result).fadeIn();
};
});
$('#previewimage').imgAreaSelect({
onSelectEnd: function (img, selection) {
$('input[name="x1"]').val(selection.x1);
$('input[name="y1"]').val(selection.y1);
$('input[name="w"]').val(selection.width);
$('input[name="h"]').val(selection.height);
}
});
});
</script>
</html>

Ajax query not returning data

I am using jquery serialize and Ajax to capture form values and process them with Ajax using json as data Type, but no values are being returned. I have tried various ways to try and see why this is happening, but to no avail. There is no errors being returned in firebug or chrome. I would be grateful if someone could check my code and point out my error. Thanks
html code
<!--- Form to add box -->
<div id="boxaddform" style="display:none;">
<div class="dialogTop_padd"></div>
<form id="BA_boxform" name="BA_boxform" method="post">
<fieldset>
<legend><span></span>Select Company</legend>
<div class="spacer"></div>
<div class="formMessage">Click again to open</div>
<div class="fld_fld">
<div>
<label for="BA_customer">Company:</label><br />
<select name="BA_customer" id="BA_customer">
<option SELECTED VALUE="">Select a Company</option>
<?php
do {
?>
<option value="<?php echo $row_Recordsetcust['customer']?>"><?php echo $row_Recordsetcust['customer']?></option>
<?php
}
while ($row_Recordsetcust = mysql_fetch_assoc($Recordsetcust));
$rows = mysql_num_rows($Recordsetcust);
if($rows > 0)
{
mysql_data_seek($Recordsetcust, 0);
$row_Recordsetcust = mysql_fetch_assoc($Recordsetcust);
}
?>
</select>
<div class="spacer"></div>
<!--- displays the address and dept from the change function -->
<div id="BA_dept"></div>
<br />
<div id="BA_address"></div>
</div>
</fieldset>
<div class="dialogTop_padd"></div>
<!--- fieldset for service level -->
<fieldset>
<legend>Service Level</legend>
<div class="spacer"></div>
<div>
<label for="BA_service">Service level:</label>
<select name="BA_service" id="BA_service">
<option SELECTED VALUE="">Select an option</option>
<option value="Standard">Standard</option>
<option value="Rapid">Rapid</option>
</select><br />
</div>
</fieldset>
<div class="dialogTop_padd"></div>
<!--- fieldset for box # -->
<fieldset>
<legend>Box Details</legend>
<div class="spacer"></div>
<div>
<label for="BA_box">Box#:</label><br />
<input id="BA_box" name="BA_box" type="text" size="32" maxlength="128" value = "" /><br />
</div>
<div>
<label for="BA_destdate">Destroy date:</label>
<input id="BA_destdate" name="BA_destdate" type="text" size="32" maxlength="128" value = "" /><br />
</div>
</fieldset>
<div class="dialogTop_padd"></div>
<!--- fieldset for authorisation -->
<fieldset>
<legend>Authorisation</legend>
<div class="spacer"></div>
<div>
<label for="BA_authorised">Requested By:</label>
<input id="BA_authorised" name="BA_authorised" type="text" value="<?php echo $_SESSION['kt_name_usr']; ?>"><br />
</div>
</fieldset>
<!--- div to show callback result from ajax via dialog -->
<div id="BA_addbox"></div>
<br />
<input type="submit" name="submit" value="Submit Intake" />
<input type="reset" name="cancel" value="Clear Form" />
<!--- buttons to submit form and reset form to default status -->
<!-- <button id="BA_submit" class="submitbutton icon-right ui-state-default2 ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Add Box</button>
<button type="reset" id="BA_reset" class="resetbutton icon-right ui-state-default2 ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Reset</button>
--><br />
</form>
</div>
jquery code
$(function() {
$("#BA_customer").live('change', function() {
if($(this).val()!="")
$.get("/domain/admin/getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data).show();
});
$.get("/domain/admin/getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data).show();
});
});
});
//Begin function to submit box intake form
$(function() { // Function to add box
$("#boxaddform").dialog({
autoOpen: false,
resizable: false,
modal: true,
title: 'Submit a box intake request',
width: 550,
height: 400,
beforeclose: function (event, ui) {
$("#BA_addbox").html("");
$("#BA_dept").hide();
$("#BA_address").hide();
},
close: function (event, ui) {
//$("#BA_boxform").get(0).reset();
$("#BA_addbox").html("");
}
});
});
$(function(){
$("#boxaddform").submit(function(){
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
//$("#confirm_department").hide();
/*
var $dialog = $('<div id="dialog"></div>')
.html('Your intake was successfully submitted and will be viewable in the reporting area.<br /><br />Thank you.');
$dialog.dialog({
autoOpen: true,
modal: true,
title: 'Box intake submission successfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function() {
$( this ).dialog( "close" );
}
}
});
*/
//alert('You have succesfully submitted your ' + msg.company + ' report. Thank you.');
//console.log(msg);
//$("#BA_addbox").html("You may now close this window.");
//$("#formImage .col_1 li").show();
$("#BA_boxform").get(0).reset();
$("#boxaddform").hide();
}
});
return false;
});
});
// End function to submit box intake form
php code
<?php
$dept = mysql_real_escape_string($_POST['BA_dept']);
$company = mysql_real_escape_string($_POST['BA_customer']);
$address = mysql_real_escape_string($_POST['BA_address']);
$service = mysql_real_escape_string($_POST['BA_service']);
$box = mysql_real_escape_string($_POST['BA_box']);
$destroydate = mysql_real_escape_string($_POST['BA_destdate']);
$authorised = mysql_real_escape_string($_POST['BA_authorised']);
$form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised);
$result = json_encode($form);
echo $result;
?>
The problem in your code is that you are serializing a DIV, what is incorrect.
The solution would be to serialize only the FORM included in your DIV with a Javascript code like:
...
$(function(){
$("#boxaddform").submit(function(){
var formdata = $('#BA_boxform').serialize();
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
...
}
});
return false;
});
....
Also, remember that serialize will only care for INPUT, SELECTand TEXTAREA controls as a normal FORM submit would do (http://api.jquery.com/serialize/).

Jquery - How to populate form fields in a modal form from a dynamic list in another modal?

Okay, I'll try to be as clear as I can with this.
I have a page with a team's roster that you can add and delete from. When you decide to add a player, you click the "Add Player" button which, using Jquery-UI, loads a dialog modal with a form. You can fill in the form and submit and it works great. I've also added a "Search" button that, when clicked, loads another modal that lets you search a DB of exists players. When it retrieves search results it loads them in an OL. Now this is where it gets tricky:
I would like to have a button called "Use player info" that, when clicked, closes the search modal and auto-fills the the form fields with the selected player's information.
Here is the code for the search modal:
Script (in the head):
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word==''){
} else {
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
HTML
<div id="search" align="center">
<div style="width:500px">
<div style="text-align:center; padding-top:10px" class="title">Player Search</div>
<div style="margin-top:20px; text-align:left">
<form method="get" action="">
<div style="margin:0; padding:0; float:left">
<input type="text" name="search" id="search_box" class='search_box'/>
</div>
<div style="margin:0; padding:0; float:left; padding-left:8px; font-size:16px">
<input type="submit" value="Search" class="search_button" />
</div>
</form>
</div>
<div style="width:480px; padding-left:10px; padding-right:10px;">
<div id="flash"></div>
<ol id="insert_search" class="update"> </ol>
</div>
</div>
</div>
Here is the php code for the actual search function:
<li><div id="all">
<div id="result"><div id="names"><div id="lnames"><?php echo $final_msg; ?></div><div id="fnames"> <?php echo $firstName ?></div></div><div id="dobs"><?php echo $DOB ?></div><div id="ids"><?php echo $ID ?></div>
<div id="add"><button type="button" id="add_player2" > Add Player </button></div></div>
</div></li>
And here is the code for the form modal I want he information to be put in:
<script>
$(function() {
$( "#search" ).dialog({
autoOpen: false,
width: 550,
modal: true,
resizable: false,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word=='')
{
}
else
{
$.ajax({
type: "GET",
url: "../../Search/searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<script>
$(function() {
$("#dialog-form").dialog({autoOpen:!1, height:380, width:350, modal:!0, buttons:{
"Search for Player":function() {
$( "#search" ).dialog( "open" );
},
"Add Player":function() {
$("#myForm").ajaxSubmit({success:function() {
window.location = ""
}});
$(this).dialog("close")
},
Cancel:function() {
$(this).dialog("close")
}
},
create:function () {
$(this).closest(".ui-dialog")
.find(".ui-button:contains(Search for Player)") // the first button
.addClass("green");
}});
$("#add-player").button().click(function() {
$("#dialog-form").dialog("open")
})
});
</script>
<div id="dialog-form" title="Add Player">
<form name="myForm" id="myForm" action="../../php/add_player_comp_script_test.php?id=<? echo $table ?>" method="post" enctype="multipart/form-data">
<fieldset>
<label for="last_name_add">Last Name</label>
<input type="text" name="last_name_add" id="last_name_add" class="text ui-widget-content ui-corner-all" />
<label for="first_name_add">First Name</label>
<input type="text" name="first_name_add" id="first_name_add" class="text ui-widget-content ui-corner-all" />
<label for="id_add">ID Number</label>
<input type="text" name="id_add" id="id_add" value="" class="text ui-widget-content ui-corner-all" />
<label for="jersey_add">Jersey Number</label>
<input type="text" name="jersey_add" id="jersey_add" value="" class="text ui-widget-content ui-corner-all" />
<label for="dob_add">DOB (YYYY-MM-DD)</label>
<input type="text" name="dob_add" id="dob_add" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
Thanks for any and all help!
I am assuming that this-
<li><div id="all">
<div id="result"><div id="names"><div id="lnames"><?php echo $final_msg; ?></div><div id="fnames"> <?php echo $firstName ?></div></div><div id="dobs"><?php echo $DOB ?></div><div id="ids"><?php echo $ID ?></div>
<div id="add"><button type="button" id="add_player2" > Add Player </button></div></div>
</div></li>
is the html in this success function-
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
If so, it would be better if you returned a json encoded array json_encode(), instead of html - eg.
[{"lname":"Jones","fname":"Joe","dob":"2000-01-13","id":"6"},
{"lname":"Jones","fname":"Jim","dob":"2001-04-04","id":"19"},
{"lname":"Jones","fname":"Bob","dob":"1999-10-23","id":"32"}]
php code on ../../Search/searchdata.php would be something like -
while($row = _fetched_array_) {
$players[] = array(
'lname' => $row['lname'],
'fname' => $row['fname'],
'dob' => $row['dob'],
'id' => $row['id']
);
}
// Return JSON Encoded Array
echo json_encode($players);
Then you can create links for each one, and on selecting the player it will add it to your form fields
success: function(html){
players = $.parseJSON(html); //create json array in format above
player_links = ''; // create blank variable
for (var i = 0; i < players.length; i++){ // loop through each of the returned players
// Echo Player First & Last Name and a link to add
player_links += '<li>' + players[i].lname + ' ' + players[i].fname + ' Add Player</li>';
}
$("#insert_search").show();
$("#insert_search").append(player_links);
$("#flash").hide();
// Bind .player_details click
$('.player_details').click(function () {
var pid = $(this).data('player');
$('#last_name_add').val(players[pid].lname);
$('#first_name_add').val(players[pid].fname);
$('#id_add').val(players[pid].id);
$('#dob_add').val(players[pid].dob);
$("#search").dialog("close");
});
}
I have created a simple example of this as a jsFiddle - http://jsfiddle.net/8jcLQ/

Javascript Automated Click?

I have the following function for a jquery login form and want to run it when php detects that the user is not logged in by echoing a javascript function that clicks the login button automatically
jq Code:
<script type="text/javascript">
$(document).ready(function() {
$('a.login-window, a.log').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
//Fade in the Popup
$(loginBox).fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
</script>
HTML
<div id="login-box" class="login-popup">
<img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" />
<form method="post" method="post" name="f" id="f" class="signin" action="login.php">
<fieldset class="textbox">
<label class="username">
<span>Username or email</span>
<input id="username" name="username" value="" type="text" autocomplete="on" placeholder="Username">
</label>
<label class="password">
<span>Password</span>
<input id="password" name="password" value="" type="password" placeholder="Password">
</label>
<button class="submit button" type="submit" name="Submit" value="<?php echo $lang['LOGIN'];" style="background:none;">Sign in</button>
<p>
<a class="forgot" href="#">Forgot your password?</a>
</p>
</fieldset>
</form>
</div>
if you want to auto click a button, you are looking for .trigger
$('#some-id').trigger('click');
.trigger( 'event' ) explanation:
Execute all handlers and behaviors attached to the matched elements
for the given event type.
(as you are already using jQuery, hence)
<?php
if (!$lang['LOGIN']) {
echo '<script type="text/javascript">';
echo '$(function() {';
echo '$("a.login-window, a.log").trigger("click")';
echo '});';
echo '</script>';
}
?>
var loggedIn = isUserLoggedIn(); // check login status
if(!loggedIn){
$('a.login-window, a.log').trigger('click');
}
.trigger Docs

Run jQuery modal dialog if PHP returns 0

I need to run jQuery modal dialog if mainOptim.php returns 0. Now Firebug says $dialog is not defined. What should I change in the code?
<script type="text/javascript">
$(document).ready(function() {
var $dialog = $('<div></div>')
.html('This dialog will show every time!')
.dialog({
autoOpen: false,
title: 'Basic Dialog'
});
});
function click_function_ps() {
$.ajax({
url: 'callpage.php?page=optim/mainOptim.php',
data: 'earl='+$('#earl').val(),
success: function(html,msg){
if(msg === '1'){
$('#opt_container').html(html);
} else {
$dialog.dialog('open');
return false;
}
}
});
}
</script>
<div id="fragment-2">
<table width="100%">
<tr>
<td width="100%">
<form name="optform" method="post" action="#">
<div class = "boxx">
<label for="earl"><span>Parameter:</span></label>
<input type="text" class="input-text" value="5" size="11" maxlength="11" name="earl" id="earl">
</div>
<br/>
<div class="buttons">
<a href="#" class="regular" onclick="click_function_ps();">
<img src="images/opt.png" alt=""/> Run
</a>
</div>
</form>
</td>
</tr>
</table>
</div>
That's because you declared it as a local variable using the var keyword in the ready scope.
Remove the var in front of the declaration (var $dialog).

Categories