I have created form which automatically search text (this text is recognized from recorded voice). After recording user's voice JS (below) recognize voice as text, then call form by id="searchform". This form then call function, which search word in database of words. JS code:
final_transcript = capitalize(final_transcript);
var queryTextField = document.getElementById("search_query");
queryTextField.value = final_transcript;
//automatic submit button search form is if form
document.getElementById('searchform').submit();
JS code call function "media/search" which is implemented in this HTML form:
<li><form class="input-group navbar-form" id="searchform" action="<?php echo base_url();?>media/search" method="post"></li>
<input type="text" class="form-control" placeholder="Vyhladat titulky..." id="search_query" name="string" />
<button type="submit" name="btn_search"></button>
</form>
"Media/search" function, which search recognized text:
//Search function
function search($string = null) {
//function can search string sent in url or in form
$data['string'] = isset($_POST['string']) ? $_POST['string'] : $string;
//For not null form
if(! empty($data['string'])) {
//Searching in database
$gid = (! access(3) && ! access(4)) ? $this->userinfo('group') : null;
$data['list'] = $this->media_model->search($data['string'], $gid);
}
//Data are set to show
$this->template->view("media/search", $data);
}
Auto submit seems works because the page with results is shown after record of voice, but no results of searching are shown. I think that searching function works, but with no value, so it seems that it search "no word". I need help, I am new in JS. This code was created in my school and I need to change it to work automatically
You should make order in your mind.
The second function is PHP (server side), it searches for your results and then write that result in the $data variable and pass it to the view "media/search".
So you should at least try to print out that variable to see if it works. To print it you can do in PHP:
<div id="results"><?php echo $data?></div>
Related
I'm have created a random slot machine with JavaScript, which works perfectly fine.
After the result is shown in the slot machine, a button to open a modal/dropdown window appears, here the user can get more details about their results (bigger image, text, titles, google map locations etc).
But for the next part of my project I have created user logins (using PHP & MySQL), so now I want to save the randomly generated result shown inside the modal/dropdown window (JavaScript) to the user's personal profile side (PHP/SQL) so that they can recheck their results when ever they feel like it.
Does anyone know any good solutions?
I have a JavaScript random image generator (with accompanying attributes) which looks like this:
const array = [
{img: 'img1.png', text:'image one', title:'etc etc etc'}
//img2 & img3 under here.
];
function generate(){
setTimeout(funtion first_img() {
index = Math.floor(Math.random() * array.length)
var display = array[index]
var result = document.getElementById('box').innerHTML += '<div><h2>' + `${display.title}` + '</h2><img src="' +`./img/${display.img}`+'"><p>'+`${display.text}`+'</p></div>'
document.querySelector('input["data"]').value = result;
}, 3000);
}
function modal_window(){
document.getElementById('before-box').style.display = 'none';
document.getElementById('modal-window').style.display = 'block';
}
This is displayed in my Index.php file after the button is clicked.
<button onclick="generate()">Generate Image</button>
<div class="open-modal-btn">
<button onclick="modal_window()">See details</button>
</div>
<div id="before-box"></div>
<div id="modal-window">
<div class="box"><
<form method="get" action="profile.php">
<input type="hidden" name="data"/>
</form>
See Profile Results
</div>
</div>
Now, I want to save this result to my Profile.php file and save it there for like two weeks, ish, but I don't know how, the $_GET['data'] is just an example because I can't have name="" attributes in div tags, which is why I don't know what should be there - it would have worked with input name="data", but in my case, the user is not supposed to contribute.
<?php
include ('conn.php');
session_start();
$res = $_GET['data'];
echo $res;
?>
I have the JavaScript array stored inside my SQL database in the same manner, with numbered ID as 0-2 (since JavaScript arrays start at 0), is there any way I can match the random number index with the SQL ID when retrieving the data maybe?
for example:
<?php
$id = $_GET['data'];
$sql = mysqli_query($conn, "SELECT * FROM array WHERE id = '$id'");
?>
Any solutions or tips are greatly appreciated, thanks!
PS: I do not mind implementing new code languages/variants to resolve this issue (AJAX, Python, etc) anything helps.
From: a desperate bachelor student :`)
You need to submit the form but you use outside for go to profile, instead you need to use a button inside form like:
<form method="get" action="profile.php">
<input type="hidden" name="data"/>
<button type="submit">See Profile Results</button>
</form>
I have a Ninja Forms form which asks for the email address and a optin checkbox. After the user submits, it opens a popup with a follow up form (using plugin Popup Maker) where the user is asked to enter more (optional) details. As the follow up form has its own submissions table, I would like to pass the email address of the first form to the popup follow-up form, so that the user doesn't have to enter it again.
Ideally, it saves all this info into just one submissions table, but I guess Ninja Forms isn't constructed that way (?).
Using the Submission Processing Hooks (http://developer.ninjaforms.com/codex/submission-processing-hooks/), I added the following code to the theme's functions.php:
add_action( 'ninja_forms_after_submission', 'ninja_forms_save_email_to_cookie' );
function ninja_forms_save_email_to_cookie( $form_data ){
$cookie_name = "nl_email";
$cookie_value = $form_data;
setcookie($cookie_name, $cookie_value); // Session cookie.
}
But no cookie is saved.
For the follow-up form I have this in the theme's functions.php which is supposed to fill a hidden form field (field key is email_1519816442526) with the cookie's value before doing any other processing of the follow up form:
add_filter( 'ninja_forms_submit_data', 'ninja_forms_submit_followup' );
function ninja_forms_submit_followup( $form_data ) {
$cookie_name = "nl_email";
if(!isset($_COOKIE[$cookie_name]) && $form_data['id'] == 2) {
$form_data['fields']['email_1519816442526']['value'] = $_COOKIE[$cookie_name]; // Update the submitted field value.
}
return $form_data;
}
Are the Submission Hooks the right point to integrate this feature? Or is this better done through a Custom Action? Are Custom Actions defined in the functions.php or someplace else? I couldn't find information on this in the Ninja Forms docs.
You need to see the NinjaDev Docs where they provided the way we can change the value of a field using JS. We need to pass the value and trigger the change event.
See the Explanation Here
I needed this too so I researched and achieved this. I know I am late but if someone benefits from this then it's worth sharing here.
Working code below:
<!-- HTML Code Starts -->
<form class="short-form" method='post'>
<input type="email" placeholder="Enter email" value="" id="shortEmail">
<input type="button" class="popup-class-name" name="Proceed" value="Proceed" onclick="passValue();">
</form>
<!-- HTML Code Ends -->
<!-- JS Script Starts -->
function passValue() {
var shortFormEmail, longFormEmail;
var fieldID = 11; // Target ID of the long form Email field
shortFormEmail = document.getElementById('shortEmail');
longFormEmail = shortFormEmail.value;
jQuery('#nf-field-' + fieldID).val(longFormEmail).trigger('change'); //from ninja Dev
// This will not work on any online IDE. Try it in actual ninja forms environment
}
<!-- JS Script Ends -->
This will only work in Ninja Forms environment.
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
Any help is certainly appreciated.Thank You
Also it's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
There's multiple ways of doing so. I personally would use AJAX. On a 'form submit', run a javascript function calling an AJAX request to a .php file to check the form information, all using post method. Calculate all the $_POST['variables'] checking for your defined errors. You would have an html element print the errors via AJAX request.
If there are 0 errors then in the request back return a string as so that your javascript function can look for if its ready to go. If ready to go, redirect the user to where ever you please.
AJAX is not hard and I only suggested the idea sense you put javascript in your tags.
Another method:
Having all your code on one .php file. When you submit the form to the same .php file check for the errors (at the top of the file). If $_POST['variables'] exist, which they do after you submit the form, you echo your errors in the needed places. If zero errors then you redirect the page.
I am having an issue with this login system, when ever I click the log in button, or the sign up button it re-directs me to a white page with writing on it, That being said it is interfering with my log in action.
Here is the code that I think is causing the issue,
<form method="POST" action="" accept-charset="UTF-8">
on line 16 of the HTML code, I tried to take that code out and it stopped the re-directing but the text boxes went out of place, and the white background/background-box was not there either,
Link, HERE
You want to use preventDefault() if this is a purely Javascript: you should be able to pass the button press event into the listener when you create it:
$('.login').on('click', function(e) {
e.preventDefault();
// Will be executed on press
}
<form method="POST" class="login" accept-charset="UTF-8">
If there's no JS involved in this scenario, then you want to get rid of the action parameter entirely – leaving it as the empty string will still cause it to redirect in some cases.
As Jonathan Lonowski explained above, when the log in / sign up button is clicked, the form will post the data to the page mentioned in the action= attribute. Since this attribute is empty in your form tags, it will re-load the same page, posting the data to itself.
The data will arrive in key=value variable pairs. The variable value will be the contents of the field, the variable name will be the value of the name="" attribute on the element.
For e.g., for this field:
<input id="fname" name="first" value="Bobby" />
The data will be received like this:
$fn = $_POST['first']; //value is Bobby, or whatever user enters
On your page containing the form, add a section at the top like this:
<?php
if (isset($_POST['fname']) == true){
$fn = $_POST['fname'];
echo "Received First Name: " . $fn;
die();
}else{
?>
//Your current page, in its entirety, goes here
<?php
} //close the PHP if statement
?>
That is how you deal with a normal HTML <form> construct.
However, if you wish to use AJAX to communicate with a PHP file without changing the page, then:
(1) There is no need to use a <form> construct, just use a DIV with an input button: <input type="button" id="sub_btn" value="Submit" />
(2) Trap the button press using standard js/jQuery:
$('sub_btn').click(function(){
var fn = $('#first').val();
//etc.
$.ajax(function(){
type: 'post',
url: 'my_php_processing_file.php',
data: 'fname=' +fn+ '&lname=' etc
});
});
In your PHP processor file, the data will be received thus:
<?php
$fn = $_POST['fname'];
$ln = $_POST['lname'];
//Do your MySQL lookup here...
echo 'Received ' .$fn. ' ' .$ln;
(3) IF you do use the form construct, you can still do everything as above, but you will need to suppress the default form action of navigating to the page specified in the action= attribute (an attribute setting of action="" will post data to and reload the same page you are on).
To suppress navigating to the page specified in action= (involves page refresh, even if just action=""), use event.preventDefault(), as follows:
$('#buttonID').click(function(event){
event.preventDefault();
//remainder of button click code goes here
});
Ok I am confused with php, javascript and html and dont know what to do. On researching on the internet, i found js is client side and php is server side. when a php file is run on the browser, it converts everything into html and the page is loaded. Now let me tell you guys what i am doing.
I have a php file that give me some stats from a particular url (in the sample i am just showing url)
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Result URL = www.example.com
The above code echoes the url which is www.example.com. I added a textbox to this code which i believe is javascript+html
<script>
function myFunction() {
$url=myurl.value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Here the result is same. only difference is that it has a textbox and button above the result.
When I enter another url in the textbox and press submit, it does nothing probably because the page is already loaded. I want to replace the result of www.example.com to the one which is entered in the textbox without changing the .php file. There will always be a default url in the .php file. whenever the file is opened in the browser, the default statistics will be shown... only when the user enters new url and clicks submit, the stats should change.
How can I achieve this? I am behind this since more than a couple of hours now and not sure how to get this done. Please help me.... Thank you.
EDIT
Can I have two .php files? one for the user to enter url and submit and another one to get the entered url and echo it? If yes, how? If I understand this logic, i can get a start for what I am doing.
I think you are trying to do more with your js function, but syntactically it is combining js and php. It should look like this
function myFunction() {
var url = document.getElementById('myurl').value;
}
Although this doesn't really do anything other then assign the content of the text box to a variable.
EDIT
<script>
function myFunction() {
document.getElementById('url').innerHTML = document.getElementById('myurl').value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<? $url = "www.example.com"; ?>
URL = <span id="url"><?= $url; ?></span>
natzim is correct if you are wanting to write the url back to the php file. If you use javascript to change the action of the form, it will submit to a different page.
//javascript
function myFunction() {
//this should change the page that loads after submit.
//If you want to go to a new page that the user enters, leave this code in...
//If not, remove it
document.getElementsByTagName("form")[0].action = document.getElementById("myUrl").value;
}
That is assuming you have a form tag somewhere (which you will need to submit the page). Also I am not sure this code will run if you use a submit and not a button. If you used a button instead you could append this to the code above to submit the form:
//This would be part of your myFunction if you used a button instead of a submit input
document.getElementsByTagName("form")[0].submit();
as per my comment -
this code is your old php:
<?
$url="www.example.com";
echo "URL = " .$url;
?>
and this is the php I suggested:
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
this would check the myurl input from that was submitted to the server and set the value of $url to its value if it existed then the $url variable would be echoed to the page under the inputs.
This code is assuming you are using the POST method rather than the GET method when your form was submitted.
**EDIT: **
To clarify - here is your page with the modifications I am suggesting. (Please ignore the javascript above as it seems you will not need it):
<form action='www.example.com' method='post'>
<input type="text" name="myurl" id="myurl">
<input type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
</form>