Ajax serialize form - PHP can't get individual input data - javascript

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.

Related

How to add reset button in Dialog box

I want to add a RESET button in dialog box whose work is to delete the Hidden field value from database and close the dialog box:
Here is my code
<script type="text/javascript">
function OpenPopup() {
var data = document.getElementById('<%=hflinkData.ClientID %>').value;
var keyval = data.split(';');
var table = '<table>';
for (var i = 0; i < keyval.length; i++) {
var arr = keyval[i].split('=');
table += "<tr><td>" + arr[0] + "</td><td>" + arr[1] + "</td></tr>";
}
table += '</table>';
$('#WindowBody').html(table);
$('#dialogWindow').dialog({
autoOpen: false,
modal: true,
height: 200,
width: 500,
title: "Device Info",
resizable: false,
draggable: false,
position: ['center', 'center'],
closeOnEscape: true,
open: function (event, ui)
{
$('.ui-dialog').css('top', 100);
},
create: function (event) { $(event.target).parent().css('position', 'fixed'); }
});
$('#dialogWindow').dialog('open');
return false;
}
`
and this my HTML code
<div id="dialogWindow" >
<label></label>
<div id="WindowBody">
</div>
</div>`
Where "hflinkData" is the name of hidden field
Kindly use ajax post to achieve your requirement. Use normal html input button inside dialog. Kindly see the below code snippet.
<div id="dialogWindow" >
<label></label>
<div id="WindowBody">
</div>
<input type="button" onclick="deleteValue();" value="RESET" />
</div>
And send the AJAX post to code behind in 'deleteValue' method. Please see the below javascript code snippet.
<script type="text/javascript">
function deleteValue() {
$.ajax({
url: "Default.aspx/DeleteData",
type: "POST",
data: {value:$("#hflinkData").val()},
error: function (data) {
alert(data);
},
success: function (result) {
alert(result);
}
})
}
</script>
And write the required code for delete operation in code behind.
[WebMethod]
public static void DeleteData(string value)
{
//get the hidden value from parameter
//code for delete corresponding value from data base
}
Regards,
Sunil Prabakar C

jQuery post to PHP not working without any errors

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" );
}
}]
});

getting "null" while trying to get the value of textbox that is inside a jquery dialog

I am trying to get the value of a textbox that I have created inside a jquery dialog using its ID and I am receiving null. I think it is some simple mistake, but I am not able to find it. Could you please have a look at the below code and tell me if I am doing anything wrong there.
$(document).ready(function() {
var name = $("#ip"), email = $("#stnid"), allFields = $(
[]).add(name).add(email);
$("#displayOrderDetailsDiv").on('click','.shippedOrder',function() {
var shipmentKey = $(this).closest('tr').find('td:first').text();
$( "#printLabelDialog" ).dialog( {
autoOpen: false,
height : "auto",
width : "auto",
modal: true,
buttons: [ {
text: "Print",
click: function() {
var ajax_load = "<img class='loading' src='loading.gif' alt='loading...' style='width: 20px; height: 20px; top: 50%; left: 50%; position:absolute;' />";
$( this ).html(ajax_load);
var ip = $("#ipAddr").val();
var stnid = $("#stnid").val();
$.ajax({
url : 'printLabelTrackingNumber.jsp',
type : 'POST',
data : {
ipAddr : ip,
stationId : stnid
},
success : function(data) {
$("#printLabelDialog").html(data);
},
error : function(err) {
alert(err.responseText);
}
});
}
} ]
});
$("#printLabelDialog").html("<form><fieldset><label for=\"ip\">Printer IP</label> <input type=\"text\" name=\"ip\" id=\"ipAddr\" class=\"text ui-widget-content ui-corner-all\"> <labelfor=\"stnid\">Station ID:</label> <input type=\"text\" name=\"stnid\" id=\"stnid\" value=\"\" class=\"text ui-widget-content ui-corner-all\"></fieldset></form>");
$( "#printLabelDialog" ).dialog( "open" );
});
});
I am trying to get the value of the textbox with id ipAddr using the line var ip = $("#ipAddr").val(); which is returning null.
Try:
var e = document.getElementById("ipAddr");
var ip = e.value;
This should get the value of ipAddr, if, of course, there is already something inside of ipAddr. otherwise this will still return null.
I figured out the problem. I set the value of #printLabelDialog to the gif image using $( this ).html(ajax_load); before I get the value of the textbox in that div and hence I was getting the error.
Thanks all for your help.

Not working plugins with ajax

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" />

Retrieving AJAX value from a different Javascript function

In this simplified example of a larger web app, consider a simplistic registration form with fields: username, firstname, lastname and a Register button type="button".
<form action="" method="post" id="cns_form">
<table id="companyTable"><tr>
<td width="200">
First name*:<br />
<input type="text" id="first_name" name="first_name">
</td>
<td width="200">
Last name*:<br />
<input type="text" id="last_name" name="last_name">
</td>
</tr></table>
<input type="button" value="Register" id="register" >
</form>
<div id="alert" title="Alert"></div>
When the username field is completed, jQuery fires an ajax search of a database to see if that username already exists. This same search is also triggered when one clicks Register (for reasons removed from this simplified example).
PROBLEM: Everything works great when leaving the username field. However, after clicking Register, I don't know how to retrieve the result of the AJAX search and stop the form from submitting if the username already exists. I've tried all kinds of different things, but have returned the code to this state so it is easiest for the reader to assist.
For example, I tried integrating the suggested solution from this question, but I was unsuccessful applying it to my situation... I tried setting async:false inside the ajax function... I also tried calling the checkUsername(uname) from inside the checkForm function, but that didn't work either. A little help?
jQuery document.ready:
$(function(){
$('#username').blur(function() {
var uname = $.trim($(this).val());
checkUsername(uname);
}); //END BLUR username
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkUsername(uname);
checkForm();
});
}); //END document.ready
AJAX Call:
function checkUsername(uname) {
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
}
checkForm Function:
function checkForm() {
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
}
One both rejoices and weeps when answering his own question, but here goes. The solution was to send the checkUsername() function as an input param to the checkForm() function, and to make the checkUserName() function return a value that we could check inside checkForm().
Therefore, we must modify the $('#register').click function thusly:
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkForm(checkUsername(uname)); //<===========================
});
THEN the checkUsername() function, thus:
function checkUsername(uname) {
var returnVal = 0; //<=================================
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
returnVal = 0; //<============================
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
return returnVal; //<==============================
}
AND the checkform() function thus:
function checkForm(exists) { //<============================
alert('sub checkForm(). value of exists: ' + exists);
if (exists==9) { //<================================
$( '#alert' ).html( 'That username is already in use' + existing +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
}else{ //<==========================================
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
} //<===================================================
}
Thanks and kudos to Felix Kling for this helpful post.
Might put return false in the function call in the HTML form markup.
<form>
<bunchOfElements />
<button onclick="checkUserName(); return false">Check Name </button>
</form>
Also, you might bind the function to the button's click event using
$(document).ready(function(){
$("#buttonID").bind('click', function(){
//do your thing
checkForm();
});
});
Put a return false at the end of your #register button click function, right below checkForm(). The button is continuing to fire the form submit. when you have that handled by your javascript function.

Categories

Resources