Where is my mistake in defining a function? - javascript

I want to make instant search using php and java,but I keep getting this error:
Uncaught ReferenceError: searchq is not defined
at HTMLInputElement.onkeydown
So i want every time on key down to activate a function which will search for results in database and display results as a div.I checked all things to make sure all is good.Link .js file to my php page and to my element.Checked my code spelling mistakes,and i cannot find where my mistake is.Here is my code:
jQuery(document).ready(function ($) {
function searchq(){
var searchTxt = $("input[name='food-search']").val();
$.post("Food-Groups-BG.php", {food_data_bg: searchTxt}, function(output){
$("#food-output").html(output);
});
}
});
<?php
mysqli_connect("localhost","myUsername","myPassword","dbName") or die ("could not connect");
if(isset($_POST['Food-Groups-BG.php'])){
$searchq = $_POST['Food-Groups-BG.php'];
$searchq = preg_replace("#[^0-9a-z]#i","".$searchq);
$query = mysqli_query("SELECT * FROM food_data");
$count = mysqli_num_rows($query);
if($count == 0){
$output = 'Няма намерени резултати!';
}else{
while($row = mysqli_fetch_array($query)){
$fname = $row['title'];
$output .= '<div>'.$fname.'</div>';
}
}
}
echo($output);
?>
<!--**************************************************************
HTML
***************************************************************-->
<p>Търсене на храни: <input type="text" name="food-search" id="food-search-id" onkeydown="searchq();"></p>
Any help is appreciated ! <3

By declaring the function searchq inside another function (which is passed to ready()) you only make searchq available inside that function, and not globally. Instead of using the onkeydown attribute in your HTML markup I would bind the event using jQuery.
jQuery(document).ready(function ($) {
function searchq(event) {
var searchTxt = $("input[name='food-search']").val();
$.post("Food-Groups-BG.php", {food_data_bg: searchTxt}, function(output){
$("#food-output").html(output);
});
}
$("#food-search-id").on("keydown", searchq);
});
To learn more about event handling you can check out the jQuery documentation, for example keydown and on.

Ali Yousuf is right. searchq() is only visible in the local scope of the jQuery(document).ready(function ($) {....}) handler function and cannot be accessed from anywhere outside. So you have to remove the jquery ready handler like Ali Yousuf said or define your function like this window.searchq = function() {...} to make it globally accessible

Related

wp_enqueue_script not working on AJAX called php file

I've got a complicated little problem here.
I'm building a WordPress plugin where I select a "parent" post (of a custom type that I made called 'step') and then an AJAX function shows a new select bar with all of the children of that parent. I do this by outputting the new and elements in the PHP file that's called in the AJAX function. This works, but now I want to repeat the process to run a function from the same JQuery file when this new outputted element is added to the page. (See Javascript code)
Main php plugin file (in a folder within the plugin directory):
<?php
/*
Plugin Name: n8jadams Step by Step Plugin (WIP)
Plugin URI:
Description:
Author: Nathan James Adams
Author URI: http://nathanjamesadams.com
Version: 0.0.1a
*/
//Exit if accessed directly
if(!defined('ABSPATH')) {
exit;
}
//My custom post type, it works fine
require_once(plugin_dir_path(__FILE__).'n8jadams-step-funnel-cpt.php');
require_once(plugin_dir_path(__FILE__).'n8jadams-ajax.php');
//Add my javascript
function n8jadams_init_javascript() {
wp_register_script('n8jadams_javascript', plugin_dir_url(__FILE__).'n8jadams-scripts.js', array('jquery'),'1.1', false);
wp_enqueue_script('n8jadams_javascript');
}
add_action('wp_enqueue_scripts', 'n8jadams_init_javascript');
//Adds a plugin menu to the wordpress sidebar
function n8jadams_add_plugin_menu() {
add_menu_page('', 'Steps Settings', 4, 'steps-settings', 'n8jadams_steps_settings', '');
}
add_action('admin_menu', 'n8jadams_add_plugin_menu');
//The actual function for the menu page
function n8jadams_steps_settings() {
//Access the database and the tables we want
global $wpdb;
$posts = $wpdb->prefix.'posts';
//Get the user id
$user = wp_get_current_user();
$userid = $user->ID;
//Initialize javascript (it works here!)
n8jadams_init_javascript();
/* Get all the parents */
$parentsquery = "
SELECT `ID`, `post_title`
FROM $posts
WHERE `post_author` = $userid
AND `post_parent` = 0
AND `post_status` = 'publish'
AND `post_type` = 'step'
";
$parentsarray = $wpdb->get_results($parentsquery);
?>
<h4>My Forms:</h4>
<select id="parentselect">
<option id="-1"> - Select Your Step Form - </option>
<?php
//output the parents
for($i=0;$i<sizeof($parentsarray);$i++) {
echo '<option id="'.$parentsarray[$i]->ID.'">'.$parentsarray[$i]->post_title.'</option>';
}
?>
</select>
<div id="displayChildren"></div>
<?php
}
?>
Javascript (n8jadams-scripts.js):
(function($){
$('#parentselect').change(function(s) {
var thisID = s.target[s.target.selectedIndex].id;
var outputDisplay = document.getElementById('displayChildren');
if(thisID != '-1') {
$.ajax({
type: 'POST',
url: 'admin-ajax.php',
data: {
action: 'n8jadams_get_children',
id: thisID
},
success: function(response){
if(response == "") {
outputDisplay.textContent = "This form has no children. Add them in the sidebar menu of this step form.";
} else {
outputDisplay.innerHTML = response;
}
},
error: function(errorThrown) {
alert(errorThrown);
}
});
} else {
outputDisplay.textContent = '';
}
});
// I want this function to work
/*
$('#childselect').change(function(t) {
console.log("test");
});
*/
})(jQuery);
PHP file called by AJAX (n8jadams-ajax.php):
<?php
function n8jadams_get_children() {
//Get the id of the parent
$parent_post_id = $_POST['id'];
//Sanitize the input (Added after question was answered)
$parent_post_id = preg_replace("/[^0-9]/","",$parent_post_id);
//Access database
global $wpdb;
$posts = $wpdb->prefix.'posts';
$user = wp_get_current_user();
$userid = $user->ID;
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
//Retrieve the children associated with this parent
$childrenarray = $wpdb->get_results($childrenquery);
//Initialize Javascript (it doesn't work here!)
n8jadams_init_javascript();
if(!empty($childrenarray)) { ?>
<h4>My Steps:</h4>
<select id="childselect">
<option id="-1"> - Select Your Step - </option>
<?php
//output the children of the parent
for($i=0;$i<sizeof($childrenarray);$i++) {
echo '<option id="'.$childrenarray[$i]->ID.'">'.$childrenarray[$i]->post_title.'</option>';
} ?>
</select>
<?php wp_die();
}
}
add_action('wp_ajax_n8jadams_get_children', 'n8jadams_get_children');
add_action('wp_ajax_nopriv_n8jadams_get_children', 'n8jadams_get_children');
?>
Screenshot of Plugin Menu
I cannot figure out why my javascript file isn't working in the PHP file that's called by AJAX. Maybe the vast wisdom of the StackOverflow can help me. Thanks for the help in advance. :)
You are hooking into wp_enqueue_scripts, which is only run for the frontend of Wordpress (the part the average visitor sees). If you want to load a script into wp-admin, the backend of Wordpress, use the admin_enqueue_scripts action.
Since this code does not work in /wp-admin/, you don't need to use admin_enqueue_scripts. I guess the whole problem would be that you are attaching a handler to $('#childselect'), while no such element exists on the page at that time. Use deferring with $(..).on(..):
$(document).on('change', '#childselect', function(e) {
//Black magic
});
Side note: As already mentioned in the comments, the following part contains an unsanitised variable which will allow an attacker to perform sql injections.
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
Use WP_Query if at all possible. If this is only used from the backend of Wordpress, don't use wp_ajax_nopriv_*, because users that are not logged in into your site have no right to use that anyway.

How properly proccess jQuery AJAX in WordPress plugin

I'm trying to add ajax autosave to my settings page in plugin and made this code:
<?php
function cfgeo_settings_javascript() { ?>
<script type="text/javascript" >
(function($){
$(document).ready(function(){
$("input[id^='cf_geo_'], select[id^='cf_geo_'], textarea[id^='cf_geo_']").on("change keyup", function(){
var This = $(this),
name = This.attr("name"),
value = This.val(),
data = {};
data['action'] = 'cfgeo_settings';
data[name] = value;
console.log(data);
console.log(ajaxurl);
$.post(ajaxurl, data).done(function(returns){
console.log(returns);
});
});
});
}(window.jQuery));
</script> <?php
}
add_action( 'admin_footer', 'cfgeo_settings_javascript');
function cfgeo_settings_callback() {
global $wpdb; // this is how you get access to the database
var_dump($_POST);
if (isset($_POST)) {
// Do the saving
$front_page_elements = array();
$updates=array();
foreach($_POST as $key=>$val){
if($key != 'cfgeo_settings')
update_option($key, esc_attr($val));
}
echo 'true';
}
else
echo 'false';
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_cfgeo_settings', 'cfgeo_settings_callback');
?>
I find problem that everytime I want to send this simple ajax request I get 0 what is realy enoying.
Here is Console Log when I try to made some change in select option box:
Object {action: "cfgeo_settings", cf_geo_enable_ssl: "true"}
admin.php?page=cf-geoplugin-settings:1733 /wp-admin/admin-ajax.php
admin.php?page=cf-geoplugin-settings:1736 0
What's wrong in my ajax call or PHP script?
I need to mention that both codes are in the one PHP file.
You should have to follow guideline of WordPress ajax method by this admin ajax reference. Please follow this.
https://codex.wordpress.org/AJAX_in_Plugins
Here is a working example with notes included in the comments, there are a lot of don't does in your code and this example addresses those concerns in the code comments.
https://gist.github.com/topdown/23070e48bfed00640bd190edaf6662dc

PHP echo within a Javascript file

So the problem is as follows:
I want to dynamically echo a javascript thing with PHP. This echo needs to be (or work with) another javascript file where the echo'd value is used to call a function when the ID is clicked.
However when the page is loaded and the document.getElementById things are added (and they are correct) when the element is clicked, the console tells me that fplaying is undefined
PHP File
<?php
mysql_connect ("localhost", "root", "") or die ("We couldn't connect!");
mysql_select_db ("dr");
mysql_query ("SELECT * FROM songs");
$result = mysql_query ("SELECT * FROM songs");
while ($row=mysql_fetch_array($result)) {
$source = $row ['audiosource'];
echo "
document.getElementById('$source').onclick = fplaying
";
}
?>
JS File
$(function() {
console.log( "ready!" );
function fplaying () {
alert ("test");
}
});
I am not sure if this can be done with php and this is probably not the answer you are looking for.But long comments are not recommended so I just posted as an answer.
It is possible to do, I have done when I was new to Web Developments (With ASP.Net), but still this indicates an improper architecture. JavaScript, that you are using, is a client side script and thus should be accompanied with proper AJAX structure to do such thing. Server should only be responsible to send proper response based on request, not dictate how a page should behave on client side.
Some thing like -
var play = function(){
...//code to play
};
$.ajax({
url: ..//url to php page
type: ...
...,
success: function(data){
...//data responded by php page
play();
},
error: function(){
}
});
I used syntax for jQuery. There are other libraries too.
This is very simple. Try this.
echo " <script> ";
echo "document.getElementById('$source').onclick = fplaying ";
echo "</script>";
I don't think
document.getElementById('$source').onclick = fplaying
will find the function as fplaying is undefined.
Try:
var fplaying = function() {
alert ("test");
}
instead of
function fplaying () {
alert ("test");
}
As in the JS you are printing through PHP only sets the onclick event for an element with that ID which exists somewhere else on the page I think. So, much better way of doing this would be define a class in that clickable item
<button id='<?php echo $source; ?>' class='click-me'>Click Me</button>
Then in JS use this:
$('.click-me').on('click',function(){
alert($(this).attr('id'));
});
Let's suppose you have a collection, coming from a db query: $collection and consists of associative arrays, with a unique id
Now, you are obviously going to display these objects and ask for a user to do something with them, your fplay function. What you must do, is echo whichever parts of the items you need and somehow pass in the html the item id.
So, the php part which will construct your html would be something like:
echo "<ul>";
$id = $item['id'];
foreach ($collection as $item){
echo '<li><a onclick="return fplaying(' + $id + ')" href="#" class="btn"></li>';
}
echo "</ul>";
Then, your js function would use the id as a parameter and do whatever you need:
function fplaying (id) {
alert ("your id is " + id);
}
$source = $row ['audiosource'];
echo '<div id="'.$source['id'].'" class="sourceDiv">'.$source['name'].'</div>';
then go to your js file and add this --you don't have to do that in php
$(document).ready(function(){
$('.sourceDiv').click(function(){alert($(this).attr('id'))});
});
Obviously your declaration of fplaying() is delayed and in addition its locally defined, only.
$(function() {
console.log( "ready!" );
function fplaying () {
alert ("test");
}
});
In that code fplaying is dropped as soon as the outer function has finished. Try binding that fplaying to your window instead.
$(function() {
console.log( "ready!" );
window.fplaying = function() {
alert ("test");
};
});
To illustrate this additionally:
function a() {
function fplaying() {
alert("Hi");
}
fplaying();
}
a();
will display alert box.
function a() {
function fplaying() {
alert("Hi");
}
}
a();
fplaying();
won't show alert box for fplaying() is visible in scope of a(), only, and thus it's undefined as in your case.
function a() {
window.fplaying = function() {
alert("Hi");
};
}
a();
fplaying();
will show alert box for now fplaying() is declared as method of object window more or less serving as global scope, too.
For it's delayed using $(function() { ... }); make sure invoking code as rendered by PHP isn't running before document has loaded. But that doesn't seem to be an issue according to your spare information on context.
Okay, from what I understand of your problem:
Your php creates a html file that has an element with id="the value of $source" and you want it to play a sound on click.
If you want to create a piece of javascript like you did, you could try:
echo ""
while ($row=mysql_fetch_array($result)) {
$source = $row ['audiosource'];
echo "
document.getElementById('$source').onclick = fplaying()
";
}
echo "</script>"
That should make the browser recognize the script as javascript and execute it. Make sure this is printed to the html after the part of the page with the elements you're referring to is printed to the html. Otherwise the script might run before the relevant part of the page is loaded in the browser.

JQUERY is not loading properly or is it my code that is wrong? [duplicate]

This question already has answers here:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead
(7 answers)
Closed 9 years ago.
I am trying to use jQuery methods for ajax to create a dropdown menu.
Using this jQuery code:
JAVASCRIPT:
<SCRIPT>
$("select[name='carid']").on("change", function() {
$.post(
"execute.php",
{ carid: $("#carid").val() },
function(data) {
$("available").append(data);
}
);
});
</SCRIPT>
execute.php :
<?php
$carid = $_POST['carid'];
$result = mysql_query("SELECT mID, mName FROM Model WHERE cID = '$carid' ");
$select = "<select>";
while ($row = mysql_fetch_array($result))
{
$mID = $row['mID'];
$mName = $row['mName'];
$select+= "<option value='".$mID."'>" .$mName. "</option>";
}
$select += "</select>"
echo $select;
?>
Unfortunately I am getting this error on loading in console event.returnValue is deprecated. Please use the standard event.preventDefault() instead. Any help is much appreciated.
The problem is here I think:
$("available").append(data);
What is available here? It won't append data any where.
Since you haven't shown us your html so assuming that it may be an element with id or class set to available so it should be $(".available").append(data); or $("available").append(data); depending upon the element to which you want to append.
UPDATE
since you specified that it's a <div id="available"> so try $("#available").append(data); instead of $("available").append(data);
Here is the complete script
<script>
$("select[name='carid']").on("change", function() {
$.post(
"execute.php",
{ carid: $("#carid").val() },
function(data) {
console.log(data); // just for testing
$("#available").append(data);
}
);
});
</script>
If that doesn't work either, check your console and post the output here.
replace this line and try again
$select += "</select>";
and if $("available").append(data); in this line available is class than use .available and if it an id than use #available
See here
event.returnValue is deprecated. Please use the standard event.preventDefault() instead
This is just a warning and can be safely ignored for the time being. It has been changed in jQuery 1.11

php array to external page using jquery

I have a php page to creates a multi-dimentional array called $results.
I would like to:
catch submit of a form button
override default behavior of the submit using jQuery
copy and process $results on separate php using $.post
I have this which is not currently working and am not sure why?:
<form id='download_to_excel' method="post">
<input type="image" name="submit" value="submit" id='xls_download_button' src='images/common/buttons/download.png'>
</form>
<?php
$json_results = json_encode($results);
?>
<script type='text/javascript'>
$(document).ready(function(){
alert($json_results);
$("#xls_download_button").click(function(e){
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
});
</script>
When selecting the xls_download_button, the alert() never fires nor does any data get passed to export_data_to_excel.php
The export_data_to_excel.php file has the following:
<?php
$results = json_decode($_POST['json_data']);
#include the export-xls.class.php file
require_once('export-xls.class.php');
$date = date('Y-m-d');
$filename = "contacts_search_$date.xls"; // The file name you want any resulting file to be called.
#create an instance of the class
$xls = new ExportXLS($filename, $results);
#lets set some headers for top of the spreadsheet
$header = "Searched Contact Results"; // single first col text
$xls->addHeader($header);
#add blank line
$header = null;
$xls->addHeader($header);
$header = null;
$row = null;
foreach($results as $outer){
// header row
foreach($outer as $key => $value){
$header[] = $key;
}
// Data Rows
foreach($outer as $key => $value){
$row[] = $value;
}
$xls->addRow($header);//add header to xls body
$header = null;
$xls->addRow($row); //add data to xls body
$row = null;
}
# You can return the xls as a variable to use with;
# $sheet = $xls->returnSheet();
#
# OR
#
# You can send the sheet directly to the browser as a file
#
$xls->sendFile();
?>
I do know that the $json_results does display proper JSON encoded values when echoed. But from there are not sure why the rest of the javascript does not run; the alerts never fire nor does the JSON data get passed?
Can you see why this isn't working?
Your PHP-supplied json is not stored as a javascript variable in your js.
$(document).ready(function(){
var json_results = <?php echo $json_results; ?>;
...
This code shouldn't run:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
It is invalid (the ; doesn't belong there). Try this code:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results});
}
Right now you are just setting a php variable called $results you need to transfear it to you javascript.
<script type="text/javascript">
// set javascript variable from php
var $results = "<?php echo json_decode($json_data); ?>";
</script>
For sure you have an error in your javascript code (you were not closing the parenthesis after $.post), should be:
$(document).ready(function() {
alert($json_results);
$("#xls_download_button").click(function(e) {
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls() {
$.post('./libs/common/export_data_to_excel.php', {
json_data: json_results
});
}
});
Then you should assign your JSON to a javascript variable inside document.ready
$(document).ready(function() {
var json_results = <?php echo($json_results);?>;
You can't pass a PHP variable to the JavaScript like that: there live in totally different worlds. Use Ajax to get the JSON data from JS.

Categories

Resources