Duplicate validation (Number) and show an error message - ajax

I have a function where I can add rows using my button. My target is when the user enters a number that is already on the database, the alert will pop up or any error messages that will say "The number/s you entered is/are already used, please use another number"**. Is there a way where I can make it work? I provided my screenshot and my codes below. Thank you
Views:
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Light</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1"/>
<span id="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
script:
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand'+rowIndex+'" id="lightBand1" value="" class="form" type="number" /></td>"' +
' <span id="email_result"></span>' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
ajax:
$(document).ready(function(){
$('#lightBand1').change(function(){
var lightBand1 = $('#lightBand1').val();
if(lightBand1 != '')
{
$.ajax({
url:"<?php echo base_url(); ?>participant/check_number_avalibility",
method:"POST",
data:{lightBand1:lightBand1},
success:function(data){
$('#email_result').html(data);
}
});
}
});
});
Controller:
function check_number_avalibility()
{
if(!filter_var($_POST["lightBand1"], FILTER_VALIDATE_INT))
{
echo '<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> Invalid LightBand</span></label>';
}
else
{
$this->load->model("Participant_repository");
if($this->participants->is_number_available($_POST["lightBand1"]))
{
echo '<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> LightBand is already registered</label>';
}
else
{
echo '<label class="text-success"><span class="glyphicon glyphicon-ok"></span> LightBand Available</label>';
}
}
}
Model:
function is_number_available($lightBand)
{
$this->db->where('lightBand', $lightBand);
$query = $this->db->get("entry");
if($query->num_rows() > 0)
{
return true;
}
else
{
return false;
}
}
**
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="light' + rowIndex + '" placeholder="duplicate validation here" id="auto" value="" class="form" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Light</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" name="light1" placeholder="duplicate validation here" required id="auto" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
**

As your input are dynamically generated you need bind it with static element so change your event handler like this $(document).on('change', 'input[name*=lightBand]', function() {..}) .Then , use $(this).val() to get value of input where change has occurred and pass same to your ajax .
In your current jquery code you have many duplicate ids so change them to class . Also , add class email_result to your span tag currrently you have id here and <span class="email_result"></span> is outside td tag put that inside td tag .
Updated jquery code:
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this)//save slector
if (lightBand1 != '') {
$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {
selector.next('.email_result').html(data);//use next here ..
}
});
}
});
Quick Demo :
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Light</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>

Related

Datatable column search with HTML Textbox

I am trying to enable column search with datatables. I set u Search textboxes with HTML :
<div class="col-lg-3 mb-lg-0 mb-6">
<label>Id:</label>
<input type="text" name="textbox[]" class="form-control datatable-input" placeholder="E.g: 1" data-col-index="0" />
</div>
<div class="col-lg-3 mb-lg-0 mb-6">
<label>Amount:</label>
<input type="text" name="textbox[]" class="form-control datatable-input" placeholder="E.g: 4500" data-col-index="1" />
</div>
And here is my search Ajax :
function addSearchControl(json) {
$("#searchTable thead");
$("#searchTable").each(function (index) {
var searchControl = $('input[name="textbox[]"]');
searchControl.on('keyup', function () {
var indexDataTable = searchControl.index( this );
alert( this.value + ', ' + indexDataTable );
empTable.column(indexDataTable).search(searchControl.val()).draw();
});
});
}
But only first textbox is working and when I type something on the second textbox I get the index which is 1 but cannot search on column 1
This is for Dropdown search I get the value but it doesnt search the table just renders table again :
$('#dropDownMenuKategorie :selected').text();
$("#dropDownMenuKategorie").on('change', function() {
var textSelected = $('#dropDownMenuKategorie option:selected').val();
alert(textSelected);
empTable.column(9).search(textSelected).draw();
});
Maybe you can change the column().search() method like this
empTable.column(indexDataTable).search(this.value).draw();
Sample:
<div class="col-lg-3 mb-lg-0 mb-6">
<label>Name:</label>
<input type="text" name="textbox[]" class="form-control datatable-input" placeholder="E.g: 1" data-col-index="0" />
</div>
<div class="col-lg-3 mb-lg-0 mb-6">
<label>Position:</label>
<input type="text" name="textbox[]" class="form-control datatable-input" placeholder="E.g: 4500" data-col-index="1" />
</div>
<div class="col-lg-12">
<table id="searchTable" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
</tbody>
</table>
</div>
#section scripts{
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" />
<script>
$(document).ready(function () {
var empTable = $("#searchTable").DataTable();
$("#searchTable").each(function (index) {
var searchControl = $('input[name="textbox[]"]');
searchControl.on('keyup', function () {
var indexDataTable = searchControl.index(this);
//alert(this.value + ', ' + indexDataTable);
empTable.column(indexDataTable).search(this.value).draw();
});
});
})
</script>
}
Result:

How Can I load Data From Database When Class Is Selected?

<div class="float-right">
<form>
<div class="form-group row">
<div class="col-sm-12">
<select class="form-control" id="select_id" >
<option> Choose Class </option>
#foreach($allclass as $classs)
<option value="{{$classs->id}}"> {{$classs->class}} </option>
#endforeach
</select>
</div>
</div>
</form>
</div>
This is Where user choose Class and when user choose the class i want to view data as per the class .
class SectionController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Clas $clas)
{
$allclass = Clas::all();
$sections = $clas->sections;
return view('admin.section.index')
->with('i',$i = 1)
->with('sections',$sections)
->with('allclass',$allclass);
}
This is my section Controller
public function clas(){
return $this->belongsTo(Clas::class);
}
This is Section Model where i keep realtion between clas and section .
public function up()
{
Schema::create('sections', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('section');
$table->string('category');
$table->string('capacity');
$table->integer('clas_id');
$table->integer('teacher_id');
$table->text('note');
$table->softDeletes();
$table->timestamps();
});
}
This is my sectios db .
<table id="userTable" class="table table-bordered table-striped table-vcenter js-dataTable-full-pagination">
<thead>
<tr>
<th class="text-center">S.n</th>
<th class="d-none d-sm-table-cell">Section</th>
<th class="d-none d-sm-table-cell">Category</th>
<th class="d-none d-sm-table-cell">Capacity</th>
<th class="d-none d-sm-table-cell">Teacher Name</th>
<th class="d-none d-sm-table-cell">Note</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
#foreach($sections as $s)
<tr id="table-data">
<td class="d-none d-sm-table-cell" width="8%">{{1}}</td>
<td class="d-none d-sm-table-cell" width="15%">{{$s->section}}</td>
<td class="d-none d-sm-table-cell" width="15%"> {{$s->category}}</td>
<td class="d-none d-sm-table-cell" width="15%"> {{$s->capacity}}</td>
<td class="d-none d-sm-table-cell" width="15%">
{{$s->teacher->user->name}}
</td>
<td class="d-none d-sm-table-cell" width="15%"> {{$s->note}}</td>
<td class="d-none d-sm-table-cell" width="20%">
<form class="" action="{{ route('section.destroy',$s->id) }}" method="post">
#csrf
#method('DELETE')
<a href="{{$s->trashed()?route('section.restore',$s->id):route('section.edit',$s->id)}}">
<button type="button" class="btn btn-warning mr-5 mb-5 " title="{{ $s->trashed()?'Recover':'Edit'}}">
<i class="{{$s->trashed()?'fa fa-recycle':'fa fa-edit'}}"></i>
</button>
</a>
<button type="submit" class="btn btn-danger mr-5 mb-5" title="{{ $s->trashed()?'Delete':'Trash'}}">
<i class="{{$s->trashed()?'fa fa-trash':'fa fa-minus-circle'}}"></i>
</button>
</form>
</td>
</tr>
#php $i++ #endphp
#endforeach
</tbody>
</table>
This is my table for viewing section only when class is selected .
how can i View sections only when some class is selected .
Sorry For my english .
Now I want to view section only when class is selected. How can i do that ?
$('#select_id').change(function(){
// alert('hello');
var cid = $(this).val();
if(cid){
$.ajax({
dataType: "json",
url: 'getSectionsForClass'+cid,
type:"GET",
success: function(response){
console.log (Object.values(response).length);
$('#userTable tbody').empty(); // Empty <tbody>
if(response != null){
var len = Object.values(response).length;
}
$.each(response,function(key,value){
// $("#section_id").append('<option value="'+key+'">'+value+'</option>');
console.log(key,value);
});
if(len >0){
for(var i=0; i<len; i++){
var section = response[i].section;
var capacity = response[i].capacity;
var category = response[i].category;
var teacher = response[i].teacher_id;
var note = response[i].note;
var tr_str = "<tr>" +
"<td align='center'>" + (i+1) + "</td>" +
"<td align='center'>" + section + "</td>" +
"<td align='center'>" + capacity + "</td>" +
"<td align='center'>" + category + "</td>" +
"<td align='center'>" + teacher + "</td>" +
"<td align='center'>" + note + "</td>" +
"<td align='center'><button type='submit' class='btn btn-danger mr-5 mb-5'>" + + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}else{
var tr_str = "<tr>" +
"<td align='center' >No record Availasb.</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
},error: (error) => {
console.log(JSON.stringify(error));
}
});
}
});
public function getSectionsForClass(Request $request ,$id )
{
$section = Section::all()->where('clas_id',$id);
return response()->json($section);
}
I have added some ajax but its only show first class when I choose another class it shows an error

Wordpress Datatrans Ajax implementation

I'm trying to implement a creditcard payment service (of datatrans.ch) into a wordpress based site. Datatrans offers an Ajax API, which you can take a look at here:
Datatrans Ajax API
Example Code
I copy/pasted the example code and saved it inside a html file on my machine. Running it works properly. In the next step I tried implementing it in wordpress by creating the following function:
function datatrans_payment_ajax($lang, $currency, $amount) {
$merchant_id = 101...; // ... on my machine it is numeric of course ;)
wp_deregister_script('datatrans-ajax');
wp_register_script('datatrans-ajax', 'https://pilot.datatrans.biz/upp/ajax/api.js?merchantId='.$merchant_id, false);
wp_enqueue_script('datatrans-ajax');
?>
<noscript>
<p class="err">
JavaScript is disabled in your browser.<br/>
This showcase requires JavaScript.
</p>
</noscript>
<div>
<h3>Step 1: Ajax UPP.paymentRequest(...)</h3>
<form id="uppform">
<fieldset>
<input type="hidden" name="language" value="<?php echo $lang; ?>"/>
<table cellspacing="0" cellpadding="3" width="550">
<tr>
<td align="left">Merchant Id :</td>
<td style="width: 10px"> </td>
<td align="left"><input type="text" size="20" name="merchantId" value="<?php echo $merchant_id; ?>"/>
</td>
</tr>
<tr>
<td align="left">Amount :</td>
<td> </td>
<td align="left"><input type="text" size="20" name="amount" value="<?php echo $amount; ?>"/> (= 10.00)
</td>
</tr>
<tr>
<td align="left">Currency :</td>
<td> </td>
<td align="left"><input type="text" size="20" name="currency" value="<?php echo $currency; ?>"/>
</td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td align="left">Card Number :</td>
<td> </td>
<td align="left"><input type="text" size="24" name="cardNumber" value="4242424242424242"/>
</td>
</tr>
<tr>
<td align="left">Expiry :</td>
<td> </td>
<td align="left">
<input type="text" size="4" name="expm" value="12"/>
<input type="text" size="4" name="expy" value="15"/> (MM/YY)
</td>
</tr>
<tr>
<td align="left">CVV code :</td>
<td> </td>
<td align="left"><input type="text" size="4" name="cvv" value="123"/>
</td>
</tr>
<tr style="display: none;">
<td align="left">Process mode :</td>
<td> </td>
<td align="left">
<input type="radio" name="mode" id="auto" value="auto" checked="checked"/> <label for="auto">Automatic 3D ACS call using API</label>
<br/>
<input type="radio" name="mode" id="manual" value="manual"/> <label for="manual">Manual redirection to 3D ACS</label>
</td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td align="left"><input type="button" class="button"
onclick="callPayment()" value="send"/><span class="buttend"></span>
</td>
</tr>
</table>
</fieldset>
</form>
<div id="frameHolder"></div>
<div id="response" style="width: 400px;"></div>
<div id="step2" style="display: none;">
<h3>Step 2: XML authorizeSplit (server-2-server request)</h3>
<form action="https://pilot.datatrans.biz/upp/jsp/XML_authorizeSplitEx.jsp" method="post" target="_parent">
<fieldset>
<textarea style="width: 400px; height: 150px;" name="xmlRequest"></textarea>
<div>
<input type="submit" class="button" value="send"/><span class="buttend"></span>
</div>
</fieldset>
</form>
</div>
<script type="text/javascript">
var mode;
var params;
function callPayment()
{
mode = $("input[name=mode]:checked").val();
// read form values
params = {
merchantId: $("input[name=merchantId]").val(),
cardNumber: $("input[name=cardNumber]").val(),
expy: $("input[name=expy]").val(),
expm: $("input[name=expm]").val(),
cvv: $("input[name=cvv]").val(),
currency: $("input[name=currency]").val(),
amount: $("input[name=amount]").val()
}
// call paymentRequest, response will be received in responseCallback
if ( mode == "auto" )
{
params.returnUrl = "https://pilot.datatrans.biz/upp/ajax/sample-merchant-return-page.html";
UPP.paymentRequest( params, responseCallback, frameCallback );
}
else
if ( mode == "manual" )
{
UPP.paymentRequest( params, responseCallback );
}
};
function frameCallback()
{
// create iframe and add it to document
var iframe = $("<iframe/>").attr( "id", "paymentIFrame" ).width( 390 ).height( 400 );
$("#frameHolder").append( iframe );
$("form#uppform").hide(); //hide the form
return iframe[0];
};
function responseCallback( response )
{
var responseElm = $("#response");
responseElm
.empty()
.append( "<h4>Ajax response:</h4>")
.append( $("<div/>").text("status: " + response.status) )
.append( $("<div/>").text("uppTransactionId: " + response.uppTransactionId) );
if ( JSON.stringify )
responseElm
.append( $("<div/>").html( "Complete JSON response: " + JSON.stringify( response ).replace( /,/g, ", ") ) )
if ( mode == "auto" )
{
if ( response.status == "success" )
{
// This step will be done server-2-server
$("#step2 textarea").val(
"<<?php?>?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
"<authorizationSplit version=\"1\">\n" +
"<body merchantId=\"" + $("input[name=merchantId]").val() + "\">\n" +
"<transaction refno=\"to_be_filled\">\n" +
" <request>\n" +
" <uppTransactionId>" + response.uppTransactionId + "</uppTransactionId>\n" +
" <amount>" + $("input[name=amount]").val() + "</amount>\n" +
" <currency>" + $("input[name=currency]").val() + "</currency>\n" +
" </request>\n" +
" </transaction>\n" +
"</body>\n" +
"</authorizationSplit>"
);
$("#step2").show();
$("#uppform").hide();
}
if ( response.is3DEnrolled ) // close/remove the iframe
{
$("#paymentIFrame").remove();
}
}
else
if ( mode == "manual" ) // manual mode used, browser has to be redirected to ACSURL
{
if ( response.is3DEnrolled && response.status == "success" )
{
responseElm.append( $("<div/>").html( "Redirecting page to ACS in 3 seconds..." ) );
setTimeout( function() {
params.uppTransactionId = response.uppTransactionId;
params.errorUrl = "https://pilot.datatrans.biz/upp/merchant/errorPage.jsp";
params.returnUrl = "https://pilot.datatrans.biz/upp/merchant/successPage.jsp";
window.parent.location = response.ACSURL + "?" + $.param( params );
}, 3000 );
}
}
};
</script>
</div>
When I run it, I receive an error status code 1003, saying that the uppTransactionId is undefined which should result from the responseCallback. So I guess it has something to do with the usual processing of Ajax calls in wordpress which must go through the admin-ajax.php file in the wp-admin folder!? I am not sure how to cut this datatrans implementation into pieces to make it fit the wordpress Ajax processing. Furthermore I would like to know if you think that my guess is even right regarding what causes the error?
Thanks in advance.
Cheers,
Tim
Ask them to open test account for you, and then you could test with your MerchantID on pilot servers with all features. If you copy/paste code from their examples i think this will not work. Those are just examples of implementation.
You can try to use Merchant-ID:1000011011 but this is shared from all users, so you cannot set landing redirect pages (on success, on error)
Also check what encoding you use:
UTF-8 encoding: /jsp/upStart.jsp
ISO encoding: /jsp/upStartIso.jsp
And most common mistake is price format, if you price is 15.25 you need to send 1525.
Also if you wish to use 3D secure, you need to activate this in datatrans backend.

MVC3 ASP.NET Ajax BeginForm doesn't work sometimes when it's injected by other Ajax

I'm trying to have some Ajax form in the page which is not working at all, it does not send any requests on submit, noting in firebug, the form is being loaded to page by ajax, but I have other forms which are loaded to form by ajax into a jquery UI dialog and they are working fine, here is my whole partial view code , (the Part with action "SeacrhTasksTable" not working) I'd attach the rendered the whole HTML but it's so big.
#model APS.HelpDesk.UI.MyModel<APS.HelpDesk.Data.App_ProjectTask>
<h2>
پروژه
#ViewBag.ProjectTitle
</h2>
<div class="wrapperTask">
<div class="firstTask">
#* <input type="hidden" value="#(ViewBag.ProjectId)" />*#
#Ajax.ActionLink("تعریف کار جدید", "AddProjectTaskDialog", new
{
Id = ViewBag.ProjectId,
area = "ProjectAdmin"
}, new AjaxOptions()
{
HttpMethod = "GET",
LoadingElementId = "AddProjectTaskLoadingGif",
UpdateTargetId = "AddProjectTaskDialog",
InsertionMode = InsertionMode.Replace,
OnBegin = "clearDialogs();",
OnSuccess = " $('#AddProjectTaskDialog').dialog('open');"
}, new { id = "AddProjecTaskLink" })
بارگذاری مجدد جدول
</div>
<div class="secondTask">
<div id="AddProjectTaskLoadingGif" style="display: none;">
<img src="#Url.Content("~/Content/Images/ajax-loader/253L.gif")" alt="" />
</div>
</div>
</div>
<div id="test">
<table>
<tr>
<th>
#
</th>
<th>
کد کار
</th>
<th>
عنوان کار
</th>
<th style="min-width: 300px;">
مختصری از توضيحات
</th>
<th>
تاريخ ايجاد کار
</th>
<th>
مهلت انجام
</th>
<th>
وضعيت
</th>
<th>
وابستگی های کار
</th>
<th colspan="2">
ويرايش و حذف
</th>
</tr>
#using (Ajax.BeginForm("SeacrhTasksTable", new { area = "ProjectAdmin" }, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "test"
}))
{
<tr>
<td>
</td>
<td>
<input type="text" id="IdTask" style = "width:40px" name = "Id" />
</td>
<td>
<input type="text" id="TitleTask" style = "width:80%;" placeholder = "جست و جو" name = "Title" />
</td>
<td style="min-width: 250px;">
<input type="text" id="DescriptionTask" style = "width:80%;" placeholder = "جست و جو" name = "Description" />
</td>
<td>
<input type="text" id="DeliverDateTask" style = "width:80%;" placeholder = "جست و جو" name = "DeliverDate" />
</td>
<td>
<input type="text" id="DeadlineDateTask" style = "width:80%;" placeholder = "جست و جو" name = "DeadlineDate" />
</td>
<td>
<select name="Status">
<option value="0"> همه</option>
<option value="1">شروع نشده</option>
<option value="2">در حال انجام</option>
<option value="3">تمام شده</option>
<option value="4">بی مسئول</option>
</select>
</td>
<td colspan="4">
<input type="submit" value="submit" style="" />
<input type="hidden" value="#(ViewBag.ProjectId)" name="ProjectId" id ="ProjectIdTask"/>
</td>
</tr>
}
<tbody id="TaskList">
#Html.Partial("_ProjectTaskList", Model.MyList)
</tbody>
<tfoot>
<tr>
<td colspan="3">
صفحه
#(Model.PageIndex + 1)
از
#Model.TotalPages
[ تعداد کل : #Model.TotalCount ]
</td>
<td id="pagesizeTaskTd" style="text-align: center;">
سايز صفحه
<select id="pagesizeTask">
<option value="5">5</option>
<option value="10" selected="selected">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</td>
<td colspan="6" align="left" class="tfoot-padding" id="morepagesTask">
#{
int start = Model.PageIndex;
if (start > 0)
{
int c = 0;
while (start > 0 && c < 4)
{
c++;
start--;
}
}
for (int j = start; j < Model.TotalPages && j < start + 10; j++)
{
if (Model.PageIndex != j)
{
<span>
#Ajax.ActionLink((j + 1).ToString(), "TaskListTablePage", "Project", new
{
Id = ViewBag.ProjectId,
PageIndex = j,
PageSize = Model.PageSize,
area = "ProjectAdmin"
}, new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "test",
InsertionMode = InsertionMode.Replace
}, new { mode = "mode" })
</span>
}
else
{
<span><b style="text-decoration: underline;">#(j + 1)</b></span>
<input type="hidden" id="PIndexAll" value="#(j)" />
}
}
if (Model.PageIndex + 10 < Model.TotalPages)
{
<span>. . . </span>
}
}
</td>
</tr>
</tfoot>
</table>
</div>
<div id="AddProjectTaskDialog" title="تعریف کار جدید" style="text-align: right;">
</div>
<div id="EditProjectTaskDialog" title="ويرايش کار" style="text-align: right;">
</div>
<div id="ReportProjectTaskDialog" title="گزارش کل کار" style="text-align: right;">
</div>
<div id="DescriptionProjectTaskDialog" title="توضيح کار" style="text-align: right;">
</div>
<div id="EditProjectDepenDialog" style="text-align: right;">
</div>
<div id="Taskresult">
</div>
<script type="text/javascript">
$("#AddProjectTaskDialog").dialog({
autoOpen: false,
width: 720,
modal: true,
draggable: true,
position: "top"
});
$("#EditProjectTaskDialog").dialog({
autoOpen: false,
width: 720,
modal: true,
draggable: true,
position: "top"
});
$("#EditProjectDepenDialog").dialog({
autoOpen: false,
width: 720,
modal: true,
draggable: true,
position: "top",
buttons: {
"OK": function () {
$(this).dialog("close");
}
}
});
$("#AddProjecTaskLink").button();
$("#resetbutton").button();
$("#pagesizeTask").live( 'change' , function (){
var val = $(this).find(":selected").val();
$("#morepagesTask").find('*[mode]').each(function(index){
var n=$(this).attr("href").lastIndexOf("=");
var t= $(this).attr("href").substring(0,n+1);
$(this).attr("href" ,t+val );
});
var url = '#Url.Action("TaskListTablePage", new { area = "ProjectAdmin" })';
url += '?Id=' + #(ViewBag.ProjectId);
url += '&PageIndex=' + $("#PIndexAll").val();
url += '&PageSize=' +val;
$.ajax({
url: url, type: 'get',
success: function (data, status) {
$("#test").html('');
$("#test").html(data);
}
});
});
$(".firstTask").delegate( '#resetbutton','click',function(){
var url = '#Url.Action("TaskListTablePage", new { area = "ProjectAdmin" })';
url += '?Id=' + #(ViewBag.ProjectId);
url += '&PageIndex=0' ;
url += '&PageSize=10';
$.ajax({
url: url, type: 'get',
success: function (data, status) {
$("#test").html('');
$("#test" ).html(data);
}
});
});
</script>
HTML of Form
<form action="/ProjectAdmin/Project/SeacrhTasksTable" data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#test" id="form0" method="post"> <tr>
<td>
</td>
<td>
<input type="text" id="IdTask" style = "width:40px" name = "Id" />
</td>
<td>
<input type="text" id="TitleTask" style = "width:80%;" placeholder = "جست و جو" name = "Title" />
</td>
<td style="min-width: 250px;">
<input type="text" id="DescriptionTask" style = "width:80%;" placeholder = "جست و جو" name = "Description" />
</td>
<td>
<input type="text" id="DeliverDateTask" style = "width:80%;" placeholder = "جست و جو" name = "DeliverDate" />
</td>
<td>
<input type="text" id="DeadlineDateTask" style = "width:80%;" placeholder = "جست و جو" name = "DeadlineDate" />
</td>
<td>
<select name="Status">
<option value="0"> همه</option>
<option value="1">شروع نشده</option>
<option value="2">در حال انجام</option>
<option value="3">تمام شده</option>
<option value="4">بی مسئول</option>
</select>
</td>
<td colspan="4">
<input type="submit" value="submit" style="" />
<input type="hidden" value="38" name="ProjectId" id ="ProjectIdTask"/>
</td>
</tr>
</form>
Your code doesn't work because you have invalid markup. By invalid markup I mean that you have a <form> nested directly inside a <tr> which is forbidden by the specification. You cannot have a <form> inside a <table>, <tbody> or <tr>.
To illustrate the problem in a simplified manner, here's what you have currently which is invalid:
<table>
<tr>
<form>
<td>Foo</td>
<td>Bar</td>
<td><input type="submit" /></td>
</form>
</tr>
</table>
Just inspect the DOM with FireBug and you will see how your <form> is floating alone (opening and closing immediately) without any elements inside.
This is invalid markup and it results in undefined behavior which in your case translates by the browser simply not submitting the form. The reason this happens is because the unobtrusive-ajax library that you are using subscribes to the submit event to all ajax forms using a .live:
$("form[data-ajax=true]").live("submit", function (evt) {
...
});
The thing is that the submit event is never raised in this case. A similar question has been asked yesterday with the same problem.
To fix this problem you could use nested tables:
<table>
<tr>
<td>
<form>
<table>
<tr>
<td>Foo</td>
<td>Bar</td>
<td><input type="submit" /></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
So simply put your Ajax.BeginForm inside a <td> and then use a nested table to put the elements.

ajax login in yii framework

I have new homepage with login and register with unlogin user.
homepage.php
<script type="text/javascript" >
$(document).ready(function()
{
$("#btnLogin").click(function()
{
var username= $("#usernamelogin").val();
var password=$("#passwordlogin").val();
var remember = $("#rememberlogin").is(':checked');
var dataString = 'usernamelogin='+ username + '&passwordlogin=' + password + '&rememberlogin=' + remember;
$.ajax
({
type: "POST",
url: "homepage",
data: dataString,
cache: false,
success: function(html)
{
alert(html);
}
});
});
});
</script>
<form action="" method="post" name="frmLogin" class="Login">
<table width="960px" align="center">
<tr>
<td rowspan="3" width="404"><label id="lbbanner"><b>UIT SOCIAL NETWORK</b></label></td>
<td width="216"><label>Username:</label></td>
<td width="324">Password:</td>
</tr>
<tr>
<td><input type="text" witdth="200px" id ="usernamelogin" name="txtUsernameLogin" /></td>
<td><input type="password" width="200px" id="passwordlogin" name="txtPasswordLogin" /></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" id="rememberlogin" name="checkRemember" /> Remember me!
<input type="button" value="Log in" id="btnLogin" name="Login"/></td>
<td colspan="2" align="right"></td>
</tr>
<tr>
</tr>
</table>
</form>
In SiteController I have actionHomePage()
public function actionHomePage() {
$model = new LoginForm();
$model->username = $_POST['usernamelogin'];
$model->password = $_POST['passwordlogin'];
$model->rememberMe = $_POST['rememberlogin'];
//echo $model->errors;
print_rcount(($model->getErrors()));
//echo $model->username . "&&" . $model->password . "$$" .$model->rememberMe;
// validate user input and redirect to the previous page if valid
if ($model->validate() && $model->login()) {
$this->loginStatus = true;
//$this->redirect(Yii::app()->user->returnUrl);
echo "SUCCESS";
} else {
echo "Error";
}
}
When I fill username and password with correct info but it return "ERROR"
$model->validate() is false but I have correct info.
I dont know what i am wrong in this part.
Your input variable names need to match the POST variables you are querying so
<td><input type="text" witdth="200px" id ="usernamelogin" name="txtUsernameLogin" /></td>
<td><input type="password" width="200px" id="passwordlogin" name="txtPasswordLogin" /></td>
should be like this:
<td><input type="text" witdth="200px" id ="usernamelogin" name="usernameLogin" /></td>
<td><input type="password" width="200px" id="passwordlogin" name="passwordLogin" /></td>
same for rememberlogin
because in actionHomePage() : $model->rememberMe = true or false; $_post return a string . You try :
($_POST['rememberlogin'] == "false") ? $model->rememberMe = false : $model->rememberMe = true ;

Resources