Wordpress jQuery initialize widgets.php area - php

Hey guys I'm having a huge problem initializing jQuery on the backend of WordPress (widgets.php). I'm building a widget to display some select options that can only be accessed through SOAP, so I had to ajaxify it using admin-ajax.php. Everything works perfectly on the front-end but when it comes to the backend it breaks completely.
function widget_inject() {
echo "<script>
jQuery(document).ready(function($) {
var ajaxurl = '".admin_url('admin-ajax.php')."';
var list_target_id = 'list-target'; //first select list ID
var list_select_id = 'list-select'; //second select list ID
var initial_target_html = '<option value=\"\">Please select category...</option>';
$('#'+list_target_id).html(initial_target_html);
$('#'+list_select_id).change(function(e) {
var selectvalue = $(this).val();
$('#'+list_target_id).html('<option value=\"\">Loading...</option>');
if (selectvalue == \"\") {
$('#'+list_target_id).html(initial_target_html);
} else {
$.ajax({url: ajaxurl,
data: {
action: 'parentcatajax1',
parentCat: selectvalue
},
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + \" \"+ thrownError);
}});
}
});
});</script>";
}
add_action('admin_enqueue_scripts','widget_inject');
^This is what I'm trying. I've tried admin-init, admin-head, admin-footer none of them seem to work.
& yeah I have...
add_action('wp_ajax_nopriv_parentcatajax1', 'parentCatCallback1');
add_action('wp_ajax_parentcatajax1', 'parentCatCallback1');
for my ajax function; it works perfectly on the front end.
I'm at a stand still for a client & can't figure out what to do.
Any suggestions? Thanks in advance!

Your printing your jQuery before wordpress has initialized jQuery. Wp_enqueue scripts is not the point where it starts printing the scripts onto the page. The below will clear your jQuery not defined error, let me know if there are more errors after this.
function widget_inject() {
echo "<script>
jQuery(document).ready(function($) {
alert('ready');//re-enter your code here
})(jQuery);
</script>";
}
add_action('admin_print_scripts','widget_inject', 100);//hook= 'admin_print_scripts'

Related

Can i add CSS style to a echo script alert message? [duplicate]

i am using smoke.js which allows to style the classic alert javascript windows.
All you have to do is place .smoke before the alert ie. smoke.confirm()
The issue I am having is with the ok/cancel callback, it isnt working for me.
This is the example the website shows.
`You can implement these the same way you'd use the js alert()...just put "smoke." in front of it.
The confirm() replacement, however, needs to be used just a little differently:
smoke.confirm('You are about to destroy everything. Are you sure?',function(e){
if (e){
smoke.alert('OK pressed');
}else{
smoke.alert('CANCEL pressed');
}
});
and the code I have is;
$(".upb_del_bookmark").click( function() {
if(smoke.confirm(delete_message)) {
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
It shows the style button and everything but when i click on OK it doesnt perform the function above, nothing happens.
So i rewrote it to
$(".upb_del_bookmark").click( function() {
if(smoke.confirm(delete_message, function(e))) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}}
But now when i click it doesnt even show anything
I am not a programmer, Help!!!!!
If you want to try it go to latinunit.org login with david:123321 and then go to a post and try to add it to your favourites
Update
I tried the following, it shows the window but it doesnt perform the function;
$(".upb_del_bookmark").click( function() {
smoke.confirm(delete_message, function(e) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}})
return false;
});
Here is the js file of the smoke script Link
When i click on cancel the following shows;
Uncaught TypeError: Property 'callback' of object # is not a
function Line:198
Uncaught TypeError: Property 'callback' of object # is not a
function Line:208
The following is what's on those linesof the smoke script;
finishbuildConfirm: function (e, f, box)
{
smoke.listen(
document.getElementById('confirm-cancel-' + f.newid),
"click",
function ()
{
smoke.destroy(f.type, f.newid);
f.callback(false);
}
);
smoke.listen(
document.getElementById('confirm-ok-' + f.newid),
"click",
function ()
{
smoke.destroy(f.type, f.newid);
f.callback(true);
}
);
The builtin javascript alert/confirm functions are synchronous, this is not. You need to handle the result of the confirm using the javascript callback pattern. You pass a function to the smoke.confirm() function which called when you need to respond to an action.
See the following code. The if around the smoke.confirm() has been removed and the handling code is wrapped in the function passed to the smoke.confirm() function.
$(".upb_del_bookmark").click( function() {
smoke.confirm(delete_message, function(e) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}
});
}
I highly recommend reading a little about the callback pattern in javascript. It's very common and understanding it will help you use this plugin and many others.

Search data from dynamically created table

I have created one application in that there is one text box for searching information from table. Although i have written the code when we enter the character in search text box, after accepting one character control goes out of textbox.
this is my code for searching`
<script type="text/javascript">
$(document).ready(function()
{
var minlength = 1;
$("#searchTerm").keyup(function () {
value = $(this).val();
if (value.length > minlength )
{
searchTable(value);
}
else if(value.length < minlength)
{
searchTable("");
}
});
});
function searchTable(value)
{
$.ajax({
type: "GET",
url: "dispatient.php",
data:({search_keyword: value}),
success: function(success)
{
window.location.href = "dispatient.php?search_keyword="+value;
$("#searchTerm").focus();
},
error: function()
{
alert("Error occured.please try again");
},
complete: function(complete)
{
$("#searchTerm").focus();
},
});
}
<input id="searchTerm" Type="text" class="search_box" placeholder="Search"
value = <?php echo $_GET['search_keyword'] ?> >
`
Please suggest to me..
thanks in advance..
value is default attribute of javascript try to change the variable name of value into something like searchData
In your success callback, you are redirecting the page to dispatient.php. I believe, this is the same page that has the search functionality. Once you redirect, the page is reloaded again and there is no point in writing:
$("#searchTerm").focus();
Since, you are already using AJAX, try loading the data from success on to your page through JavaScript/jQuery without reloading the page.
create one div and load your data in that instead of reloading entire page.
try something like this instead of ajax Call
<div id="searchResult"></div>
$("#searchResult").load("search.php?search_keyword=value",function(){
//your callback
});

AJAX post function not working properly after first call to the function

I'm totally new to jquery and AJAX, After trying hard for 5-6 hours and searching the solution I'm asking for the help.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit").live('click',(function() {
var data = $("this").serialize();
var arr = $("input[name='productinfo[]']:checked").map(function() {
return this.value;
}).get();
if(arr=='')
{
$('.success').hide();
$('.error').show();
}
else
{
$.ajax({
data: $.post('install_product.php', {productvars: arr}),
type: "POST",
success: function(){
$(".productinfo").attr('checked', false);
$('.success').show();
$('.error').hide();
}
});
}
return false;
}));
});
</script>
and HTML+PHP code is,
$json = file_get_contents(feed address);
$products = json_decode($json);
foreach(products as product){
// define various $productvars as a string
<input type="checkbox" class="productvars" name="productinfo[]" value="<?php echo $productvars; ?>" />
}
<input type="submit" class="submit" value="Install Product" />
<span class="error" style="display:none"><font color="red">No product selected.</font></span>
<span class="success" style="display:none"><font color="green">product successfully added to database.</font></span>
As I'm pulling the product information from feed, I don't want to refresh the page, that's why I'm using AJAX post method. Using above code "install_product.php" page is handling the string properly and doing its job properly.
The problem I'm facing is, when first time I check the check box and install the product it works absolutely fine, but after first post "Sometimes it work and sometimes it won't work". As new list is pulled from feed every first post is perfect after that I need to click install button again and again to do so.
I tested the code on different browsers, but same problem. What may be the problem?
(I'm testing the code on live host not localhost)
$.live is deprecated, consider using $.on() instead.
Which function is not executing after it executes once? $.live?
Also, it should be:
var data = $(this).serialize();
not
var data = $("this").serialize();
In your example, you are looking for an explicit tag called 'this', not a scope.
UPDATE
$(function () {
$(".submit")
.live('click', function(event) {
var data = $(this).serialize();
var arr = $("input[name='productinfo[]']:checked")
.map(function () {
return this.value;
})
.get();
if (arr == '') {
$('.success')
.hide();
$('.error')
.show();
} else {
$.ajax({
data: $.post('install_product.php', {
productvars: arr
}),
type: "POST",
success: function () {
$(".productinfo")
.attr('checked', false);
$('.success')
.show();
$('.error')
.hide();
}
});
}
event.preventDefault();
});
});
Is it possible, it is missing the value at arr and showing up the error or is it like it is making call but not returning or it is not reaching the call at all?
Do a console.log to deal with debuging and check things out in firefox / chrome and see what and where is the issue.

How do I send and receive vars with jquery and AJAX?

so lets say this is my jquery portion of the code:
$.ajaxSetup ({
cache: false
});
load() functions
var loadUrl = "load.php";
$("#load_basic").click(function(){
$("#result").load(loadUrl + "?language=php&version=5");
});
});
and this is "load.php"
<?php $_GET['language'] .= "cool"; $_GET['version']+=2; ?>
How do I return the processed language and version vars back to my #result div?
Sorry if I'm doing this wrong. Pretty comfortable in php and jquery, but ajax sort of confuses me and I haven't found any tutorials that really clicked.
I know I can echo these vars out, and that will return the contents of load.php into my div.. but that seems clunky, and I doubt that's the way people actually do it..
JQuery
$("#load_basic").click(function(){
$.get(loadUrl + "?language=php&version=5", function(data){
var obj = eval(data)
$("#result").html(obj.language + " " + obj.version)
});
});
PHP
<?php $_GET['language'] .= "cool"; $_GET['version']+=2;
echo "{\"language\" : \"".$_GET['language']."\",\"version\" : \"".$_GET['version']."\"" ?>
not tested and not bullet-proof, but the concept is here. Return somthing in your PHP that you can read back (i choose JSON)
" What If I'm echoing out two or three vars in php, and I want them to be seperated and echoed out to different divs.. "
I'm ASP and not PHP but I think the prinicple is the same.
I have this is my requesting page:
<script type="text/javascript">
$(document).ready(function(){
$("#list").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#list option:selected").val();
var bob = $("#list option:selected").text();
if (selected.length > 0) {
$.post("twopart.asp", { thing: selected, bob: bob }, function(data) {
var dataraw= data;
var dataarray = (dataraw).split("~~~");
var outone= dataarray["0"];
var outtwo= dataarray["1"];
var outthree= dataarray["2"];
$("#output1").html(outone);
$("#output2").html(outtwo);
$("#output3").html(outthree);
});
}
}
</script>
and this is in my processing page:
response.write bunch of stuff and ~~~
response.write bunch of stuff and ~~~
response.write more stuff
Sorry is the formatting is off- still learning how to do it.
Anyway, the "echoing page" echos its content with the three tildes stuck in there. Then I parse the return on the tildes and write different places.
Hope this is helpful.
The JSON answer by Grooveek is probably better.
try
$.ajax({
url:YOUR_URL,
dataType:'json',
type:'POST',
data:'&var1=value1&var2=value2',
beforeSend:function(){
//
},
success:function(response){
//complete
$('#container').html(response.result + ' ' + response.other);
}
});
in your php
$var1 = $_POST['var1'];
//your proccess
$result = array(
'result' => 'ok',
'other' => 'value'
);
echo json_encode($result);

Javascript (jQuery) - Problem with $.post

So, for some reason my script refuses to work, although it seems to be correct.
I tried using $.ajax instead, but not working with that either. Any ideas what's gone wrong?
<script>
$(document).ready(function() {
$('#saveForm .submit').click(function() {
var _user = $('#saveForm .user');
_userId = $('#saveForm .userId');
_password = $('#saveForm .password');
$('#saveForm').append('<p>Loading...</p>');
$.post("ajax/fetchPhotos.php", {user:_user, userId:_userId, password:_password}, function(data) {
alert(data);
});
return false;
});
});
</script>
In ajax/fetchPhotos.php i have this:
<?php
set_time_limit(0);
session_start();
require_once("includes/functions.php");
require_once("includes/pclzip.lib.php");
/*
Huge block of code here (commented out for the moment)
*/
echo "wut?";
So, when clicking .submit, it should send a request to fetchPhotos.php with three params and then alert "wut?". Right now the page hangs in chrome.. nothing happens. In firefox the page just refreshes. I do get one error in the console, but i only see it for a split second as the page refreshes directly.
Thanks,
Pete
you must use the .val() method to get the value of the inputs.
try this way:
<script>
$(document).ready(function() {
$('#saveForm .submit').bind('click', function() {
var
user = $('#saveForm .user').val(),
id = $('#saveForm .userId').val(),
password = $('#saveForm .password').val();
$('#saveForm').append('<p>Loading...</p>');
$.post("ajax/fetchPhotos.php", {user:user, userId:id, password:password}, function(data) {
alert(data);
});
return false;
});
});
</script>
It seems syntax related problem and also try with absolute url or can do in this way
new Ajax.Request("ajax/fetchPhotos.php", {
method: 'post',
parameters: 'id='+id,
onComplete: function(transport) {
alert(transport.responseText);
}
});

Categories