I would like to close my modalbox, so I return to the same page, after I click the "Select" button.
I am on shuffle.php. I open the modalbox and call the code in updaterecords.php. When I click Select I should return to shuffle.php. The problem is right now that I am redirected to updaterecords.php.
I try to solve that with adding this code to my AJAX call:
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
But I am still redirected. Is the code I added in the wrong place?
shuffle.php
<div class="modal-footer msg">
<form action="updaterecords.php" method="post">
<input type="hidden" id="fantasy-id" value="" name="id" />
<button type="submit" name="selectStore" >Select</button>
<button type="button" data-dismiss="modal">Close</button>
</form>
</div>
updaterecords.php
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});
Please try to use $('.modal').modal('hide'); on updaterecords.php.
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$('.modal').modal('hide');
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});
Related
BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->delete();
I have an ajax request and the result shound go in a bootstrap tooltip field.
ยดยดยด
function loadTooltip(idExecution) {
$('#tooltip' + idExecution).attr('title', "");
$.ajax({
url: (URL + "managementExecution/getAllPartecipantsExecution/"),
type: "POST",
dataType: "json",
data: {
idExecution: idExecution
},
success: function (text) {
$('body').tooltip({
selector: '[rel=tooltip]'
});
$.each(text, function (k, v) {
var oldTitle = "";
var lastname = v.lastname;
var oldTitle = $('#tooltip' + idExecution).attr('title');
$('#tooltip' + idExecution).tooltip({html:true}).attr('title', oldTitle + "<br>" + lastname);
});
}
});
}
This is my html:
<a id="tooltip<?php echo $e['id'];?>" onmouseover="loadTooltip('<?php echo $e['id'];?>')" href="<?php echo URL . 'managementExecution/getDataExecution/' . $e[DB_EXECUTION_ID]; ?>">
<?php echo date("d.m.y", strtotime($e[DB_EXECUTION_START]))."<br>".date("d.m.y", strtotime($e[DB_EXECUTION_END])); ?>
</a>
It's working but the text is not going to a new line, the <br> tag is not recognized and i have the text with <br> inside
index.php
function delete_function(value){
alert("value is "+value);
$(document).ready(function () {
$.ajax({
url: "fields.php",
type: "POST",
datatype: "html",
data: { "delval": value},
success: function(data){
//console.log(data);
//jQuery(".res").html(data);
// var result = $(data).filter('div.dummy');
//$(".dummy").append($(data).filter('div.dummy'));
var input_value = $(data).find("#lastname").val();
alert(input_value);
//$(data) = "dfsadf";
$(".dummy").replaceWith($(data).find('#lab').val());
//$(".dummy").replaceWith($(data).val());
//$(".dummy").replaceWith($(data).find('#submit').val());
// $(".dummy").remove();
//alert(data);
$(".class"+value).remove();
}
});
alert("delete clicked ");
});
}
fields.php
" value="iamkarthik">
" value= id="firstname" placeholder="First Name">
" placeholder="Last Name">
" placeholder="Email address">
" placeholder="Department">
" placeholder="Date of joining">
" placeholder="Basic pay">
" onclick="delete_function()" id="delete" value="delete" class="input_fields" >
on delete function, please remove the $(document).ready , as this is event listener, it isn't triggered when you call the function
function delete_function(value){
alert("value is "+value);
$.ajax({
url: "fields.php",
type: "POST",
datatype: "html",
data: { "delval": value},
success: function(data){
//console.log(data);
//jQuery(".res").html(data);
// var result = $(data).filter('div.dummy');
//$(".dummy").append($(data).filter('div.dummy'));
var input_value = $(data).find("#lastname").val();
alert(input_value);
//$(data) = "dfsadf";
$(".dummy").replaceWith($(data).find('#lab').val());
//$(".dummy").replaceWith($(data).val());
//$(".dummy").replaceWith($(data).find('#submit').val());
// $(".dummy").remove();
//alert(data);
$(".class"+value).remove();
}
});
alert("delete clicked ");
}
my requirement of coding is "when i am click on wishlist heart icon. if i am not login, then i am going to login page & If i am login then fa-fa heart color is change orange when i am added item in wishlist & grey when it remove. i am sending json response refer my coding.
controller:
public function add_to_wishlist(Request $req)
{
$userId=Session::get('userid');
if(empty($userId))
{
return response()->json(['status'=> 1]);
}
else
{
$checkWishlist=DB::select('select * from wishlist where user_id=? && product_id=?',[$userId,$req->sub_id]);
if($checkWishlist)
{
DB::table('wishlist')->where('user_id',$userId)->where('product_id',$req->sub_id)->delete();
return response()->json(['status'=> 2]);
}
else
{
DB::table('wishlist')->insert(['user_id'=>$userId,'product_id'=>$req->sub_id]);
return response()->json(['status'=> 3]);
}
}
}
blade code:
<input type="text" name="status" id="status" class="form-control status" value="">
<a class="sub" data-id="{{$value->sub_id}}" href="#"><i class="fa fa-heart" style="float:right;color:grey"></i></a>
jquery and ajax:
<script type="text/javascript">
$(document).ready(function(){
$('.sub').click(function(e) {
var sub_id=$(this).attr('data-id');
var input=$(this).prev();
e.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/add-to-wishlist') }}",
method: 'get',
data: {
sub_id: sub_id,
},
success: function(result){
input.val(result.status);
}});
});
});
</script>
First add dataType:'JSON'
Then add some conditions in success function:
$('.sub').click(function(e) {
var input = $(this);
...
...
$.ajax({
...
success: function(result){
var status = result.status;
input.val(status);
if(status==1){
//Not logged in
window.location.href ="path/to/login";
}else if(status==2){
//Delete
input.next().css('background','gray');
}else{
//Logged in
input.next().css('background','orange');
}
}});
});
});
I have to execute a authentication process using JQuery. I have two textbox UserName and Password and two button are Login and Submit.
If i am clicking on Submit button then it will automatically fire validation that good and this functionality i have to implement on Login button click.
So how could i achieve automatic validation on button click?
Why i would like this:
Usin JQuery it is sending a request to the server with UserName and
Password during that time i will display Processing....
Then it will verify supplied value with database and return response
with Success or Failed then i will display either Success or Failed.
Here is the code snippet:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm(null, null, FormMethod.Get, new { id = "Form1", name = "Form1" }))
{
<table>
<tr>
<td>
User Name
</td>
<td>#Html.TextBoxFor(u => u.UserName, new { id = "txtUser" }) #Html.ValidationMessageFor(u => u.UserName)
</td>
</tr>
<tr>
<td>
Password
</td>
<td>#Html.TextBoxFor(u => u.Password, new { id = "txtPassword" }) #Html.ValidationMessageFor(u => u.Password)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Login" onclick="checkAuthentication();" />
<input type="submit" value="Submit" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvStatus" class="loginMessageStatus">
</div>
</td>
</tr>
</table>
}
<script language="javascript" type="text/javascript">
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
Note:-
Validation completely work with Submit button
Verifying process completely work with Login button ( just i have to integrate validation with Login button)
you can do the validation using the onclick of the submit button with the following event handler:
Add an identifier to the button:
<input id="SubmitButton" type="submit" value="Submit" />
JavaScript:
$(document).ready(function(){
$("#SubmitButton").click(function(){
return checkAuthentication();
});
});
Change the Validation method to return whether it failed or not:
function checkAuthentication() {
var _user = jQuery.trim(jQuery('#txtUserName').val());
var _pass = jQuery.trim(jQuery('#txtPassword').val());
if (_user.length == 0 || _pass.length == 0) {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>User Name and Password are required!</div>")
return false;
}
else {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
return true;
}
}
This should then stop the submit if the validation fails.
I have solved this one:
I have used only submit button
<input id="btnLogin" type="submit" value="Login" />
Following are the updated code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//$.preloadCssImages();
$("#btnLogin").click(function () {
if ($("#Form1").valid() == true) {
checkAuthentication();
return false;
}
});
});
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
</script>