Include js files in Custom Wordpress Plugin - wordpress

I'm trying to develop my own Wordpress Plugin, but somehow I can't include javascript files in it. Before I concidered to ask this question here, i've done a lot of research, but none of it was fixing my problem. I've read a lot about wp_register_script() and wp_enqueue_script(), and also that I don't have to include both, so I decided to only use wp_enqueue_script().
The javascript file is located in wp-content/snappy-list-plugin/js/public/snappy-wordpress-plugin.js, and the index file is located in wp-content/snappy-list-plugin/snappy-wordpress-plugin.php.
In the snappy-wordpress-plugin.php file I have:
function mslb_public_scripts(){
wp_enqueue_script('custom_js', plugins_url( '/snappy-list-plugin/js/public/snappy-wordpress-plugin.js', __FILE__ ), array('jquery'), '', true);
}
which seems to be oke, but it doesn't include the file.
On top of the file I have:
add_action('wp_enqueue_scripts', 'mslb_public_scripts');
Can somebody help me with this?!
I tried to add wp_register_script(), but it doesn't work
add_action('admin_enqueue_scripts', 'mslb_public_scripts');
function mslb_public_scripts(){
wp_enqueue_script('custom_js', plugins_url( '/snappy-list-plugin/js/public/snappy-wordpress-plugin.js', __FILE__ ), array('jquery'), '', true);
}
snappy-wordpress-plugin.js file:
jQuery(document).ready(function($) {
var wpajax_url = document.location.protocol + '//' + document.location.host + '/wp-admin/admin-ajax.php';
var email_capture_url = wpajax_url += '?action=swp_save_subscription';
$('form.swp_form').bind('submit', function(){
$form = $(this);
var form_data = $form.serialize();
$.ajax({
'method' : 'post',
'url' : email_capture_url,
'data' : form_data,
'dataType' : 'json',
'cache' : false,
'success' : function( data, textStatus){
if(data.status == 1){
$form[0].reset();
alert(data.message);
} else {
var msg = data.message + '\r' + data.error + '\r';
$.each(data.error, function(key, value){
msg += '\r';
msg += ' - ' + value;
});
alert( msg );
}
},
'error' : function(jqXHR, textStatus, errorThrown){
}
});
//stop the form from submitting normally
return false;
});
});```

The right action is wp_enqueue_scripts
add_action('wp_enqueue_scripts', 'mslb_public_scripts');
function mslb_public_scripts(){
wp_register_script('custom_js', plugins_url('/js/public/snappy-wordpress-plugin.js',__FILE__ ), array('jquery'), '', true);
wp_enqueue_script('custom_js');
}

Related

Modernizr.load Deprecated. Yepnope.js Deprecated. Current Alternatives?

Modernizr.load and yepnope.js have both been deprecated.
How do we conditionally call javascript files now?
Could you give me a example?
This is the javascript that I want to load
var BubbleShoot = window.BubbleShoot || {};
BubbleShoot.Game = (function($){
var Game = function(){
this.init = function(){
$(".but_satart_game").bind("click", startGame);
};
var startGame = function(){
console.log("dentro de startGame en game.js");
//$(".but_satart_game").unbind("click");
//BubbleShoot.ui.hideDialog();
};
};
return Game;
})(jQuery);
And modernizr's code:
Modernizr.load({
load: "_js/game.js",
complete: function(){
$(function(){
var game = new BubbleShoot.Game();
game.init();
})
});
You can dynamically add scripts to a page with document.createElement and adding it to the DOM with .async = true and call your game's init() function from the script's load event-listener:
function addGameScriptToPage() {
const scriptElement = document.createElement('script');
scriptElement.async = true;
scriptElement.addEventListener( 'load', function( e ) { new BubbleShoot.Game().init(); } );
scriptElement.src = '__js/game.js';
document.head.appendChild( scriptElement );
}
You can make it more generic by passing the script's URL as a parameter and returning a Promise for the load event-listener, so pages using this function can have their own custom load logic:
function addScriptToPage( scriptUrl ) {
return new Promise( ( resolve, reject ) => {
const scriptElement = document.createElement('script');
scriptElement.async = true;
scriptElement.addEventListener( 'load', function( e ) {
resolve( e );
);
scriptElement.addEventListener( 'error', function( e ) {
reject( e );
);
scriptElement.src = scriptUrl;
document.head.appendChild( scriptElement );
} );
}
Used like so:
async function doStuff() {
const shouldLoadGame = prompt( "Would you like to play a game of global thermonuclear war?" );
if( shouldLoadGame ) {
try {
await addScriptToPage( "__js/game.js" );
// This code runs when the 'load' event listener calls `resolve(e)`.
const g = new BubbleShoot.Game();
g.init();
}
catch( err ) {
// This code runs when the 'error' event listener calls `reject(e)`.
alert( "Game failed to load." ); //
}
}
}
...and this is pretty much how the require() function for loading modules on-demand works, btw.

Autocomplete Text box in Asp.net MVC

I am working in asp.net MVC. I need a text box to autocomplete by ajax function.
Ajax function can't call values from the controller.
Here is the code:
$( "#birds" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "search.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
} );
},
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
} );
Here is the complete code:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
var cache = {};
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "Your Controller URL", request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
}
});
} );
</script>
Your Controller should response the data in JSON format like:
[{"id":"Locustella naevia","label":"Common Grasshopper Warbler","value":"Common Grasshopper Warbler"},{"id":"Locustella certhiola","label":"Pallas`s Grasshopper Warbler","value":"Pallas`s Grasshopper Warbler"}]
Your JSON should be dynamic, otherwise, it will respond you the same JSON. You should filter your data in your controller before responding back to the AJAX and the data always in the JSON format.
You can find more about autocomplete on https://jqueryui.com/autocomplete/
& https://jqueryui.com/autocomplete/#remote-with-cache

wordpress rest api issue in inserting post meta value while inserting post

Here is my code. I have an issue while inserting a new post using WordPress REST API. With given code, Post inserted successfully but the post meta field remains empty.
<script type="text/javascript">
jQuery( document ).ready( function ( $ ) {
//Create Cause
$( '#frm_create_campaign' ).on( 'submit', function(e) {
e.preventDefault();
var title = $('#cmp_title').val();
var content = $('#post_submission_content').val();
var meta = {'gdlr-current-funding':"0"};
var status = 'draft';
var data = {
title: title,
content: content,
meta: meta
};
$.ajax({
method: "POST",
url: POST_SUBMITTER.root + 'wp/v2/cause',
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( POST_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( POST_SUBMITTER.failure );
}
});
});//End Create Cause
</script>

Correct Way to Pass Script to PhantomJS via PHP-PhantomJS?

I'm learning PhantomJS and PHP-PhantomJS. I want to pass a script to PhantomJS.
Currently I'm trying this:
$client->getEngine()->addOption('/Applications/myWebApp/js/phantomtest.js');
$request = $client->getMessageFactory()->createRequest('http://www.jonnyw.me/', 'GET');
$response = $client->getMessageFactory()->createResponse();
$client->send($request, $response);
if ($response->getStatus() === 200) {
echo $response->getContent();
}
I'm getting an empty $response object back after the call to $client->send($request, $response).
Here's the contents of my test script ('phantomtest.js'):
var page = require('webpage').create();
page.open('http://www.jonnyw.me', function(status) {
console.log("Status: " + status);
if(status === "success") {
page.render('example.png');
}
phantom.exit();
});
I think this must be the relevant page in the docs: http://jonnnnyw.github.io/php-phantomjs/4.0/4-custom-scripts/
Here is code that is working:
In PHP:
$location = '/Applications/myWebApp/js/';
$serviceContainer = ServiceContainer::getInstance();
$procedureLoader = $serviceContainer->get('procedure_loader_factory')
->createProcedureLoader($location);
$client->getProcedureLoader()->addLoader($procedureLoader);
$request = $client->getMessageFactory()->createRequest();
$client->setProcedure('phantomJStest');
$response = $client->getMessageFactory()->createResponse();
$client->send($request, $response);
if (($response->getStatus() === 200) || ($response->getStatus() == 'success')){
// Dump the requested page content
echo $response->getContent();
}
In the proc file phantomJStest.proc:
phantom.onError = function (msg, trace) {
console.log(JSON.stringify({
"status": msg
}));
phantom.exit(1);
};
var system = require('system');
var uri = "http://www.jonnyw.me";
var page = require('webpage').create();
page.open(uri, function (status) {
console.log(JSON.stringify({
"status": status
}));
if (status === "success") {
page.render('example.png');
}
phantom.exit(1);
});

select2 how to display data

I want to use select2 in my Symfony project but still do not know how to display results. My code for frontend is
$(".js_search").select2({
ajax: {
url: "{{ path('search') }}",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
console.log(data.items);
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) {
return markup;
}, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
});
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = '<div class="clearfix">' +
'<div class="col-sm-1">' +
'<img src="' + repo.owner.avatar_url + '" style="max-width: 100%" />' +
'</div>' +
'<div clas="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-6">' + repo.full_name + '</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
'<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
'</div>';
if (repo.description) {
markup += '<div>' + repo.description + '</div>';
}
markup += '</div></div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.full_name || repo.text;
}
g
and for the backend
public function searchAction()
{
$response = new Response();
$response->setContent(json_encode(
[
'items' =>
[
'id' => 1,
'text' => 'test'
]
]
));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
I dont know how should $response looks like or how to show returned data in view.
Somebody know the answer ?
I am using this https://select2.github.io/
Your response should be a JSON array with the elements Select2 uses to create the option tags for the dropdown.
In your case the content in the reposnse to your AJAX request would be:
[{"id": 1, "text":"test"}]
Select2 will then update the element identifed by the JQuery Selector $(.js-search) with the options and values in your response.

Resources