jQuery post to PHP not working without any errors - javascript

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

Related

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

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.

Taking a String and Inserting Only Numbers from that String

I have a dialog box that pops up after hitting an Add button. There are two inputs, one being a dropdown. The information in the dropdown for example looks like this, 1 - Company A, 2 - Company B, etc. It is a value made up of 2 concatenated values. I need MR_ID, not MR_Name. However, whenever I submit this and insert into the database, I only want those first few numbers, not the company name or anything like that. How can I do this? Would using str_replace or preg_replace work? And if so, how and where would I put it in my code?
Query that populates dropdown list inside dialog box
$sql1 = "WITH cte AS (
SELECT DISTINCT CONCAT(CAST(Stage_Rebate_Index.MR_ID AS INT),' - ', Stage_Rebate_Master.MR_Name) AS MR_ID
, Stage_Rebate_Index.MR_ID AS sort_column
FROM Stage_Rebate_Index
LEFT JOIN Stage_Rebate_Master
ON Stage_Rebate_Master.MR_ID=Stage_Rebate_Index.MR_ID
)
SELECT MR_ID
FROM
cte
ORDER BY
sort_column;";
JavaScript for dialog box and adding information:
$( function() {
$("#insertButton").on('click', function(e){
e.preventDefault();
});
var dialog, form,
mr_id_dialog = $( "#mr_id_dialog" ),
supplier_id = $( "#supplier_id" ),
allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
//valid = valid && checkRegexp( mr_id_dialog, /^(0|[1-9][0-9]*)$/, "Please enter a valid MR ID" );
valid = valid && checkRegexp( supplier_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Supplier ID" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#index_table tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = value;
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}
});
$( "#index_table tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Supplier ID": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});
$( "#insertButton" ).button().on( "click", function() {
dialog.dialog({
position: ['center', 'top'],
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
Insert.php
<?php
$MR_ID = $_POST['MR_ID'];
$Supp_ID = $_POST['Supp_ID'];
$host="xxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxx";
$dbPass="xxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($MR_ID, $Supp_ID));
echo json_encode($result);
?>
in the java script just use a parse int
parseInt(string);
doing this with
var string = "2 - Company A"
var number = parseInt(string);
console.log(number);
give the output of 2
jsfiddle https://jsfiddle.net/esz5jnec/
if i understand your code correctly it would go in the switch
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = parseInt(value);
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}

Closing a dialog box if ajax sucess

I'm using dialog box for add new users to db , I want to close dialog box if validation pass and user successfully saved. please advice
$('.add_user_link a').each(function () {
var $link = $(this);
var $dialog = $('<div id="dialog"></div>')
.load($link.attr('href') + ' #content')
.dialog({
autoOpen: false,
title: $link.attr('title'),
});
$link.click(function () {
$dialog.dialog('open');
$('#add_user').submit(function () {
url = '/user/useradd/';
$.ajax({
type: "POST",
cache: false,
url: $('#add_user').attr('action'),
data: $('#add_user').serializeArray(),
success: function (data) {
var json_obj = $.parseJSON(data);
var result = json_obj['result'];
var lname = json_obj['lname'];
var email = json_obj['email'];
var fname = json_obj['fname'];
if (!result) {
$("#dialog").dialog('close');
}
else {
//
document.getElementById('email-error').innerHTML = email;
var fname_count = $("label[id*='errorfname']").length;
$('input[name=fname]').after('<label id="errorfname"></label>');
document.getElementById('errorfname').innerHTML = fname;
var lname_count = $("label[id*='errorlname']").length;
if (lname_count == 0) {
$('input[name=lname]').after('<label id="errorlname"></label>');
document.getElementById('errorlname').innerHTML = lname;
}
}
}
});
return false;
});
return false;
});
});
I'm getting this error
jquery-1.11.1.min.js:2 Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
Replace:
$("#dialog").dialog('close');
With
$dialog.dialog('close')
You've already set a variable for your dialog in the click function which should be in scope so you don't need to reselect it.
UPDATE:
Element IDs should be unique so you should make the dialog ID unique when adding it for a link if there are multiple links. Otherwise, you will select multiple dialog elements when you do this $('#dialog') when there are mulitiple links.
When you do this:
$dialog = $('<div id="dialog"></div>')
the ID value "dialog" should be something unique, like "dialog1", "dialog2", etc.

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.

How to call an AJAX function on anchor tag?

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.

Categories

Resources