I got a problem with getting my working php/javascript/ajax application into my wordpress theme. I use it for my users so not in the admin panel.
What I already did:
I called the JavaScript file in my functions.php. And its loading fine. But when I open my main php file it doesn't make the ajax call.
I have 4 pages: response.php
response.php (This one is working fine.)
single-page.php (This one is also working fine.)
voedingsschema.js (This one is working without wordpress.)
function.php (I don't know if I did this right.)
I hope I've given enough information.
The function.php code from my template looks like this:
function fitnesszone_child_scripts(){
wp_enqueue_script( 'voedingsschema js', get_stylesheet_directory_uri() . '/js/voedingsschema.js');
}
add_action( 'wp_enqueue_scripts', 'fitnesszone_child_scripts');
The javascript code:
<script type="text/javascript">
$(document).ready(function() {
//##### send add record Ajax request to response.php #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val()==='')
{
alert("Please enter some text!");
return false;
}
$("#FormSubmit").hide(); //hide submit button
$("#LoadingImage").show(); //show loading image
var myData = {
content_txt: $('#contentText').val(),
content_txt2: $('#contentText2').val(),
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "http://website.com/wp-content/themes/fitnesszone-child/response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
//##### Send delete Ajax request to response.php #########
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
$(this).hide(); //hide currently clicked delete button
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "http://website.com/wp-content/themes/fitnesszone-child/response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut();
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
</script>
Let's try this way for implementing ajax in WordPress
functions.php
function fitnesszone_child_scripts(){
wp_enqueue_script( 'voedingsschema_js', get_stylesheet_directory_uri() . '/js/voedingsschema.js' );
wp_localize_script( 'voedingsschema_js', 'voedingsschema_vars', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'fitnesszone_child_scripts' );
function fitnesszone_implement_ajax(){
include( TEMPLATEPATH .'/response.php');
}
add_action( 'wp_ajax_fitnesszone', 'fitnesszone_implement_ajax' );
add_action( 'wp_ajax_nopriv_fitnesszone', 'fitnesszone_implement_ajax' );
voedingsschema.js
var contentTxt: $('#contentText').val();
var contentTxt2: $('#contentText2').val();
$.ajax({
url: voedingsschema_vars.ajaxurl,
type: 'POST',
data: 'action=fitnesszone&context_txt=contextTxt&context_txt2=contextTxt2,
success: function(results){
// YOUR CODE
},
});
Don't wrap javascript code in voedingsschema.js into <script></script> tag. This is reserved when you put javascript code inside your HTML
Related
I'm trying to add jQuery to the javascript.js file for a child of woodmart theme, but I keep getting "javascript.js:131 Uncaught ReferenceError: jQuery is not defined".
javascript.js
(function($){
jQuery(document).ready(function($) {
//cart_actions parent container
//for POST requests when user saves a cart
clickparent = document.querySelector(".cart-actions");
clickparent.addEventListener("click", function(e) { // e = event object
let carts = JSON.parse(window.localStorage.getItem('yithPOS_carts'));
if (e.target && (e.target.className == "cart-action cart-action--suspend-and-save-cart cart-action--with-icon") || e.target.className == "cart-action__icon yith-pos-icon-saved-cart") {
// Use ajax to do something...
var postData = {
action: 'wpa_49691',
my_var: 'carts',
}
$.ajax({
type: "POST",
data: postData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
console.log("Cart saved to database.");
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
//pos_current_Cart_buttons parent container
//for GET requests when user views saved carts
viewcartparent = document.querySelector(".yith-pos-cart__buttons");
viewcartparent.addEventListener("click", function(e) { // e = event object
if (e.target && (e.target.className == "yith-pos-cart__buttons-saved-carts")) {
// Use ajax to do something...
var getData = {
action: 'wpa_49692',
my_var: 'my_data',
}
$.ajax({
type: "GET",
data: getData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
let total;
for(item in response){
total += item[lineTotal];
}
$(".yith-pos-cart__savedcarts").append('</div><i class="yith-pos-cart__savedcart"></i><div class="cart-saved__name"><div class="cart-saved__name__id">' + response['id'] + '</div><div class="cart-saved__name__customer">' + response['cartitems']['names'] + '</div></div><div class="cart-saved__num_of_items">' + response['cartitems'].size + '</div><div class="cart-saved__status">Pending Payment</div><div class="cart-saved__total">'+ total + '</div><button class="btn btn-primary"><i class="yith-pos-icon-refresh"></i> load</button></div>');
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
// Handler for .ready() called.
});
})(jQuery);
I've also tried enqueuing jquery with wp_enqueue_script and passing jquery in an array to the javascript file, neither changed anything.
functions.php:
wp_enqueue_script('jquery');
//First enqueue your javascript in WordPress
function save_cart_enqueue_scripts(){
//Enqueue your Javascript (this assumes your javascript file is located in your plugin in an "includes/js" directory)
wp_enqueue_script( 'javascript.js', plugins_url('https://cigarchiefstg.wpengine.com/wp-content/themes/woodmart-child/yith-pos-additions/javascript.js', dirname(__FILE__) ), array( 'jQuery' ));
//Here we create a javascript object variable called "youruniquejs_vars". We can access any variable in the array using youruniquejs_vars.name_of_sub_variable
wp_localize_script( 'javascript', 'javascript_vars',
array(
//To use this variable in javascript use "youruniquejs_vars.ajaxurl"
'ajaxurl' => admin_url( 'javascript_vars.ajaxurl' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'save_cart_enqueue_scripts' );
//This is your Ajax callback function
function cart_save_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
update_option('saved_carts', $my_var);
//Create the array we send back to javascript here
$return_array = array();
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $return_array );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49691', 'cart_save_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49691', 'cart_save_callback_function' );
function cart_view_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
//Create the array we send back to javascript here
$carts = get_option('saved_carts');
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $carts );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49692', 'cart_view_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49692', 'cart_view_callback_function' );
Edit: Issues with POS items:
first check if jquery is correctly loaded on you wp website.
I suggest using this syntax for jQuery:
(function($){
$(document).ready(function(){
//your code
})(jQuery);
It is a Wordpress installation using Gravity Forms which I know pretty well, however what I am trying to do is get the value of a hidden input and use it in a PHP script to get more data about.
JS CODE: http://pastebin.com/5FFf4ESb
jQuery(function($){
$(document).bind('gform_post_render', function(event, form_id){
if (form_id == 1) {
var uploader = $("#gform_drag_drop_area_1_1");
var uploads = $("#gform_uploaded_files_1").val();
alert(uploads);
uploader.on("drop", function() {
$.ajax({
url: mp3_object.ajaxurl,
async: true,
type: "POST",
data: {
action : 'ajax_mp3',
files : uploads,
},
success: function(response) {
//results = jQuery.parseJSON(response);
alert(response);
}
});
});
}
});
});
PHP CODE: http://pastebin.com/H2Cd1Dfd
function enqueue_mp3_scripts_init($form, $is_ajax) {
if ( $is_ajax ) {
wp_enqueue_script( 'mp3-script', plugin_dir_url(__FILE__) . 'js/scripts.js', array('jquery'), 1.0 ); // jQuery will be included automatically
wp_localize_script( 'mp3-script', 'mp3_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
}
}
add_action('gform_enqueue_scripts', 'enqueue_mp3_scripts_init', 10, 2);
function ajax_mp3_func() {
if( isset($_POST['files']) ) {
echo $_POST['files'];
}
die(); // stop executing script
}
add_action( 'wp_ajax_ajax_mp3', 'ajax_mp3_func' ); // ajax for logged in users
add_action( 'wp_ajax_nopriv_ajax_mp3', 'ajax_mp3_func' ); // ajax for not logged in users
The issue I am having is that the file upload uses plupload AJAX request and it is performing asynchronously with my JS code so my code fires before the value of the hidden field var uploads is set and it returns empty before being sent via my AJAX request to the PHP File.
I don't know enough about AJAX to know how to isolate and run my AJAX request after the hidden value is set.
I want to get a variable from ajax to php. I'm using the Yii framework.
So my problem is, when I want to transfer a variable from ajax to a php script I get this error:
Fatal error: Class 'Yii' not found in
/var/www/vhosts/adappter.de/comamos/protected/views/store/search_area.php
on line 44 store.js:1308:13
This is how my Ajax Call looks like
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "../protected/views/store/search_area.php",
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});
and this is my php script to line 44
<?php
if (!isset($_SESSION)) { session_start(); }
$_SESSION['search_type']='';
if (isset($_GET['s'])){
$_SESSION['kr_search_address']=$_GET['s'];
$_SESSION['search_type']='kr_search_address';
}
unset($_SESSION['kr_item']);
unset($_SESSION['kr_merchant_id']);
$marker=Yii::app()->functions->getOptionAdmin('map_marker');
if (!empty($marker)){
echo CHtml::hiddenField('map_marker',$marker);
}
?>
The jQuery call is only when I click on a checkbox. So the value of the selected box gets pushed in an array. I want to return the array to the php script.
When I'm loading the site, I don't get such an error. So I don't know why this error occurs.
You need to use controller with action. Not only view file. You try to call view file from web. But it is wrong, because all code in protected directory. All requests must processing from index file. In index file connected framework. Here a small example. Controller:
class SiteController extends Controller
public function actionTest()
{
//... example
echo CHtml::button('test');
}
js:
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "/site/test", // url for your action
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});
I have included a contact form in my page. In the same page I have a script that gets prices depending on the value of a dropdown. Now when I try to submit the contact message I have a conflict with the script for prices. Basically it tries to run it and I have no clue why. Also the contact form when submitted never works...I just get a new page to open with URL..?message=blablabla
Any idea what is going wrong?
I am working on Laravel 4.2 and so the route you see redirects to my php function.
Here is the JSfiddle and here is the php code:
public function postSendMessage() {
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!</span><br><br>";
}
Cancel the click so the form will not submit
$("button#send").click( function(evt){
evt.preventDefault();
New error, form has an id of contact, not a class
data: $('form.contact').serialize(),
needs to be
data: $('form#contact').serialize(),
This is what I do for the same situation
//For your drpbox use this code
$(document).on("change", "#yorDropBoxId", function(){
dropBoxValue=$("#yorDropBoxId").val();
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: {
ObjEvn:"dropBoxEvent",
dropBoxValue: dropBoxValue //You will use $myVar=$_POST["dropBoxValue"] to retrieve the information from javascript
},
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP sent by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//To submit your form use this code. You must use Prevent default if you are using a button or using a <a> link tag to trigger the evenrmrnt
$(document).on("click", "#btn_sendForm", function(e){
e.preventDefault();
var dt={
ObjEvn:"FormEvent",
input1:$("#txt_input1").val(),
input2: $("#txt_input2").val(),
input3: $("#txt_input3").val()
};
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: dt,
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP send by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//In the samePagePHPcript.php you can do this:You will return your information from PHP using json like this
$event = $_POST["ObjEvn"];
if(event==="FormEvent"){//Event to insert in your form
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}
elseif(event==="dropBoxEvent"){//Event to your dropbox - if you want
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}
What I'm tring to do is to load information from different pages, without having to refresh the whole main page...
Could you tell me how to adapt this code for loading files with different names (like about.html and project.html?
Note: this code is made just for loading 'page_.html' files.
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Here is the php file:
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else echo 'There is no such page!';
You can make multiple ajax requests this is the jquery load method:
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
do that 2x and your well off!
Keep in mind for this to work you'll need the jquery library.
I was doing a similar thing on my site here is my code:
window.setInterval("check()",60000);
//request information notice is inside a function called check() (it's not required to put inside function I only do this if I will be making the same request multiple time throughout the program)
function check() {
var request = $.ajax({
url: "file.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
//when request is done:
$(".wheretoputnewdata").html(msg);
});
request.fail(function(jqXHR, textStatus) {
//if request failed do this:
alert( "Request failed: " + textStatus );
});
}
Replace this line
if(file_exists('pages/page_'.$page.'.html'))
with this
if(file_exists('pages/'.$page.'.html'))