This code have an ajax script that delete a record and have an animation when deleting. But when I mix the ajax script with plugins confirm it's not working. What is the problem with this script?
This is the delete button in my table record.
<?php
echo' <tr class="record">
<td align="center"><img src="images/del.png"></td></tr>';
?>
Ajax with confirm plugins
<script>
$(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
$(function() {
$("<div />").attr("id", "dialog-confirm").append(
$("<p />").text('Are you sure?').css("text-align", "center").prepend(
$("<span />").addClass("ui-icon ui-icon-alert").css({
display: 'inline-block',
margin: '0px 7px 0px 0px'
})
)
).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function(){
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast").animate({ opacity: "hide" }, "slow");
}
});
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
return false;
}
}
}); // end Dialog
return false;
}); // end .delbtn
});
}); // end jquery load
</script>
i copy your code and do a test , it's useful! so , please check the file sequence, i do like this:
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
Related
I have a JQuery UI dialog that is used for making a backup of a file. It contains an input box so users can add a short description that will become part for the name of the backup file. So if the user enters "blue", the backup file name will be: file_blue_2020-08-08-11:10:23.
The form name is: bckup
In my Ajax code, I'm using var frm = $('form[name="bckup"]').serialize(); for the form.
The name of the input field is: dscrb
As you can see in my PHP code, I'm trying to get the value of dscrb but it does not work. The resulting file name is: file_2020-08-08-11:10:23. However, if I change the PHP code to use $_POST["frm"] instead of $_POST["dscrb"], the resulting file name is: file_dscrb=blue_2020-08-08-11:10:23
So this tells us that the data is being posted to the PHP page.
Why then does $_POST["dscrb"] not work?
HTML:
<div id="dialog-backup" style="display: none;" title="Blah?">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0px 12px 22px 0px;"></span>Blaha.</p>
<form name="bckup">
<p style="margin-left: 28px;"><label for="dscrb">Description: </label><input id="dscrb" type="text" style="z-index:10000" name="dscrb"> (optional)</p>
</form>
<p style="margin-left: 28px;">Blah?</p>
</div>
JS:
$("#backup").click(function() {
$( "#dialog-backup" ).dialog({
stack: true,
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Save": function() {
//$( this ).dialog( "close" );
$("#saveConf").trigger("click");
},
"Create a backup": function() {
$( this ).dialog( "close" );
var frm = $('form[name="bckup"]').serialize();
$.ajax({
url : "ajax_functions.php",
type: "post",
data: { action: "backup", frm: frm },
//dataType: "text",
dataType: 'json',
success : function (response) {
var response = response[0]
if (response && response.toLowerCase().indexOf("success") >= 0) {
$("#dialg-success-msg").text(response);
$("#dialg-success").dialog("open");
} else {
$("#dialg-failed-msg").text(response);
$("#dialg-failed").dialog("open");
}
},
error : function(response) {
$("#dialg-failed-msg").text(response);
$("#dialg-failed").dialog("open");
}
});
//return false;
//////////////////
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
PHP:
$dscrpn = isset($_POST["dscrb"]) ? trim(stripslashes($_POST["dscrb"]))."_" : '';
$backup_file = "backups/File_".$dscrpn.date('Y-m-d-H:i:s');
Since you are sending your post-data as frm: frm you will have to use $_POST['frm'] in PHP.
You will get a string like dcsbr=.... To convert this to an array use parse_str.
$form = [];
parse_str($_POST['frm'], $form);
var_dump($form);
Working example.
I got an associative array which I use to generate images. From these images I want to select two or more pictures to get one random.
My code works but I got two questions:
How can I improve my code?
And how can I use json or something else that my site doesn't refresh after submit?
<style>
.check {
opacity: 0.5;
color: #996;
}
</style>
<script>
function getRandomInt( min, max )
{
return Math.floor( Math.random() * (max - min + 1) ) + min;
}
function debug()
{
console.log( $( "img.check" )[0] );
}
$( document ).ready( function()
{
$( "form" ).submit( function()
{
var images = $( "img.check" );
if( images.length > 0 )
{
$( "input[name=images]" ).attr( "value", $( images[getRandomInt( 0, images.length )] ).data( "id" ) );
return true;
}
else
{
alert( 'Kein Bild ausgewählt.' );
return false;
}
} );
$( 'form img' ).click( function()
{
$( this ).toggleClass( 'check' );
} );
} );
</script>
</head>
<body>
<?php
$random = [
'Key1' => 'https://static.pexels.com/photos/4952/sky-beach-vacation-summer.jpeg',
'Key2' => 'https://static.pexels.com/photos/1852/dawn-landscape-mountains-nature.jpg',
'Key3' => 'https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg',
'Key4' => 'https://static.pexels.com/photos/12567/photo-1444703686981-a3abbc4d4fe3.jpeg',
'Key5' => 'https://static.pexels.com/photos/2757/books-magazines-building-school.jpg',
];
?>
<form method="post">
<input type="hidden" name="images">
<?php
foreach ($random as $key => $val)
{
echo '<h1>$key</h1>';
echo '<img src="'.$val.'" width="100px" height="100px" data-id="'.$key.'"">';
}
?>
<button type="submit" name="submit" class="btn btn-default">Submit</button>
</form>
<?php
if (isset($_POST['images']))
{
echo '<img src="' . $random[$_POST['images']] . '" />';
}
?>
You can use ajax that returns your associate array into a json format.
example
use jquery for this
$.post('yourphpscript.php', function(data) {
data // this is your associated array
}, 'JSON');
Use code like this if you just want to refresh your div
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Generate random number</title>
</head>
<body>
<div id="div1" style="border:solid 1px red; width: 100px;"></div>
<br /><br />
<div id="div2" style="border:solid 1px green; width: 100px;">
<button type="button" id="btn_click" /> click me!</button>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$("#btn_click").click(function(){
$('#div1').html(10 + Math.floor(Math.random()*91));
});
$("#btn_click").trigger("click");
</script>
</body>
</html>
Use AJAX with POST method for send data and image using mimeType: "multipart/form-data"
AJAX script code:
<script>
$.ajax({
type:"POST",
url:"ajax_filename.php",
data:data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success:function(result)
{
$('#image_div').attr('src','image_file_path.png'); // Change the image to submited image.
}
});
</script>
ajax is used for prevent page loading ,so you need to change your form submit function a little bit and input hidden no need if you use ajax
$( document ).ready( function()
{
$( "form" ).submit( function()
{
var images = $( "img.check" );
if( images.length > 0 )
{
images = $(images[getRandomInt( 0, images.length)]).data( "id" );
$.ajax({
type : "POST", //set method
url : "", //link to current page (can go other link if u want)
data: "images=" + images, // post data
success : function(r){
$('body').html(r); // replace current page with new data
}
})
return true;
}
else
{
alert( 'Kein Bild ausgewählt.' );
return false;
}
} );
$( 'form img' ).click( function()
{
$( this ).toggleClass( 'check' );
} );
});
input type hidden will no need longer if you used like above ....
I know this may be ridiculously easy for a javascript programmer, but I want to change "incorrect answer" and "correct answer" for an image located in my folder assets/img/avatar/incorrect.png any idea how i may do this? I've tried to google, but every option i've tried doesn't seem to work?
<script type="text/javascript">
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
if(!$("#myForm").validationEngine('validate'))
{
return false;
}
var id = $('input[type=radio][name=is_correct]:checked').attr('id');
var formData = $("#myForm").serializeArray();
$.ajax
({
type: "POST",
url: "<?php echo base_url()?>user/checkanswer/<?php echo $questionrecord[0]['id']?>/"+id,
cache: false,
data : formData,
async: false,
success: function(data)
{
if( data == '0' ){
$("#msgbox_answer").fadeTo(200,0.1,function() { //start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('Incorrect Answer').addClass('messageboxerror').fadeTo(900,1);
document["pic1"].src = "assets/img/avatars/incorrect.png";
});
}else if( data == '1' ){
$("#msgbox_answer").fadeTo(200,0.1,function() { //start fading the messagebox
//add message and change the class of the box and start fading
$(this).html(' Correct Answer').addClass('messageboxok').fadeTo(900,1);
});
}
$( "#remove_submit" ).remove();
$("#view_correct_answer").html('<span class="whitetext">View correct answer</span>');
}
});
});
$(".hidetext").click(function () {
$(".text_class").toggle("slow")
});
$('.carousel').carousel({
interval: 4000 //changes the speed
})
</script>
I have a jQuery dialog button, and inside it I parse all the inputs.
I want to send these parsed values to a php file, but when I click "OK" nothing happens -at all-, without any errors.
Here's my code:
$("#dialog").dialog({
autoOpen: false,
width: 'auto',
buttons: [ {
text: "Ok",
click: function() {
var functionName = $("#txtFunctionName").val();
var cassName = $("#txtClassName").val();
var classDesc = $("#txtClassDesc").val();
var input = $("#txtInput").val();
var output = $("#txtOutput").val();
/* SEND THE DATA TO addFunc.php */
var $dataStr = {'name': functionName,
'input': input,
'output': output,
'class': cassName,
'desc': classDesc};
$.post('../php/addFunc.php',
$data,
function(response){
alert("test");
}
);
$( this ).dialog( "close" );
}
}]
});
And the addFunc.php contains just a sample echo to verify correctness, but it doesn't alert anything, meaning it didn't work:
<?php
echo "Welcome";
?>
Change $dataStr to dataStr and add the correct var (dataStr no $data) in the post function.
Try this:
$("#dialog").dialog({
autoOpen: false,
width: 'auto',
buttons: [ {
text: "Ok",
click: function() {
var functionName = $("#txtFunctionName").val();
var cassName = $("#txtClassName").val();
var classDesc = $("#txtClassDesc").val();
var input = $("#txtInput").val();
var output = $("#txtOutput").val();
/* SEND THE DATA TO addFunc.php */
var dataStr = {'name': functionName,
'input': input,
'output': output,
'class': cassName,
'desc': classDesc};
$.post('../php/addFunc.php',
dataStr,
function(response){
alert("test");
}
);
$( this ).dialog( "close" );
}
}]
});
I'm using PHP, jQuery, AJAX, Smarty for my website. I'm having following line of code from smarty template. I wan to call the jQuery AJAX function on the onclick of that hyperlink but I'm not able to call it. Can you help me in giving call to the jQuery AJAX function?
Following is my code.
Code from Smarty template:
<a class="edit_user_transaction_status" href="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</a>
jQuery AJAX function is as follows:
$(".edit_user_transaction_status").click(function(e) {
e.preventDefault();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('href');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
If I try to print the alert at the beginning of function it's not getting printed. Can you help me in achieving this? Thanks in advance.
Corrected Code:
$(".edit_user_transaction_status").click(function(e) {
e.preventDefault();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('href');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
Note: Remove }); from the last line.