Embed if condition inside javascript function with HTML output - javascript

I am trying to update a script written by someone else and need some help, as I do not work in Javascript often. The script is part of a SurveyGizmo survey, so may use some syntax/functions not standard in Javascript.
The script below works. It takes the results of each category's quiz score and prints a message stored in another variable in the survey. There are 5 categories. The output looks like this:
Category 1 Score
Category 1 Message
Category 2 Score
Category 2 Message
etc..
Below this code is my question.
function sgapiQuizResults(){
%%html .= '<div class="recommendations"><div class="something">Recommendations</div>';
foreach (sgapiQuizMessages() as %%category => %%message) {
%%html .= '<div class="recommendation '. sgapiCSSClassName(%%category) .'">';
%%html .= '<div class="header">' . %%category .'</div>';
%%html .= '<div class="graphic">'. sgapiScore(%%category) . '</div>';
%%html .= '<div class="content">' . %%message . '</div>';
%%html .= '</div>';
}
%%html .= '</div>';
return %%html;
}
What I would like to do is modify this to add additional messaging that cannot be stored in a variable. Basically, I would like to add a condition similar to as follows:
if ( Number(sgapiGetValue(8)) < 3 ) {
%%html .= "Message for Question 8";
}
if ( Number(sgapiGetValue(9)) < 3 ) {
%%html .= "Lorem Ipsum for 9";
}
if ( Number(sgapiGetValue(10)) < 3 ) {
%%html .= "Dolor for 10";
}
... and so on ...
The output of which would look like:
Category 1 Score
Category 1 Message
Message for Question 8
Category 2 Score
Category 2 Message
Lorem Ipsum for 9
etc..
I have been successful at simply adding &&html .= 'Hello World'; to the code, having that message printed to each category; however, any time I try to include a conditional statement, the script breaks.
Any help would be much appreciated!

function sgapiQuizResults(){
%%html .= '<div class="recommendations"><div class="something">Recommendations</div>';
foreach (sgapiQuizMessages() as %%category => %%message) {
%%html .= '<div class="recommendation '. sgapiCSSClassName(%%category) .'">';
%%html .= '<div class="header">' . %%category .'</div>';
%%html .= '<div class="graphic">'. sgapiScore(%%category) . '</div>';
%%html .= '<div class="content">' . %%message . '</div>';
if ( Number(sgapiGetValue(8)) < 3 ) {
%%html .= '<div class="content">Message for Question 8</div>';
}
if ( Number(sgapiGetValue(9)) < 3 ) {
%%html .= '<div class="content">Lorem Ipsum for 9</div>';
}
if ( Number(sgapiGetValue(10)) < 3 ) {
%%html .= '<div class="content">Dolor for 10</div>';
}
%%html .= '</div>';
}
%%html .= '</div>';
return %%html;
}
revised.
can try this?

Related

How to create a boostrap modal using chatGpt inside [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
I tried to create a boostrap modal including a chat inside and using chatgpt.
I have just a problem after the message is sent, maybe my js is not well set or the orientation I take is not the good approach.
I need some help to close this point
What I need to change ?
No idea if I am int the good way. Please let me know
Thank you
My modal
$content = '<!-- Gpt start -->';
$content .= '<link rel="stylesheet" href="http://localhost/admin/css/chatgpt.css">';
$content .= '' . $this->app->getDef('text_gpt') . '';
$content .= '<!-- The Modal -->';
$content .= '<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">';
$content .= '<div class="modal-dialog modal-lg">';
$content .= '<div class="modal-content">';
$content .= '<!-- Modal Header -->';
$content .= '<div class="modal-header">';
$content .= '<h4 class="modal-title">Chat Box</h4>';
$content .= '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>';
$content .= '</div>';
$content .= '<!-- Modal body -->';
$content .= '<div class="modal-body">';
$content .= '<div class="chat-box">';
//the question
$content .= '<div class="chat-box-header">';
$content .= '<span class="col-md-10">';
$content .= HTML::inputField('msg', null, 'placeholder="Type a message..."');
$content .= '</span>';
$content .= '<span class="col-md-2">';
$content .= HTML::button($this->app->getDef('text_send'), null, null, 'success', ['params' => 'id="ajax_message_gpt" list="chatgpt_list"']);
$content .= '</span>';
$content .= '</div>';
// $content .= '</form>';
$content .= '<div class="chat-box-body">';
//the response
$content .= '<div class="chat-box-message" id="message">';
$content .= '<datalist id="chatgpt_list"></datalist>';
$content .= '<p class="message-text">Hello! How can I help you?</p>';
$content .= '<p class="message-time">12:00 PM</p>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '<!-- Gpt end -->';
// Call my ajax
$chtgpt_ajax = CLICSHOPPING::link('ajax/chatGpt.php');
//the javascript
//AS you see I have some problem inside
==> addEventListener("keyup", function(event) Keyup need to be change I think
==> `option.value = item.prompt;
Below all the script
$output = <<<EOD
<script>
window.addEventListener("load", function(){
// Add a keyup event listener to our input element
document.getElementById('ajax_message_gpt').addEventListener("keyup", function(event){hinterchatGpt(event)});
// create one global XHR object
// so we can abort old requests when a new one is make
window.hinterchatGptXHR = new XMLHttpRequest();
});
// Autocomplete for form
function hinterchatGpt(event) {
var input = event.target;
var ajax_message_gpt = document.getElementById('chatgpt_list'); //datalist id
// minimum number of characters before we start to generate suggestions
var min_characters = 0;
if (!isNaN(input.value) || input.value.length < min_characters ) {
return;
} else {
window.hinterchatGptXHR.abort();
window.hinterchatGptXHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse( this.responseText );
ajax_message_gpt.innerHTML = "";
response.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
option.value = item.prompt;//get name
ajax_message_gpt.appendChild(option);
});
}
};
window.hinterchatGptXHR.open("GET", "{$chtgpt_ajax}?q=" + input.value, true);
window.hinterchatGptXHR.send()
}
}
</script>
EOD;
Below my ajax
if (isset($_GET['q'])) {
$terms = HTML::sanitize(mb_strtolower($_GET['q']));
$client = OpenAI::client(CLICSHOPPING_APP_CHATGPT_CH_API_KEY);
$result = $client->completions()->create([
'model' => 'davinci',
'prompt' => $terms,
'temperature' => 0.9,
'max_tokens' => 150,
'frequency_penalty' => 0,
'presence_penalty' => 0.6
]);
# JSON-encode the response
$json_response = json_encode($result); //Return the JSON Array
# Return the response
echo $json_response;
}

javascript radio on click

I would know how to update a file when I click on radio button
When I click on the radio button, the page is updated with the new radio button checked.
I added :
id="radio_shipping_' . $j .'"
Now I miss the javascript. I don't know how to
Thank you
for ($j=0, $n2=count($quote['methods']); $j<$n2; $j++) {
$checked = (($quote['id'] . '_' . $quote['methods'][$j]['id'] == $_SESSION['shipping']['id']) ? true : false);
$data .= '<tr>';
$data .= '<td class="text-md-right">';
if (isset($quotes['error'])) {
$data .= ' ';
} else {
$data .= '<span class="moduleRadio">' . HTML::radioField('shipping', $quote['id'] . '_' . $quote['methods'][$j]['id'], $checked, 'required aria-required="true" id="radio_shipping_' . $j .'"') .'</span>';
}
$data .= '</td>';
$data .= '</tr>';
}

Javascript form submit change action with attr attributes

I want to change the attribute action from my form in the goal to get the next page dynamically. In javascript, my variable action get the right 'value' but the page does not load still. It works fine if I return manually the right 'value', but it does not work when I use jQuery('#select_program').children().filter(':selected').text().replace(/\s+/g, '-').toLowerCase(), to make it dynamically.
Here is my form (in php):
public function form_creation() {
$html = '<form id="search_projects" action="';
$html .= esc_url(get_bloginfo('url'));
$html .= '/" method="post">';
$html .= '<select id="select_langue" name="lg123" onchange="change_select(0, this.value)">';
$html .= '<option value="nd" class="optionDefault">';
$html .= __('Language', 'mon-plugin');
$html .= '</option>';
$html .= '</select>';
$html .= '<select id="select_program" name="pg123" onchange="change_select(1, this.value)">';
$html .= '<option value="nd" class="optionDefault">';
$html .= __('Program', 'mon-plugin');
$html .= '</option>';
$html .= '</select>';
$html .= '<select id="select_country" name="dst123" onchange="change_select(2, this.value)">';
$html .= '<option value="nd" class="optionDefault">';
$html .= __('Country', 'mon-plugin');
$html .= '</option>';
$html .= '</select>';
$html .= '<select id="select_city" name="city123" onchange="change_select(3, this.value)">';
$html .= '<option value="nd" class="optionDefault">';
$html .= __('City', 'mon-plugin');
$html .= '</option>';
$html .= '</select>';
$html .= '<input type="hidden" name="data123" value="';
$html .= htmlspecialchars(json_encode($this->backend_select_category));
$html .= '"/>';
$html .= '<button id="submit_project_list" type="submit">';
$html .= '<i class="fa fa-search" aria-hidden="true"></i>';
$html .= __('Search', 'mon-plugin');
$html .= '</button>';
$html .= '</form>';
return $html;
}
Here is my javascript:
jQuery('#search_projects').submit(function() {
var selection_value = [
jQuery('#select_langue').val(),
jQuery('#select_program').val(),
jQuery('#select_country').val(),
jQuery('#select_city').val()
];
var selection_display = [
jQuery('#select_langue').children().filter(':selected').text().replace(/\s+/g, '-').toLowerCase(),
jQuery('#select_program').children().filter(':selected').text().replace(/\s+/g, '-').toLowerCase(),
jQuery('#select_country').children().filter(':selected').text().replace(/\s+/g, '-').toLowerCase(),
jQuery('#select_city').children().filter(':selected').text().replace(/\s+/g, '-').toLowerCase()
];
jQuery(this).attr('action', function() {
if (selection_value[1] !== 'nd') {
var action = selection_display[1];
if (selection_value[2] !== 'nd') {
action += selection_display[2];
if (selection_value[3] !== 'nd') {
action += selection_display[3];
}
}
} else {
var action = 'search_program';
}
return action;
});
});
Thank you for your help !
I solved the problem.
I realize when I do not change any select, the page changes like it should. But when I change just one select, the page does not load anymore.
I don't know why, but the problem comes from my hidden input in php. If I remove it, everything works.
Great.. but how can I send my data through this form to the other page so ?
Thank you in advance for your help !

How to create a javascript widget to load recent posts from my wordpress site and display in other sites?

I have a WordPress site. I want to allow others to place a web widget in their website which grabs recent posts from my site and display title with a link to its page for each of my recent posts. I know that this is possible through using iframe. But this has no positive effect on my website SEO. I found a solution here to use JavaScript for similar purpose. But it used Python and JSON to load HTML from the original site in the main() function. I am not familiar with JSON and Python. Is there any solution that I can return my recent posts using PHP and put it in the main function?
I use SimplePie to get RSS feeds. This is the function I use.
function start_rss(){
$urls = array(
0 => 'http://ogmarketreport.com',
1 => 'http://petroriveroil.com/feed/'
);
$numberOfPosts = 10;
foreach ($urls as $key => $value) {
$url = $value;
$feed = new SimplePie();
$feed->set_cache_location($_SERVER['DOCUMENT_ROOT'] . '/cache/');
$feed->set_feed_url($url);
$feed->set_stupidly_fast(true);
$feed->init();
$feed->handle_content_type();
$blog_title = $feed->get_title();
$blog_title_url = '<div class="row" style="width: 100%; display: block;"><h2><?php $title; ?></h2></div>';
$blog_desc = $feed->get_description();
$html = "";
$x = $feed->get_items(0, $numberOfPosts);
$html .= '<div class="container" style="width: 100%; display: block;"><h2><a target="_blank" href="' .$feed->get_permalink() . '">' . $feed->get_title() . '</a></h2></div>';
if (count($x) == 0 ) {
$html .= '<article class="rss col-md-12">';
$html .= '<p class="danger">No Recent Posts.</p>';
$html .= '</article>';
} else {
foreach ($x as $item) {
$html .= '<article class="rss col-md-12">';
$html .= '<h4 class="title">';
$html .= '' .$item->get_title() . '' ;
$html .= '</h4>';
$html .= '<p>';
$html .= $item->get_description();
$html .= '</p>';
$html .= '<p><small>';
$html .= "Posted on ";
$html .= $item->get_date('j F Y | g:i a');
$html .= '</small></p>';
$html .= '</article>';
}
}
print_r($html);
}

How to create mega dropdown menu dynamically using PHP?

I need to create mega drop down menu dynamically. I have created code but not able to display like this: http://cdn.tutsplus.com/net/uploads/legacy/819_megamenu/demo/index.html
I have studied other code but not helping me.
Below is my code:
$result = mysql_query("SELECT id, label, link, parent FROM menu ORDER BY parent, sort, label");
//Create a multidimensional array to conatin a list of items and parents
$menu = array(
'items' => array(),
'parents' => array()
);
//Builds the array lists with data from the menu table
while($items = mysql_fetch_assoc($result)) {
//Creates entry into items array with current menu item id ie. $menu['items'][1]
$menu['items'][$items['id']] = $items;
//Creates entry into parents array. Parents array contains a list of all items with children
$menu['parents'][$items['parent']][] = $items['id'];
}
//echo "<pre>"; print_r($menu);
//Menu builder function, parentId 0 is the root
function buildMenu($parent, $menu) {
$html = "";
if(isset($menu['parents'][$parent])) {
$html .= "<ul id='mega-menu-9' class='mega-menu'>";
foreach($menu['parents'][$parent] as $itemId) {
if(!isset($menu['parents'][$itemId])) {
$html .= "<li><a href='Javascript: void(0);' class='arrow'><span><i class='fa fa-home'></i></span>".$menu['items'][$itemId]['label']."</a><li>";
}
if(isset($menu['parents'][$itemId])) {
$html .= "<li><a href='Javascript: void(0);' class='arrow'><span><i class='fa fa-home'></i></span>".$menu['items'][$itemId]['label']."</a>";
$html .= buildMenu($itemId, $menu);
$html .= "</li>";
}
}
$html .= "</ul> \n";
}
return $html;
}
Try this, it's working for me :)
$Testresult = mysql_query("select id,anchordescription,RootMenu,link from MenuTable");
$menu = array(
'menus' => array(),
'parent_menus' => array()
);
while ($row = mysql_fetch_assoc($Testresult))
{
$menu['menus'][$row['id']] = $row;
$menu['parent_menus'][$row['RootMenu']][] = $row['id'];
}
function buildMenu($parent, $menu)
{
$html = "";
if (isset($menu['parent_menus'][$parent]))
{
$html .= "<ul id='ulNav'>";
foreach ($menu['parent_menus'][$parent] as $menu_id)
{
if (!isset($menu['parent_menus'][$menu_id]))
{
$html .= "<li><a href='" . $menu['menus'][$menu_id]['link'] . "'>" . $menu['menus'][$menu_id]['anchordescription'] . "</a></li>";
}
if (isset($menu['parent_menus'][$menu_id]))
{
$html .= "<li><a href='" . $menu['menus'][$menu_id]['link'] . "'>" . $menu['menus'][$menu_id]['anchordescription'] . "</a>";
$html .= buildMenu($menu_id, $menu);
$html .= "</li>";
}
}
$html .= "</ul>";
}
return $html;
}
There is a huge amount of examples in the internet. Here is a nice step-by-step explanation of how to build a menu like the one that you want.
I also recommend you to look for jQuery plugins as there are a lot of working solutions there.

Categories