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

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;
}

Related

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.

jQuery ajax call to php process form page not returning success or error

I have a contact page with a HTML Form.
I use jQuery to validate the fields. Then use jQuery's .ajax() method to send the information to the php file that processes and sends out the email via the mail() method.
Inside the PHP File i have an IF statement that checks to see if a POST variable is set that way I can put all form processing on one page for multiple forms through out the website.
I get all variables and do another form field validation with PHP. Then I build out the HTML Email and it's headers.
If the PHP Validation is successful I then send the email via the mail() method. Then I check if the mail() method was successful and if so I send another "auto reply" email.
Inside of the IF statements that check to see if the mail() method was successful I echo a success or error message with json_encode().
When the user clicks the submit button on the form I have it set to return false so it stays on the same page and have a message displayed upon send success.
Both emails send successfully from the form. Except my .ajax() method does not receive the success or error message from the php files' json_encode().
I removed the return false in the jQuery .click and have tried a standard PHP echo inside the php IF statement that checks if the post isset() and I couldn't get it to print to the browser. nor does the json_encode print to the browser. However, when I put the PHP echo outside of the IF statement it printed just fine. Which confuses me because it obviously goes inside that if statement to send the email but won't echo. What am I doing wrong?
jQuery
$("#contactFormSubmit").click(function(){
// validate and process form here
// NAME VALIDATION
var name = $("input#nameField").val();
if (name == "") {
$("input#nameField").focus();
$("input#nameField").css("border","1px solid red");
alert("nameFieldError");
return false;
}
// EMAIL VALIDATION
var formEmail = $("input#emailField").val();
if (formEmail == "" || !validateEmail(formEmail)) {
$("input#emailField").focus();
$("input#emailField").css("border","1px solid red");
alert("emailFieldError");
return false;
}
// PHONE VALIDATION
var phone = $("input#phoneField").val();
var phoneReg = "/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/";
if (phone == "" || !isValidUSPhoneFormat(phone)) {
//alert("phone is wrong");
$("input#phoneField").focus();
$("input#phoneField").css("border","1px solid red");
alert("phoneFieldError");
return false;
}
var message = $("textarea#messageField").val();
var subject = $("#subjectField").val();
var dataString = 'name='+ name + '&email=' + formEmail + '&phone=' + phone + '&subject=' + subject + '&message=' + message + '&submitContactForm=1';
$.ajax({
type: "POST",
url: "process-form.php",
data: dataString,
dataType:"json",
success: function(response) {
if(response.status === "success") {
alert("success");
// do something with response.status or other data on success
} else if(response.status === "error") {
alert("error");
// do something with response.status or other data on error
}
},
error: function(xhr,errmsg) { alert(errmsg); }
});
return false;
});
PHP File
<?php
include "includes/functions.php";
if(isset($_POST['submitContactForm'])) {
$nextEventDay = getDay();
$eventToShow = "";
$dayToShow = "";
$dateToShow = "";
if ($nextEventDay == "Sunday" || $nextEventDay == "Monday" || $nextEventDay == "Tuesday" || $nextEventDay == "Wednesday" ||$nextEventDay == "Thursday" || $nextEventDay != "Friday" || $nextEventDay != "Saturday") {
$eventToShow = "thurEvent";
$dayToShow = "THU";
$dateToShow = getNextThursdayDate();
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$messageBody = $_POST['message'];
$sendTo = "xxxx#xxxx.com";
$confirmTo = $email;
//HTML EMAIL
$headers = "From: " . $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//COMPANY EMAIL
$message5 = '<html><style type="text/css">table, td, tr, th{border:none !important;border-color:#111 !important;border-collapse:collapse;}a{color:#c92626 !important;}.title{color:#aaa;}</style><body style="background-color: #111;color:#ddd;border:2px solid #333;">';
$message5 .= '<table rules="all" style="background-color:#111;border:none !important;width:100%;" cellpadding="10" border="0">';
$message5 .= '<tr style="border:none;"><td style="border:none;padding:20px 0px !important;"><img src="images/logo.jpg" alt="Nightclub" style="display:block;margin:0 auto;min-width:260px;max-width:300px;width:50%;" width="260" /></td></tr>';
$message5 .= "<tr style='border:none;'><td style='border:none;'><img src='/images/" . $eventToShow . "-email-next-event.jpg' width='260' style='min-width:260px;max-width:1024px;width:100%;display:block;margin: 0 auto;' /></td></tr>";
$message5 .= "<tr style='border:none;background-color:#161616;'><td style='border:none;' class='title'><strong style='color:#aaa;'>Name:</strong> " . strip_tags($name) . "</td></tr>";
$message5 .= "<tr style='border:none;'><td style='border:none;' class='title' ><strong style='color:#aaa;'>Email:</strong> <span style='color:#c92626 !important;'>" . strip_tags($email) . "</span></td></tr>";
$message5 .= "<tr style='border:none;background-color:#161616;' ><td style='border:none;' class='title'><strong style='color:#aaa;'>Phone:</strong> <span style='color:#c92626 !important;'>" . strip_tags($phone) . "</span></td></tr>";
$message5 .= "<tr style='border:none;'><td style='border:none;' class='title'><strong style='color:#aaa;'>Subject:</strong> " . strip_tags($subject) . "</td></tr>";
$message5 .= "<tr style='border:none;background-color:#161616;' ><td style='border:none;' class='title'><strong style='color:#aaa;'>Message:</strong> " . strip_tags($messageBody) . "</td></tr>";
$message5 .= "<tr style='border:none;'><td style='border:none;'></td></tr>";
$message5 .= "</table>";
$message5 .= "</body></html>";
//CLIENT EMAIL
$areply = '<html><style type="text/css">table, td, tr, th {border:none !important;border-color:#111 !important;border-collapse:collapse;}a {color:#c92626 !important;}.title{color:#aaa;}#date a{color:#fff !important;text-decoration:none;}</style><body style="background-color: #111;color:#ddd;border:2px solid #333;">';
$areply .= "<table rules='all' style='background-color:#111;border:none !important;width:100%;' cellpadding='10' border='0'>";
$areply .= "<tr style='border:none;'><td style='border:none;padding:20px 0px !important;'><img src='images/logo.jpg' alt='Nightclub Ann Arbor' style='display:block;margin:0 auto;min-width:260px;max-width:300px;width:50%;' width='260' /></td></tr>";
$areply .= "<tr style='border:none;'><td style='border:none;'><img src='images/" . $eventToShow . "-email-next-event.jpg' width='260' style='min-width:260px;max-width:1024px;width:100%;display:block;margin: 0 auto;' /></td></tr>";
$areply .= "<tr style='border:none; background:#151515;'><td style='border:none;text-align:justify;background-color:#161616;'><div style='float:left;display:inline-block;background-color:#000;margin:0px 10px 10px 0px;font-size:197%; padding: 25px 30px;'><p id='date' style='margin:0;color:#fff !important;'> \r\n <strong>" . $dateToShow ."</strong></p><p style='margin:0;color:#c92626 !important;'>" . $dayToShow ."</p></div><p style='margin-top:10px;margin-right:15px;'>Thank you for contacting us at Nightclub . We look forward to assisting you. Below is the information that we recieved and we will be contacting you as soon as possible. Thank you again, and we look forward to speaking with you. If you have any additional questions please contact us at our website (<a href='' style='color:#c92626'></a>), give us a call <span style='color:#c92626 !important;'></span>, or send us an Email <span style='color:#c92626 !important;'></span></p></td></tr>";
$areply .= "<tr style='border:none;'><td style='border:none;' class='title'><strong style='color:#aaa;'>Name: </strong>" . strip_tags($name) . "</td></tr>";
$areply .= "<tr style='border:none; background-color:#161616 !important;' ><td style='border:none !important;background-color:#161616 !important;' class='title'><strong style='color:#aaa;'>Email:</strong> <span style='color:#c92626 !important;'>" . strip_tags($email) . "</span></td></tr>";
$areply .= "<tr style='border:none;'><td style='border:none;' class='title'><strong style='color:#aaa;'>Phone:</strong> <span style='color:#c92626 !important;'>" . strip_tags($phone) . "</span></td></tr>";
$areply .= "<tr style='border:none;background-color:#161616;' ><td style='border:none;' class='title'><strong style='color:#aaa;'>Subject:</strong> " . strip_tags($subject) . "</td></tr>";
$areply .= "<tr style='border:none;'><td style='border:none;' class='title'><strong style='color:#aaa;'>Message:</strong> " . strip_tags($messageBody) . "</td></tr>";
$areply .= "<tr style='border:none;'><td style='border:none;'></td></tr>";
$areply .= "</table>";
$areply .= "</body></html>";
$subject2 = "Thank you for your expressed interest ()";
$noreply = "xxx#xxx.com";
$headers2 = "From: " . $noreply . "\r\n";
$headers2 .= "MIME-Version: 1.0\r\n";
$headers2 .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (empty($name) || empty($email) || empty($phone) || !preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[#][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$email) || !preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
echo json_encode(array(
'status' => 'error'
//'message'=> 'error message'
));
} else {
$send = mail($sendTo, $subject, $message5, $headers);
}
if($send){
echo json_encode(array(
'status' => 'success'
//'message'=> 'success message'
));
$send2 = mail($email, $subject2, $areply, $headers2);
} else {
echo json_encode(array(
'status' => 'error'
//'message'=> 'success message'
));
}
}
?>
UPDATE
I added the error call back to the jQuery ajax() method and found I was receiving the error I also removed everything from my PHP file except for the:
echo json_encode(array(
'status' => 'success'
//'message'=> 'success message'
));
And I still get the error message from the jQuery ajax() method. So it must be in my jQuery code... I think.
Ok, so thanks to the advice from #PatrickEvans and #MartyMcKeever above, I solved it by looking at the firebug console to find out that one of my custom PHP functions was missing a required argument. This was causing a parse error which was then making my jQuery throw an error but still allow the PHP to process the email.
If you look at the above PHP code there is a method that says $nextEventDay = getDay();
It should have been $nextEventDay = getDay("today");. This was causing all the problems
give #MartyMcKeever's comment an up vote.

Categories