Javascript function inside php, does not work - javascript

I have a webpage which displays rows from a database inside text boxes. I have made buttons one of which when clicked dynamically creates a row with input boxes. So this onClick function written with javascript to create these boxes is not being triggered. The error thrown out by the concole is addInput() not defined.
<?php
include('adodb/adodb.inc.php');
echo ' <h1>\n' .
' Revenue Management Solution\n' .
' </h1>\n';
echo ' <img alt = "mxpresso logo"\n' .
' src = "http://mxpresso.com/images/logo.png"\n' .
' style = "width : 171px; height : 108px;">\n\n';
echo ' <h2>\n' .
' 1. To See existing records\n' .
' </h2>\n';
$db = NewADOConnection( 'mysql' );
$db -> Connect( "127.0.0.1",
"vcc",
"abcd4",
"vcc" );
$sql = "SELECT * FROM rev";
$result = $db->Execute( $sql );
if ( $result === false )
die( "failed2" );
$records = array();
$count = $result -> RecordCount();
echo "Total Records Found :".$count."<br>";
if ( $count > 0 )
{
while ( !$result -> EOF )
{
$offerId = $result -> fields[ 0 ];
$affId = $result -> fields[ 1 ];
$status = $result -> fields[ 2 ];
$deduction = $result -> fields[ 3 ];
echo ' <form action = "updatecopy.php"\n' .
' method = "get"\n' .
' target = "_blank">\n' .
' <div id = "dynamicInput">\n' .
' <table id = "dataTable"\n' .
' class = "form">\n' .
' <tbody>\n' .
' <tr>\n' .
' <td>\n' .
' <input checked = "checked"\n' .
' required = "required"\n' .
' name = "chk[]"\n' .
' type = "checkbox">\n' .
' </td>\n\n';
echo ' <td>\n' .
' <h4>\n' .
' OfferID\n' .
' </h4>\n\n';
echo ' <input name = "update_for_offerid"\n' .
' type = "text"\n' .
' value = ' .
$offerId .
'>\n' .
' </td>\n\n';
echo ' <td>\n' .
' <h4>\n' .
' AffId\n' .
' </h4>\n\n';
echo ' <input name = "update_for_affid"\n' .
' type = "text"\n' .
' value = ' .
$affId .
'>\n' .
' </td>\n\n';
echo ' <td>\n' .
' <h4>\n' .
' deduction :\n' .
' </h4>\n\n';
echo ' <input name = "deduct"\n' .
' type = "text"
' value = ' .
$deduction .
'>\n' .
' </td>\n\n';
echo ' <td>\n' .
' <h4>\n' .
' Status\n' .
' </h4>\n\n';
echo ' <input name = "status"\n' .
' type = "text" ' .
' value = ' .
$status .
'>\n' .
' </td>\n' .
' </tr>\n' .
' </tbody>\n' .
' </table>\n\n';
echo ' <input type = "submit"\n' .
' value = "Update Entry">\n' .
' </div>\n' .
' </form>\n\n';
$rec = array( "offerId" => $offerId,
"affiliate_id" => $affId,
"status" => $status,
"deduction" => $deduction );
array_push( $records,
$rec );
$result->MoveNext();
}
}
echo ' <input type = "button"\n' .
' onClick = "addInput(\'dynamicInput\')"\n' .
' value = "Add another text input">\n\n';
echo ' <script language = "Javascript"\n' .
' type = "javascript">\n' .
' var counter = 1;\n' .
' var limit = 3;\n\n';
echo ' function addInput( divName )\n' .
' {\n' .
' if ( counter == limit )\n' .
' {\n' .
' alert( "You have reached the limit of adding " + counter + " inputs" );\n' .
' }\n' .
' else\n' .
' {\n' .
' var newtable = document.createElement( "dataTable1" );\n' .
' var td1 = document.createElement(\'td\');\n' .
' var td2 = document.createElement(\'td\');\n' .
' var td3 = document.createElement(\'td\');\n'
' var tr = document.createElement( \'tr\' );\n\n';
echo ' td1.innerHTML = \'<h4>Entry</h4>\' + \'<br><input name = "myI" type = "text">\';\n\n';
echo ' td2.innerHTML = \'<h4>Entry</h4>\' + \'<br><input name = "myI" type = "text">\';\n\n';
echo ' td3.innerHTML = \'<h4>Entry</h4> \' + \'<br><input name = "myIn" type = "text">\';\n\n';
echo ' tr.appendChild( td1 );\n' .
' tr.appendChild( td2 );\n' .
' tr.appendChild( td3 );\n\n';
echo ' newtable.appendChild( tr );\n\n';
echo ' document.getElementById( divName ).appendChild( newtable );\n\n';
echo ' counter++;\n' .
' }\n' .
' </script>\n';
?>

I'm too noob to comment, and while this isn't a complete answer, I believe it will send you along your way well enough. If you were to get this page delivered to you in a browser, then "inspect" using the debug tool of your favorite browser, you would likely find that the javascript isn't registered with the browser as a "script" source, but rather just text inside the element that's not displaying cause DOM rules. This of course makes it non-executable, as you would be able to tell since the event isn't firing. addInput() not defined since it's inside a script that's not registered.
This is kind of tricky layering it like this. FWIW, my solution to this kind of thing was to declare a JS script in the caller -> that had a function that created a new page (using JS of course), >that .append 'ed all the elements to the defined script, the "source" of the script being a separate JS file. This also allows me to use the IDE to maintain the script in a separate file.
There are several ways to "post" the script as an element, but it needs to be posted to DOM.

You are missing a >:
echo '<html

javascript is case sensive, it should be onclick not onClick.
I din't really got deeper in your code, but if this doesn't solve it then tell me

Related

How to make it store ecryption in database and decryption for user

I have main function class for encrypted and decrypted password. But here, I want to call the function in my php (now is the other php).So, the database should have crypted password but not yet. How can i get it? Its supposedly to be crypted in database and encrypted for user see it. Thank you.
Funtion that I have is :
EHORS_CRYPT_VAR - for encrypted password
EHORS_DECRYPT_VAR - for decrypted password
PHP
function addEmployee() {
global $ehorsObj;
$employeeID = (isset($_POST['employeeID']) ? $_POST['employeeID'] : '');
$employeeName = (isset($_POST['employeeName']) ? $_POST['employeeName'] : '');
$departmentID = (isset($_POST['departmentID']) ? $_POST['departmentID'] : '');
$positionID = (isset($_POST['positionID']) ? $_POST['positionID'] : '');
$languageID = (isset($_POST['languageID']) ? $_POST['languageID'] : '');
$userName = (isset($_POST['userName']) ? $_POST['userName'] : '');
$passWord = (isset($_POST['passWord']) ? $_POST['passWord'] : '');
$srAuthorized = (isset($_POST['srAuthorized']) ? $_POST['srAuthorized'] : '');
$srMultiDepAuthorized = (isset($_POST['srMultiDepAuthorized']) ? $_POST['srMultiDepAuthorized'] : '');
$headOfDepartment = (isset($_POST['headOfDepartment']) ? $_POST['headOfDepartment'] : '');
$employeeID = $_SESSION['employeeID'];
$propertyID = $_SESSION['propertyID'];
$Crypted = $ehorsObj->EHORS_CRYPT_VAR($passWord);
$DeCrypted = $ehorsObj->EHORS_DECRYPT_VAR($Crypted);
/* check unique */
$sqlCount = "SELECT COUNT(*) AS TOTAL FROM tblHrsEmployee
WHERE employeeID != '" . $employeeID . "'
AND employeeName = '" . $employeeName . "'
AND departmentID = '" . $departmentID . "'
AND positionID = '" . $positionID . "'
AND languageID = '" . $languageID . "'
AND userName = '" . $userName . "'
AND passWord = '" . $passWord . "'
AND srAuthorized = '" . $srAuthorized . "'
AND srMultiDepAuthorized = '" . $srMultiDepAuthorized . "'
AND headOfDepartment = '". $headOfDepartment ."'";
$GetResult = $ehorsObj->FetchData($sqlCount, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
while ($row = $GetResult->fetch()){
$total = $row ['TOTAL'];
}
if ($total == 0){
$employeeID = $ehorsObj->EHORS_PK("tblHrsEmployee");
$sqlAdd = "INSERT INTO tblHrsEmployee
SET employeeID = '" . $employeeID . "',
employeeName = '" . $employeeName . "',
departmentID = '" . $departmentID . "',
positionID = '" . $positionID . "',
languageID = '" . $languageID . "',
userName = '" . $userName . "',
passWord = '" . $DeCrypted . "',
srAuthorized = '" . $srAuthorized . "',
srMultiDepAuthorized = '" . $srMultiDepAuthorized . "',
headOfDepartment = '". $headOfDepartment ."',
propertyID = '" . $propertyID . "',
active = 'y',
dateTimeEmployee = NOW() ";
$ehorsObj->ExecuteData($sqlAdd, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
}else{
echo "Record already exist";
}}
JavaScript
{ field: "passWord", hidden:true, title:"Password", editor: getPassword},
function getPassword(container, options) {
$('<input data-text-field="' + options.field + '" ' +
'class="k-input k-textbox" ' +
'type="password" ' +
'data-value-field="' + options.field + '" ' +
'data-bind="value:' + options.field + '"/>')
.appendTo(container)
}
try somehing like this
Php:
global $ehorsObj;
$encrypted_pass = "";
$decrypted_pass = "";
$sql = "SELECT passWord FROM tblHrsEmployee WHERE employeeID = '" . $employeeID . "' ";
$data = $ehorsObj->ExecuteData($sql, $ehorsObj->DEFAULT_PDO_CONNECTIONS)->fetchAll();
foreach ($data as $row) {
$encrypted_pass = $row['passWord']."<br />\n";
}
$decrypted_pass = $ehorsObj->EHORS_DECRYPT_VAR($encrypted_pass);
html:
<input type="hidden" class="decrypted_pass" name="decrypted_pass" value="<?=$decrypted_pass?>" >
javascript:
$( document ).ready(function() {
console.log($(".decrypted_pass").val());
//will show decrypted pass at console.log
});

validate textfield contents in wordpress simple job board plugin

how to validate text field content in job application form ?? to make sure the content holding only characters from A-Z and a-z, to avoid SQL injection and other bad string such as |_"'$#!;...etc ???
Any good plugin should already have text sanitization. If you want to sanitize the text yourself via custom php code, you may use built-in PHP of WordPress functions for this job:
http://php.net/manual/en/filter.filters.sanitize.php
or
https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data
For example for a text-field input we can filter contents like this:
$title = sanitize_text_field( $_POST['title'] );
update_post_meta( $post->ID, 'title', $title );
i customize the sjb(simple job board) plugin via add content validation with specific pattern for any text field that generate by plugin in application form, which allow only characters [A-Z, a-z].
just replace this file
simple-job-board/templates/single-jobpost/job-application.php
by this code:
<?php
/**
* Display the job application form.
*
* Override this template by copying it to yourtheme/simple_job_board/single-jobpost/job-application.php
*
* #author PressTigers
* #package Simple_Job_Board
* #subpackage Simple_Job_Board/Templates
* #version 1.0.0
* #since 2.1.0
* #since 2.2.2 Added more #hooks in application form.
* #since 2.3.0 Added "sjb_job_application_template" filter & "sjb_job_application_form_fields" filter.
*/
ob_start();
global $post;
/**
* Fires on job detail page before displaying job application section.
*
* #since 2.1.0
*/
do_action('sjb_job_application_before');
?>
<!-- Start Job Application Form
================================================== -->
<form class="jobpost-form" id="sjb-application-form" name="c-assignments-form" enctype="multipart/form-data">
<h3><?php echo apply_filters('sjb_job_application_form_title', esc_html__('Apply Online', 'simple-job-board')); ?></h3>
<div class="row">
<div class="col-md-12">
<?php
/**
* Fires on job detail page at start of job application form.
*
* #since 2.3.0
*/
do_action('sjb_job_application_form_fields_start');
$keys = get_post_custom_keys(get_the_ID());
if (NULL != $keys):
foreach ($keys as $key):
if (substr($key, 0, 7) == 'jobapp_'):
$val = get_post_meta(get_the_ID(), $key, TRUE);
$val = unserialize($val);
$is_required = isset($val['optional']) ? "checked" === $val['optional'] ? 'required="required"' : "" : 'required="required"';
$required_class = isset($val['optional']) ? "checked" === $val['optional'] ? "sjb-required" : "sjb-not-required" : "sjb-required";
$required_field_asterisk = isset($val['optional']) ? "checked" === $val['optional'] ? '<span class="required">*</span>' : "" : '<span id="sjb-required">*</span>';
$id = preg_replace('/[^\p{L}\p{N}\_]/u', '_', $key);
$name = preg_replace('/[^\p{L}\p{N}\_]/u', '_', $key);
$label = isset($val['label']) ? $val['label'] : ucwords(str_replace('_', ' ', substr($key, 7)));
// Field Type Meta
$field_type_meta = array(
'id' => $id,
'name' => $name,
'label' => $label,
'type' => $val['type'],
'is_required' => $is_required,
'required_class' => $required_class,
'required_field_asterisk' => $required_field_asterisk,
);
/**
* Fires on job detail page at start of job application form.
*
* #since 2.3.0
*/
do_action('sjb_job_application_form_fields', $field_type_meta);
//. '<input type="text" name="' . $name . '" class="form-control ' . $required_class . '" id="' . $id . '" ' . $is_required . ' >'
switch ($val['type']) {
case 'text':
echo '<div class="form-group">'
. '<label for="' . $key . '">' . $label . $required_field_asterisk . '</label>'
. '<input type="text" name="' . $name . '" class="form-control sjb-text ' . $required_class . '" id="' . $id . '" ' . $is_required . '><span class="sjb-invalid-text validity-note">' . esc_html__('A valid text is required.', 'simple-job-board') . '</span>'
. '</div>';
break;
case 'text_area':
echo '<div class="form-group">'
. '<label for="' . $key . '">' . $label . $required_field_asterisk . '</label>'
. '<textarea name="' . $name . '" class="form-control ' . $required_class . '" id="' . $id . '" ' . $is_required . '></textarea>'
. '</div>';
break;
case 'email':
echo '<div class="form-group">'
. '<label for="' . $key . '">' . $label . $required_field_asterisk . '</label>'
. '<input type="email" name="' . $name . '" class="form-control sjb-email-address ' . $required_class . '" id="' . $id . '" ' . $is_required . '><span class="sjb-invalid-email validity-note">' . esc_html__('A valid email address is required.', 'simple-job-board') . '</span>'
. '</div>';
break;
case 'phone':
echo '<div class="form-group">'
. '<label for="' . $key . '">' . $label . $required_field_asterisk . '</label>'
. '<input type="tel" name="' . $name . '" class="form-control sjb-phone-number ' . $required_class . '" id="' . $id . '" ' . $is_required . '><span class="sjb-invalid-phone validity-note" id="' . $id . '-invalid-phone">' . esc_html__('A valid phone number is required.', 'simple-job-board') . ' </span>'
. '</div>';
break;
case 'date':
echo '<div class="form-group">'
. '<label for="' . $key . '">' . $label . $required_field_asterisk . '</label>'
. '<input type="text" name="' . $name . '" class="form-control sjb-datepicker ' . $required_class . '" id="' . $id . '" ' . $is_required . '>'
. '</div>';
break;
case 'radio':
if ($val['options'] != '') {
echo '<div class="form-group">'
. '<label class="sjb-label-control" for="' . $key . '">' . $label . $required_field_asterisk . '</label>'
. '<div id="' . $key . '" >';
$options = explode(',', $val['options']);
$i = 0;
foreach ($options as $option) {
echo '<label class="small"><input type="radio" name="' . $name . '" class=" ' . $required_class . '" id="' . $id . '" value="' . $option . '" ' . sjb_is_checked( $i ) . ' ' . $is_required . '>' . $option . ' </label> ';
$i++;
}
echo '</div></div>';
}
break;
case 'dropdown':
if ($val['options'] != '') {
echo '<div class="form-group">'
. '<label for="' . $key . '">' . $label . $required_field_asterisk . '</label>'
. '<div id="' . $key . '" >'
. '<select class="form-control" name="' . $name . '" id="' . $id . '" ' . $is_required . '>';
$options = explode(',', $val['options']);
foreach ($options as $option) {
echo '<option class="' . $required_class . '" value="' . $option . '" >' . $option . ' </option>';
}
echo '</select></div></div>';
}
break;
case 'checkbox' :
if ($val['options'] != '') {
echo '<div class="form-group ">'
. '<label for="' . $key . '">' . $label . $required_field_asterisk . '</label>'
. '<div id="' . $key . '">';
$options = explode(',', $val['options']);
$i = 0;
foreach ($options as $option) {
echo '<label class="small"><input type="checkbox" name="' . $name . '[]" class="' . $required_class . '" id="' . $id . '" value="' . $option . '" ' . $i . ' ' . $is_required . '>' . $option . ' </label>';
$i++;
}
echo '</div></div>';
}
break;
}
endif;
endforeach;
endif;
/**
* Modify the output of file upload button.
*
* #since 2.2.0
*
* #param string $sjb_attach_resume Attach resume button.
*/
$sjb_attach_resume = '<div class="form-group">'
. '<label for="applicant_resume">' . apply_filters('sjb_resume_label', __('Attach Resume', 'simple-job-board')) . '<span class="sjb-required required">*</span></label>'
. '<input type="file" name="applicant_resume" id="applicant-resume" class="sjb-attachment form-control "' . apply_filters('sjb_resume_required', 'required="required"') . '>'
. '<span class="sjb-invalid-attachment validity-note" id="file-error-message"></span>'
. '</div>';
echo apply_filters('sjb_attach_resume', $sjb_attach_resume);
/**
* Fires on job detail page before job submit button.
*
* #since 2.2.0
*/
do_action('sjb_job_application_form_fields_end');
?>
<input type="hidden" name="job_id" value="<?php the_ID(); ?>" >
<input type="hidden" name="action" value="process_applicant_form" >
<input type="hidden" name="wp_nonce" value="<?php echo wp_create_nonce('jobpost_security_nonce') ?>" >
<div class="form-group" id="sjb-form-padding-button">
<button class="btn btn-primary app-submit"><?php esc_html_e('Submit', 'simple-job-board'); ?></button>
</div>
</div>
</div>
</form>
<div class="clearfix"></div>
<?php
/**
* Fires on job detail page after displaying job application form.
*
* #since 2.1.0
*/
do_action('sjb_job_application_end');
?>
<div id="jobpost_form_status"></div>
<!-- ==================================================
End Job Application Form -->
<?php
/**
* Fires on job detail page after displaying job application section.
*
* #since 2.1.0
*/
do_action('sjb_job_application_after');
$html_job_application = ob_get_clean();
/**
* Modify the Job Applicatin Form Template.
*
* #since 2.3.0
*
* #param html $html_job_application Job Application Form HTML.
*/
echo apply_filters('sjb_job_application_template', $html_job_application);
and this file simple-job-board/public/js/simple-job-board-public.js
with this code
/**
* Simple Job Board Core Front-end JS File - V 1.4.0
*
* #author PressTigers <support#presstigers.com>, 2016
*
* Actions List
* - Job Application Submission Callbacks
* - Date Picker Initialization
* - Validate Email
* - Initialize TelInput Plugin
* - Validate Phone Number
* - Allowable Uploaded File's Extensions
* - Validate Required Inputs ( Attachment, Phone & Email )
* - Checkbox Group Required Attribute Callbacks
* - Custom Styling of File Upload Button
*/
(function ($) {
'use strict';
$(document).ready(function () {
var jobpost_submit_button = $('.app-submit');
$(".jobpost-form").on("submit", function (event) {
var jobpost_form_status = $('#jobpost_form_status');
var datastring = new FormData(document.getElementById("sjb-application-form"));
/**
* Application Form Submit -> Validate Email & Phone & text
* #since 2.2.0
*/
var is_valid_email = sjb_is_valid_input(event, "email", "sjb-email-address");
var is_valid_phone = sjb_is_valid_input(event, "phone", "sjb-phone-number");
var is_valid_text = sjb_is_valid_input(event, "text", "sjb-text");
var is_attachment = sjb_is_attachment(event);
/* Stop Form Submission on Invalid Phone, Email & File Attachement Plus text*/
if ( !is_valid_email || !is_valid_phone || !is_attachment || !is_valid_text) {
return false;
}
$.ajax({
url: application_form.ajaxurl,
type: 'POST',
dataType: 'json',
data: datastring,
async: false,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
jobpost_form_status.html('Submitting.....');
jobpost_submit_button.attr('disabled', 'diabled');
},
success: function ( response ) {
if ( response['success'] == true ) {
$('.jobpost-form').slideUp();
/* Translation Ready String Through Script Locaization */
jobpost_form_status.html(response['success_alert']);
}
if ( response['success'] == false ) {
/* Translation Ready String Through Script Locaization */
jobpost_form_status.html( response['error'] + ' ' + application_form.jquery_alerts['application_not_submitted'] + '</div>' );
jobpost_submit_button.removeAttr( 'disabled' );
}
}
});
return false;
});
/* Date Picker */
$('.sjb-datepicker').datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true
});
/**
* Application Form -> On Input Email Validation
*
* #since 2.2.0
*/
$('.sjb-email-address').on('input', function () {
var input = $(this);
//alert("emaiiiil");
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
var error_element = $("span", $(this).parent());
if (is_email) {
input.removeClass("invalid").addClass("valid");
error_element.hide();
} else {
input.removeClass("valid").addClass("invalid");
}
});
/**
* Application Form -> On Input text Validation
*
* #since 2.2.0
*/
$('.sjb-text').on('input', function () {
var input = $(this);
// var re = /^[a-zA-Z.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z]+(?:\.[a-zA-Z]+)*$/;
var re = /^[a-zA-Z0-9]*$/;
var is_text = re.test(input.val());
var error_element = $("span", $(this).parent());
//error_element.show();
if (is_text) {
input.removeClass("invalid").addClass("valid");
error_element.hide();
} else {
input.removeClass("valid").addClass("invalid");
}
});
/**
* Initialize TelInput Plugin
*
* #since 2.2.0
*/
if ($('.sjb-phone-number').length) {
var telInput_id = $('.sjb-phone-number').map(function () {
return this.id;
}).get();
for (var input_ID in telInput_id) {
var telInput = $('#' + telInput_id[input_ID]);
telInput.intlTelInput({
initialCountry: "auto",
geoIpLookup: function (callback) {
$.get('https://ipinfo.io', function () {
}, "jsonp").always(function (resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
callback(countryCode);
});
},
});
}
}
/**
* Application Form -> Phone Number Validation
*
* #since 2.2.0
*/
$('.sjb-phone-number').on('input', function () {
var telInput = $(this);
var telInput_id = $(this).attr('id');
var error_element = $("#" + telInput_id + "-invalid-phone");
error_element.hide();
// Validate Phone Number
if ($.trim(telInput.val())) {
if (telInput.intlTelInput("isValidNumber")) {
telInput.removeClass("invalid").addClass("valid");
error_element.hide();
} else {
telInput.removeClass("valid").addClass("invalid");
}
}
});
/**
* Check for Allowable Extensions of Uploaded File
*
* #since 2.3.0
*/
$('.sjb-attachment').on('change', function () {
var input = $(this);
var file = $("#" + $(this).attr("id"));
var error_element = file.parent().next("span");
error_element.text('');
error_element.hide();
// Validate on File Attachment
if ( 0 != file.get(0).files.length ) {
/**
* Uploded File Extensions Checks
* Get Uploded File Ext
*/
var file_ext = file.val().split('.').pop().toLowerCase();
// All Allowed File Extensions
var allowed_file_exts = application_form.allowed_extensions;
// Settings File Extensions && Getting value From Script Localization
var settings_file_exts = application_form.setting_extensions;
var selected_file_exts = (('yes' === application_form.all_extensions_check) || null == settings_file_exts) ? allowed_file_exts : settings_file_exts;
// File Extension Validation
if ($.inArray(file_ext, selected_file_exts) > -1) {
jobpost_submit_button.attr( 'disabled', false );
input.removeClass("invalid").addClass("valid");
} else {
/* Translation Ready String Through Script Locaization */
error_element.text(application_form.jquery_alerts['invalid_extension']);
error_element.show();
input.removeClass("valid").addClass("invalid");
}
}
});
/**
* Stop Form Submission -> On Required Attachments
*
* #since 2.3.0
*/
function sjb_is_attachment( event ) {
var error_free = true;
$(".sjb-attachment").each(function () {
var element = $("#" + $(this).attr("id"));
var valid = element.hasClass("valid");
var is_required_class = element.hasClass("sjb-not-required");
// Set Error Indicator on Invalid Attachment
if (!valid) {
if (!(is_required_class && 0 === element.get(0).files.length)) {
error_free = false;
}
}
// Stop Form Submission
if (!error_free) {
event.preventDefault();
}
});
return error_free;
}
/**
* Stop Form Submission -> On Invalid Email/Phone/text
*
* #since 2.2.0
*/
function sjb_is_valid_input(event, input_type, input_class) {
var jobpost_form_inputs = $("." + input_class).serializeArray();
var error_free = true;
for (var i in jobpost_form_inputs) {
var element = $("#" + jobpost_form_inputs[i]['name']);
var valid = element.hasClass("valid");
var is_required_class = element.hasClass("sjb-not-required");
if (!(is_required_class && "" === jobpost_form_inputs[i]['value'])) {
if ("email" === input_type) {
var error_element = $("span", element.parent());
} else if ("phone" === input_type) {
var error_element = $("#" + jobpost_form_inputs[i]['name'] + "-invalid-phone");
}else if ("text" === input_type) {
var error_element = $("span", element.parent());
}
// Set Error Indicator on Invalid Input
if (!valid) {
error_element.show();
error_free = false;
}
else {
error_element.hide();
}
// Stop Form Submission
if (!error_free) {
event.preventDefault();
}
}
}
return error_free;
}
/**
* Remove Required Attribute from Checkbox Group -> When one of the option is selected.
* Add Required Attribute from Checkboxes Group -> When none of the option is selected.
*
* #since 2.3.0
*/
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.on('change', function () {
var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');
var isChecked = checkboxGroup.is(':checked');
checkboxGroup.prop('required', !isChecked);
});
});
/*
* Custom Styling of Upload Field Button
*
* #since 2.4.0
*/
var file = {
maxlength: 20, // maximum length of filename before it's trimmed
convert: function () {
// Convert all file type inputs.
$('input[type=file].sjb-attachment').each(function () {
$(this).wrap('<div class="file" />');
$(this).parent().prepend('<div>'+ application_form.file['browse']+'</div>');
$(this).parent().prepend('<span>'+ application_form.file['no_file_chosen']+'</span>');
$(this).fadeTo(0, 0);
$(this).attr('size', '50'); // Use this to adjust width for FireFox.
});
},
update: function (x) {
// Update the filename display.
var filename = x.val().replace(/^.*\\/g, '');
if (filename.length > $(this).maxlength) {
trim_start = $(this).maxlength / 2 - 1;
trim_end = trim_start + filename.length - $(this).maxlength + 1;
filename = filename.substr(0, trim_start) + '…' + filename.substr(trim_end);
}
if (filename == '')
filename = application_form.file['no_file_chosen'];
x.siblings('span').html(filename);
}
}
$(document).ready(function () {
file.convert();
$('input[type=file].sjb-attachment').change(function () {
file.update($(this));
});
});
})(jQuery);
Note: my plugin Version is 2.4.6

SQL insert query insert multiple times and don't update

I want to insert some data that's is send with javascript (cordova app) i send this here
var link = 'somelink';
var stmt = "SELECT * FROM card WHERE Productsync = 0 ";
//console.log(stmt);
$cordovaSQLite.execute(db, stmt).then(function(res) { //console.log(res)
if(res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++){
console.log(res.rows.item(i));
console.log(res.rows.item(i).ProductName);
console.log(res.rows.item(i).ProductBarcode);
console.log(res.rows.item(i).ProductPakking);
console.log(res.rows.item(i).ProductPresent);
console.log(res.rows.item(i).ProductMinimuim);
console.log(res.rows.item(i).FotoUrl);
console.log(res.rows.item(i).DBid);
$http.post(link, {ProductName : res.rows.item(i).ProductName , ProductBarcode : res.rows.item(i).ProductBarcode , ProductPakking : res.rows.item(i).ProductPakking , ProductPresent : res.rows.item(i).ProductPresent , ProductMinimuim : res.rows.item(i).ProductMinimuim , FotoUrl : res.rows.item(i).FotoUrl , DBid : res.rows.item(i).DBid}).then(function (res){//sending data
console.log(res.data);//respone of server
var data = res.data;
for (var key in data) {//read out respone
if (data.hasOwnProperty(key)) {
var obj = data[key];
console.log(obj);
//have to make this
}
}
});
}
}
});
Now i want it to add this in my databases online (BIND variables will i do later) This is how my php script looks like
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$ProductName = $request->ProductName;
$ProductBarcode = $request->ProductBarcode;
$ProductPakking = $request->ProductPakking;
$ProductPresent = $request->ProductPresent;
$ProductMinimuim = $request->ProductMinimuim;
$FotoUrl = $request->FotoUrl;
$DBid = $request->DBid;
$ProductName = mysqli_real_escape_string($connection,$ProductName);
$ProductBarcode = mysqli_real_escape_string($connection,$ProductBarcode);
$ProductPakking = mysqli_real_escape_string($connection,$ProductPakking);
$ProductPresent = mysqli_real_escape_string($connection,$ProductPresent);
$ProductMinimuim = mysqli_real_escape_string($connection,$ProductMinimuim);
$FotoUrl = mysqli_real_escape_string($connection,$FotoUrl);
$DBid = mysqli_real_escape_string($connection,$DBid);
$query ="REPLACE into `card` (ProductName,ProductBarcode,ProductPakking,ProductPresent,ProductMinimuim,FotoUrl,DBid)
VALUES( '" . $ProductName . "' ,
'" . $ProductBarcode . "' ,
'" . $ProductPakking . "' ,
'" . $ProductPresent . "' ,
'" . $ProductMinimuim . "' ,
'" . $FotoUrl . "' ,
'" . $DBid ."')";
When I echo the $ProductName before the query in php, i just see the productsnames (what I want)
My problem is: it don't replace the value if it already exists, and it insert multiple times, it have to insert just one time and replace or update if the column already exists.
Can someone help my ?
UPDATE QUERY IN PHP
$query ="SELECT ProductName FROM `card` WHERE
`ProductName` = '" . $ProductName . "' AND
`ProductBarcode` = '" . $ProductBarcode . "' AND
`ProductPakking` = '" . $ProductPakking . "' AND
`ProductPresent` = '" . $ProductPresent . "' AND
`ProductMinimuim` = '" . $ProductMinimuim . "' AND
`FotoUrl` = '" . $FotoUrl . "' AND
`DBid` = '" . $DBid ."'";
$result_set = mysqli_query($connection,$query);
if (mysqli_num_rows($result_set) == 0){
$query ="INSERT INTO `card` (ProductName,ProductBarcode,ProductPakking,ProductPresent,ProductMinimuim,FotoUrl,DBid)
VALUES( '" . $ProductName . "' ,
'" . $ProductBarcode . "' ,
'" . $ProductPakking . "' ,
'" . $ProductPresent . "' ,
'" . $ProductMinimuim . "' ,
'" . $FotoUrl . "' ,
'" . $DBid ."')";
$result = mysqli_query($connection,$query);
}else{
$query = "UPDATE `card`
SET `ProductName` = '" . $ProductName . "' ,
`ProductBarcode` = '" . $ProductBarcode . "' ,
`ProductPakking` = '" . $ProductPakking . "' ,
`ProductPresent` = '" . $ProductPresent . "' ,
`ProductMinimuim` = '" . $ProductMinimuim . "' ,
`FotoUrl` = '" . $FotoUrl . "' ,
`DBid` = '" . $DBid ."'
WHERE `ProductBarcode` = '" . $ProductBarcode . "' AND `DBid` = '" . $DBid ."'";
$fines = mysqli_query($connection,$query);
}
Note that for this approach (or the REPLACE INTO approach or even the ON DUPLICATE KEY approach) to be successfull you need to have a unique index on the fields that you don't want duplicated.
From docs states
REPLACE makes sense only if a table has a PRIMARY KEY or UNIQUE index. Otherwise, it becomes equivalent to INSERT, because there is no index to be used to determine whether a new row duplicates another.
looks like you have some issue with below lines
console.log(res.data);//respone of server
var data = res.data;
for (var key in data) {
this loop has some problem because if it json then it iterate over all key one by one and it insert multiple of keys record keys injson * number of time response
please provide res.data logs and also check what you get in key and how many time you looping around that loop.

Passing JSON data to another function as parameter ... not passing

PHP script (AJAX is calling this) (within this is this variable):
$name_and_id = $first_name . " " . $last_name . " (" . $row['id'] . ")";
passed back like:
$datarr = array();
$datarr[] = array('name_and_id' => $name_and_id);
echo json_encode($datarr);
JSON successfully accepts like:
$.each(data, function(k, v){
v = v.name_and_id;
...
htmlStr += '<tr onclick="shrow(' + x + ',' + v + ',' + z + ')">'
... populates a div
This loads correctly, but when I click on that tr the request doesn't complete ... console says throwing an error at v ...

How to load content with PHP $_SERVER['PHP_SELF'] and href

Hello everyone I need some help with this:
I´m a total noob in php and javascript and I´m facing a little problem here , I´m working with a website that displays a list on the left side and then when I do a click on an element it shows a subelement then when I do a click on the subelement it displays a table that contains info stored in a mysql database, it works flawlessly but the data shown sometimes displays like 5000 rows so it's annoying to be scrolling all the way down 5000 rows, so I decided to paginate the results to be able to just show like 100 elements per page.
Now when I click on the link to show the next 100 rows it takes me to another page and my menu on the left disappears!
I´m using something like this to navigate through the results:
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' ' . $add1 . ' ';
}
else if ($pn == $lastPage) {
$centerPages .= ' ' . $sub1 . ' ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
}
else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' ' . $sub2 . ' ';
$centerPages .= ' ' . $sub1 . ' ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' ' . $add1 . ' ';
$centerPages .= ' ' . $add2 . ' ';
}
else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' ' . $sub1 . ' ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' ' . $add1 . ' ';
}
My guess is that because the next and back links are an <a href> tags it loads a new page showing the next 100 rows.
How can I prevent that??
I tried to use a jquery adding a preventDefault(); to those <a href="' . $_SERVER['PHP_SELF'] tags, it worked but now nothing happend on those links xD.
Help me please.
Thanks in advance.
I hope that this example helps you. Its not refreshing the url. So your menu link be opened
you can create pagination link like this
$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM paginate");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
$pagination = '';
if($pages > 1)
{
$pagination .= '<ul class="paginate">';
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?>
and here is script for pagination
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page': (page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element
return false; //prevent going to herf link
});
});
and here fetching Pages
<?php
include("config.inc.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($connecDB,"SELECT id,name,message FROM paginate ORDER BY id DESC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '<li id="item_'.$row["id"].'">'.$row["id"].' <span class="page_name">'.$row["name"].'</span><span class="page_message">'.$row["message"].'</span></li>';
}
echo '</ul>';
?>

Categories