js Object Array causing function not defined - multidimensional-array

Ok, I'm having a hard time trying to create an object array that I can use within a select box...
Here is the code I have so far:
var oTranslators = {{"bosniancroatianserbian" : null} , {"dutch" : {"name":"willemjan","id":2}} , {"german" : {"name":"chilly","id":11}} , {"german_informal" : {"name":"Boantio","id":1640}} , {"greek" : null} , {"hungarian" : {"name":"Rudi","id":69}} , {"norwegian" : null} , {"russian" : {"name":"Bugo","id":43}} , {"spanish" : {"name":"Diego Andr\u00e9s","id":413}} };
function lang_switch(val)
{
if (val == 1)
document.getElementById("lang").innerHTML = '<select name="lang_name" onchange="trans_switch(this.selectedIndex);"><option value="bosniancroatianserbian">Bosnian/Croatian/Serbian</option><option value="dutch">Dutch</option><option value="german">German</option><option value="german_informal">German Informal</option><option value="greek">Greek</option><option value="hungarian">Hungarian</option><option value="norwegian">Norwegian</option><option value="russian">Russian</option><option value="spanish">Spanish</option></select><label for="translator">Translator: <select name="translator" id="translator"></select></label>';
else
document.getElementById("lang").innerHTML = '';
}
function trans_switch(oBName)
{
document.upload.translator.options.length = 0;
var oBoard = oTranslators[oBName];
for (var i = 0; i < oBoard.length; i++) {
translator.options[translator.options.length] = new Option(oBoard.name, oBoard.id, false, false);
}
}
And the HTML:
<form name="upload" enctype="multipart/form-data" action="http://mydomain.com/myaction.php" method="post" autocomplete="off">
<dl class="settings">
<dt>
<strong>Choose a file to upload:</strong>
</dt>
<dd>
<input type="file" name="dp_file" size="38" class="input_file" />
</dd>
<dt>
<select name="down_area" onchange="lang_switch(this.value);">
<option value="0">Main Download</option>
<option value="1">Language Packs</option>
</select>
</dt>
<dd>
<div id="lang"></div>
</dd>
</dl>
<div style="text-align: right;"><input name="upload" type="submit" value="Upload" class="button_submit" /></div>
</form>
Basically, I am getting error stating that lang_switch is undefined, which is nuts, because it's right there. Is there something wrong with my object array? Did I not define it properly? This is coming from a json_encode, but it is a multidimensional array and I had to fix it a little, so am using this php code to fix it, within a for loop:
$oTrans = '';
$i = 0;
foreach($context['languages'] as $lang => $language)
{
$i++;
$oTrans .= '{"' . $lang . '" : ' . json_encode($language['translator'][$lang]) . '} ' . (count($context['languages']) == $i ? '};' : ', ');
Am I not doing this right? What is wrong with the oTranslators object array above?

The problem you are facing with your code is that while you are trying to make a javascript-array of objects, you are attempting to initialize the array using object-brackets: {.
The result will give you an error, because you cannot initialize an object in the following way:
{{Prop1:val}, {Prop2:val}};
It would need to be the following:
{Prop1:val, Prop2:val};
Therefore, to fix your array, all you need to do is replace the first { and last } with array brackets, [ and ]:
[{"bosniancroatianserbian" : null} , {"dutch" : {"name":"willemjan","id":2}} , {"german" : {"name":"chilly","id":11}} , {"german_informal" : {"name":"Boantio","id":1640}} , {"greek" : null} , {"hungarian" : {"name":"Rudi","id":69}} , {"norwegian" : null} , {"russian" : {"name":"Bugo","id":43}} , {"spanish" : {"name":"Diego Andr\u00e9s","id":413}} ];

Related

How can i set error message in right place drupal 7?

need help with drupal 7. I'm newbie with drupal.
I have code below for validation and validation errors, and it works fine. But errors always appear in wrong place.
I think the problem in $element, but i'm note sure.
some example html
<form id="webform_client_form_226">
<div class="catalogue__form-input-inner">
<div class="catalogue__form-input">
<div class="form-item">
// i need it here
<label for="edit-submitted-vashe-imya--3">Your name</label>
<input name="submitted[vashe_imya]" value="" size="60" maxlength="128" class="form-text error">
</div>
</div>
<div class="catalogue__form-input">
<div class="form-item webform-component webform-component-textfield webform-component--nomer-telefona webform-container-inline">
// and here
<label>Phone number</label>
<input name="submitted[nomer_telefona]">
</div>
</div>
<div class="catalogue__form-button">
// always appears here right now
<div class="form-actions">
<input name="op" value="send"></div>
</div>
</div>
</div>
and template.php
function pkpro_uikit_form_alter(&$form, &$form_state, $form_id) {
// Check the form id
if($form_id == 'webform_client_form_226') {
$form['#validate'][] = 'form_validate';
}
}
function form_validate(&$form, &$form_state) {
$message = "Field required";
if(isset($form_state['values']['submitted']['vashe_imya'])) {
$name = $form_state['values']['submitted']['vashe_imya'];
if( condition ) {
form_error($form['submitted']['vashe_imya'], $message);
}
}
if(isset($form_state['values']['submitted']['nomer_telefona'])) {
$name = $form_state['values']['submitted']['nomer_telefona'];
if( condition ) {
form_error($form['submitted']["nomer_telefona"], $message);
}
}
// get all validation errors.
$form_errors = form_get_errors();
if (!empty($form_errors)) {
foreach ($form_errors as $element => $error) {
$form[$element]['#suffix'] = '<div>'.$error.'</div>';
}
}
// clear default error messages.
drupal_get_messages('error');
}
Help, pls)
You need to modify your template. Look for page.tpl.php. It should have a $message variable on it. Move it to the correct location. If you only want it for one content type or page, copy the page.tpl.php so it only targets what you want.

Nonce check is failing

EDITED WITH UPDATED CODE: STILL NO SOLUTION
Can anyone spot the error in this code please?
custom-page.php:
<form name="customForm">
<?php wp_nonce_field('code_check', 'codecheck'); ?>
Validation Code:<br>
<input type="password" name="inputcode" id="inputcode" maxlength="6" inputmode="numeric">
<input type="text" name="message" id="message" style="display:none; background-color: #FFCCCC;"><br>
<input type="button" name="submitbutton" value="Submit" onClick="customfunction()">
</form>
custom.js:
function customfunction() {
const userInput = document.addStamp.inputcode.value;
const token = document.addStamp.codecheck.value;
fetch(`http://...../wp-json/api/v1/custom?code=${userInput}&token=${token}`).then(r => r.json()).then(data => {
......
API file.php:
public function custom($request)
{
$params = $request->get_params();
$retrieved_nonce = $params[token];
if($retrieved_nonce) {
if (!wp_verify_nonce($retrieved_nonce, 'code_check' ) ) die( 'Failed security check' );
}
....
Everything works fine until I added in the nonce verify code to the api request.
Now when I click on "submit" button, it does not submit and I get in console:
Uncaught (in promise) SyntaxError: Unexpected token F in JSON at position 0
So it is failing as "F" is point 0 of the failure message.
However, if I output "$retrieved_nonce" I actually get the nonce value as shown in my page source code, so it looks like it is getting to the endpoint?
I have tried logging out and back in but no change.
Do I have this code set up wrong?
You can try.
Form.
<form name="customForm" method="post">
<?php wp_nonce_field('code_check', 'code_check'); ?>
Validation Code:<br>
<input type="password" name="inputcode" id="inputcode" maxlength="6" inputmode="numeric">
<input type="text" name="message" id="message" style="display:none; background-color: #FFCCCC;"><br>
<input type="button" name="submitbutton" value="Submit" onClick="customfunction()">
</form>
In customfunction function also send the wp_nonce_field filed value like.
function customfunction() {
const userInput = document.customForm.inputcode.value;
const code_check = document.customForm.code_check.value;
fetch('http://...../wp-json/api/v1/custom?code='+userInput+'&code_check'+code_check).then(r => r.json()).then(data => {
Now in validate the wp_nonce_field field value
public function custom($request)
{
$retrieved_nonce = $request['code_check'];
if (!wp_verify_nonce($retrieved_nonce, 'code_check' ) ) die( 'Failed
security check' );
/***
you can also try
if ( isset( $request['code_check'] ) || wp_verify_nonce( $request['code_check'], 'code_check' ) )
*******/
}

get values of all selected checkboxes symfony2

<th scope="col">{{ d.id }} <input type="checkbox" value="{{ d.id }}" name="checkboxD" class="checker"></th>
how to get list of values from the selected checkbox ??
my controller action
public function traiterAction() {
$IDs = array();
if ( $this->getRequest()->isMethod('POST') ) {
$IDs = $this->getRequest()->get('checkboxD');
}
return $this->render('#EgovPoste/test.html.twig',array('ids'=>$IDs));
}
You need to change the name to checkboxD[] .
I hope that will help you

Changing some text in the Fivestar module

I'm using the Fivestar module in Drupal 6...
http://drupal.org/project/fivestar
And, I want to change the text:
From: Average: *****
To This: Rate this Article: *****
I'd rather not hack the module of use string overrides, I'm hoping to use a hook_form_alter function or something similar in the template.php file.
Here's is what the HTML looks like:
<form action="/fall-foliage" accept-charset="UTF-8" method="post" id="fivestar-form-node-232" class="fivestar-widget"><div>
<div class="fivestar-form-vote-232 clear-block"><input type="hidden" name="content_type" id="edit-content-type" value="node" />
<input type="hidden" name="content_id" id="edit-content-id" value="232" /><div class="fivestar-form-item fivestar-average-stars fivestar-labels-hover">
<div class="form-item" id="edit-vote-wrapper">
<label for="edit-vote">Average: </label>
...etc...
Code in fivestar.module looks like this:
function theme_fivestar_summary($user_rating, $average_rating, $votes, $stars = 5, $feedback = TRUE) {
$output = '';
$div_class = '';
if (isset($user_rating)) {
$div_class = isset($votes) ? 'user-count' : 'user';
$user_stars = round(($user_rating * $stars) / 100, 1);
$output .= '<span class="user-rating">'. t('Your rating: <span>!stars</span>', array('!stars' => $user_rating ? $user_stars : t('None'))) .'</span>';
}
if (isset($user_rating) && isset($average_rating)) {
$output .= ' ';
}
if (isset($average_rating)) {
$div_class = isset($votes) ? 'average-count' : 'average';
$average_stars = round(($average_rating * $stars) / 100, 1);
$output .= '<span class="average-rating">'. t('Average: <span>!stars</span>', array('!stars' => $average_stars)) .'</span>';
}
in fivestar.module file search for 'Average' not 'average' and can change as per your wise, But changing core module file is not recommend(Whenever you update your module, changes revert back).
Please create custom module and implement hook_form_alter
Example:
function YourModuleName_form_alter(&$form, $form_state, $form_id)
Print $form and search for 'Average'
change $form[xyz][xyz] = 'Average' to $form[xyz][xyz] = 'Rate this Article'
if is not form, use hook_nodeapi

posting a footer contact form to a different script not working

I have two files the one which hosts my actual contact form and then a file where i post the form to.
contactform.php (which is part of the footer template)
<form id="contact" action="<?php bloginfo('template_url'); ?>/sendmail.php" method="post">
<label for="name">Your name: *</label>
<input type="text" id="nameinput" name="name" value=""/>
<label for="email">Your email: *</label>
<input type="text" id="emailinput" name="email" value=""/>
<label for="comment">Your message: *</label>
<textarea cols="20" rows="7" id="commentinput" name="comment"> </textarea><br />
</form>
sendmail.php
<?PHP
if(isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
{
$to = preg_replace("([\r\n])", "", hexstr($_POST['receiver']));
$from = preg_replace("([\r\n])", "", $_POST['email']);
$subject = "Website contact message from ".$_POST['name'];
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) ||
preg_match($match, $from) ||
preg_match($match, $message)) {
die("Header injection detected.");
}
$headers = "From: ".$from."\r\n";
$headers .= "Reply-to: ".$from."\r\n";
if(wp_mail($to, $subject, $message, $headers,'',true))
{
echo 1; //SUCCESS
}
else {
echo 2; //FAILURE - server failure
}
}
else {
echo 3; //FAILURE - not valid email
}
}else{
die("Direct access not allowed!");
}
function hexstr($hexstr) {
$hexstr = str_replace(' ', '', $hexstr);
$hexstr = str_replace('\x', '', $hexstr);
$retstr = pack('H*', $hexstr);
return $retstr;
}
?>
The issue is that this does not know of wp_mail function. I know that I need to include something so wp_mail will be available but what do I add? The function does exist. The issue with including the file that has wp_mail defined is that inside that function it requires some core php functions (wp_mail is being overwritten by cimy_swift plugin)
hi why not try just submitting the form to the base wpurl? then within your header.php file copy and paste your code in?
ie: using a hidden field you can check to see if its been posts, in this case the hidden field is called 'action' and it has a value of 'sendemail'.
form
<form id="contact" action="<?php bloginfo('wpurl'); ?>" method="post">
//form stuff
<input type="hidden" name="action" value="sendemail" />
</form>
Header.php
within the header file we do a call to check and see if the form has been posted,
<html>
<head>
<title><?php wp_title();?></title>
<?php
if( isset($_POST['action']) && ($_POST['action']=='sendemail') ) {
// run your code
}
?>
</head>
if you dont want to go down that route, and wish to use your theme folder to hold the php script then what to is, include the below in your sendmail.php file
define('WP_USE_THEMES', FALSE);
require('../../../wp-blog-header.php');
//above is assuming your file is located in the theme root, not a sub folder.
this will give you access to all the wordpress functions and shortcodes etc..etc..
hope that helps a little..
Marty

Resources