I tried some steps I saw on the internet on how to send forms without refreshing the page using ajax but I cant seem to do it fine. Here is my code inside the form
$(".coupon_thumbsup").on('submit', function(e) {
e.preventDefault();
console.log("click");
var ThumbsUp = $(this).parent().find(".ThumbsUpVal").val();
ThumbsUp = parseInt(ThumbsUp) + 1;
$(this).parent().find(".ThumbsUpVal").val(ThumbsUp);
$(this).find(".green_thumb").css('background', 'url(http://www.accessdoorreviews.com/wp-content/uploads/2017/11/smalllike2.jpg)');
var totalvotess = $(this).parent().parent().find(".numofvotes").text();
totalvotess = parseInt(totalvotess) + 1;
$(this).parent().find(".ThumbsUpVote").val("1");
$(this).parent().parent().find(".numofvotes").text(totalvotess);
var successpercentv = ((ThumbsUp/totalvotess)*100).toFixed(2);
$(this).parent().parent().find(".successpercent").text(successpercentv);
console.log(successpercentv);
var ThumbsDown = $(this).parent().find(".ThumbsDownVal").val();
ThumbsDown = parseInt(ThumbsDown);
var companycouponid = $(this).parent().find(".companycouponid").val();
$.ajax({
type: "POST",
url: "insertcouponthumbs.php",
data: {'ThumbsUp': ThumbsUp, 'companycouponid':companycouponid, 'ThumbsDown':ThumbsDown},
});
});
And this is my php file:
<?php add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$comcoupid = $_POST['companycouponid'];
$resultcoupon = $wpdb->get_results("SELECT * FROM wp_coupon_list WHERE ID = $comcoupid");
foreach ($resultcoupon as $keyy) {
$wpdb->update($wpdb->prefix."coupon_list", array(
'ThumbsDown' => $_POST['ThumbsDown'],
'ThumbsUp' => $_POST['ThumbsUp'],
), array('ID'=>$keyy->ID)
);
}
wp_die();
} ?>
Related
I have written a Wordpress plugin which places several buttons inside a metabox on the post-edit page. I'd go to example.com/wp-admin/post.php?post=number1&action=edit. I want my Wordpress hook to receive an AJAX call, and in turn makes a request to a remote server (one which requires authentication that the WP user shouldn't have to enter), then returns the result to the Wordpress user.
My code for the form with the data I want to send is two custom HTML elements' entered data. They are:
class MyFormData extends HTMLElement{
constructor() {
super();
}
connectedCallback(){
const li = document.createElement('li');
const newDat = document.createElement('input');
newDat.setAttribute('type','text');
newDat.setAttribute('name',`title box`);
newDat.setAttribute('placeholder',`Test Data`);
const deleteButton = document.createElement('button');
deleteButton.setAttribute('type','button');
deleteButton.innerHTML = "-";
deleteButton.addEventListener("click",function(){
li.parentNode.remove();
});
li.appendChild(newDat);
li.appendChild(deleteButton);
this.appendChild(li);
}
}
customElements.define('form-data',MyFormData);
and
class DurationMenu extends HTMLElement{
constructor(){
super();
}
connectedCallback(){
const amount = document.createElement('input');
amount.setAttribute('id','selectedTime');
amount.setAttribute('type','number');
amount.setAttribute('step',5)
amount.setAttribute('name','duration');
amount.setAttribute('min',5);
amount.setAttribute('max',60);
amount.setAttribute('value',15);
this.appendChild(amount)
}
}
customElements.define('duration-choice', DurationMenu);
Both of these custom elements show up in the metabox. I have a custom element for the submit button:
import ModelObject from './model/modelobject.js'
var theJson;
var data;
import {CO} from './Controller/controllerobject.js';
export var c = new ModelObject();
import {grabDataForSending} from './Controller/wordpressrelay.js';
export class SubmitAndCreate extends HTMLElement{
constructor(){
super();
}
connectedCallback(){
var data;
const submitbutton = document.createElement('button');
submitbutton.setAttribute('type','submit');
submitbutton.setAttribute('id','submitButton');
submitbutton.innerHTML = "Begin ";
submitbutton.addEventListener('click',this.myFunc.bind(this));
submitbutton.addEventListener('click',()=>{
document.getElementById('selectedTime').value = 15;
var dataset = document.getElementById("dataset").children;
for(var i = 0; i < dataset.length; i++){
document.getElementById("dataset").children[i].children[0].childNodes[0].value = '';
}
});
submitbutton.addEventListener('click',(event)=>{
CO.updateModelData();
event.preventDefault();
})
submitbutton.addEventListener('click',(event)=>{
grabExperimentForSending();
})
this.appendChild(submitbutton);
}
gatherData(){
//var enteredURL = document.getElementsByName('URL box')[0].value;
var dataAmount = document.getElementById('dataset').children.length;
var experTime = document.getElementById('selectedTime').value;
var dataObject = {
experimentDuration : experTime,
myData: {}
}
var individualDatum = [];
for (var i = 0; i < dataAmount; i++){
individualDatum[i] = {
dataset: document.getElementById("dataset").children[i].children[0].childNodes[0].value
}
}
dataObject.myData = individualDatum;
var dataObjectJSON = JSON.stringify(dataObject,null,2);
theJson = dataObjectJSON;
return theJson;
}
}
export {theJson, CO};
customElements.define('submit-button', SubmitAndCreate)
I want to grab the data one enters in both, and submit it to an external site that normally requires a password and username to login to from outside Wordpress. I want to submit it as JSon. How can I do this with Ajax and php?
My php so far is:
//for admin-ajax
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) {
return;
}
wp_enqueue_script( 'ajax-script', plugins_url( '/wp-content/plugins/my-plugin/js/Controller/ajaxdata.js', __FILE__ ), array('jquery') );
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'c' => c ) ); //c has the data that I need to send to the remote site's server
}
//relevant to admin-ajax
add_action( 'wp_ajax_CBAjax', 'CBAjax' );
//relevant to admin-ajax
function CBAjax() {
error_log(print_r($_REQUEST));
if ( isset($_REQUEST) ) {
$exper = $_REQUEST['experdata'];
error_log(print_r($exper,true));
echo "The exper is " . $exper;
}
$body = array(
'dur' => $exper['experimentDuration'],
'buckets'=> $experdata['myData']
);
$response = wp_remote_post( $url = "https://subdomain.example.com:8080/api/v1/data", array(
'body' => $body,
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( "login#example.com" . ':' . "password!" ),
),
) );
if($response){
error_log(print_r($response,true));
error_log("PING");
}
$respcode = wp_remote_retrieve_response_code($response);
error_log(print_r($respcode,true));
$ajax['remote_code'] = $response['response']['code'];
echo json_encode( $ajax );
error_log(print_r($ajax,true));
wp_die();
}
in the creation of the metabox, I have:
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
add_action( 'wp_ajax_CBAjax', 'CBAjax' );
This is how I proxy the data from the button to the admin-ajax.php page:
import {c} from '../submitbutton.js';
function grabExperimentForSending(){
$.ajax({
url: "admin-ajax.php",
type: "POST",
data: c ,
success: function (response, statusCode) {
console.log(c.exps[0]);
console.log(`statusCode is ${statusCode}`);
console.log(`data is ${data}`);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(`jqXHR is ${jqXHR}, textStatus is ${textStatus}, errorThrown is ${errorThrown}`);
console.log(c.exps[0]);
}
});
}
and from there, it goes to ajaxdata.js
import {c} from './wordpressrelay.js';
function my_action_javascript(){
$('#submitButton').click( function(){
var data = { //model
'action': 'CBAjax',
'experdata': ajax_object.c
}
jQuery.post(ajax_object.ajax_url, data, function(response) {
console.log('Got this from the server: ' + response);
console.log(data.experdata);
console.log(`data[experdata] is ${data['experdata']}`);
});
});
}
export {my_action_javascript,c};
export {grabExperimentForSending,c};
I want to send that data, exp (a Json) to the remote site.
You will need to trigger an ajax request, for example when button click, to your ajax handler.
$('#my-submit-button').click(function(){
var data = {
'action': 'cbAjax',
'experdata': c.exps[0]
};
// from php generate your ajaxurl from admin_url( 'admin-ajax.php' );
jQuery.post(ajaxurl, data, function(response) {
// ajax response if any
});
});
Simply log something in your ajax handler to see if a request is sent after click the button. This is to verify your ajax handler is reachable.
I need it to fit and I click on a file to increase the number to 1 and saved in the database
I already have the database created and part of the AJAX code ready, in addition to the number YA INCREMENTA, the issue is that I have an update of the page manually instead of only updating the div
Number to update
<span id="'.$rowRE[id_reclamo].'" class="badge badge-primary badge-pill like">'.$rowRE[positivo].'</span>
Function with ajax
$(document).ready(function () {
$('.like').on('click', function () {
var reclamoID = $(this).attr('id');
if (reclamoID) {
$.ajax({
type: 'POST'
, url: 'like.php'
, data: 'reclamo_id=' + reclamoID
, success: function () {}
});
}
else {
alert("error");
}
});
});
php code
$reclamoID=$_POST['reclamo_id'];
$query = $db->query("UPDATE reclamos SET positivo = positivo +1 WHERE id_reclamo = $reclamoID");
//Count total number of rows
$rowCountTabla = $query->num_rows;
I need you NOT to recharge the entire page if not ONLY THE NUMBER
Return the count in the same request you make when you post your data. Something along the lines of:
PHP:
$reclamoID = pg_escape_string($_POST['reclamo_id']);
$results = $db->query("SELECT positivo FROM reclamos WHERE id_reclamo = '".$reclamoID."'");
// Whatever DB wrapper you're using here... this is just a guess.
$count = $results[0]['positivo'];
echo json_encode(array(
'id' => $reclamoID,
'count' => $count
));
Javascript:
$('.like').on('click', function () {
var element = $(this);
var reclamoID = element.attr('id');
if (reclamoID) {
$.post(
'like.php',
{
reclamo_id: reclamoID
},
function (responseData) {
element.text(responseData.count);
},
'json'
);
}
});
ALWAYS sanitize posted data, to prevent injections and other malicious code.
Used AJAX for this chat function, however, it needs to be refreshed to retrieve new chats. I tried using setIntervala and setTimeout. sorry, noob with this.
message.php
$(document).ready(function(){
$("#btn-submit").click(function(e){
e.preventDefault()
var msgg = $("#chat-msg").val();
var href = $('#btn-submit').attr('href');
var ssid = $("#s-id").val();
var rrid = $("#r-id").val();
$.ajax({
method: "POST",
url: "http://127.0.0.1/test/admin/dashboard/ajaxMessage/",
data: {
message: msgg
}
})
.done(function(msg) {
console.log(msg);
$("#chat-msg").val("");
var head;
if (rrid != ssid) {
head = '<br><br><br><h1 class="msg-show-right">';
} else {
head = '<br><br><br><h1 class="msg-show-left">';
}
var chatBubble = head + " " + msgg + "</h1>";
$( ".msg-show-right" ).each(function( index ) {
last_bubble = $(this);
});
last_bubble.after(chatBubble)
});
});
});
dashboard.php
public function ajaxMessage () {
$message = $this->input->post('message');
$s_id = $this->session->userdata('s_id');
$r_id = $this->session->userdata('r_id');
$data = array(
'msg' => $message,
'status' => '1',
's_id' => $s_id,
'r_id' => $r_id
);
$this->admin_model->form_insert($data);
echo "true";
}
there are some unnecessary codes also.
I have a problem
There is a rating system on songs (Its not my code i debugging it). but it could not add or update or show me the rating.
here is my code:
Ajax.js
function bindEvents() {
$(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
$(cssSelector.ratingLevel).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = $(cssSelector.title+':first').text();
var postdata1 = 'action=my_special_ajax_call5&rating='+rating+'&trackname='+trackname;
alert(postdata1);
jQuery.ajax({
type:'POST',
url:ajaxurl,
cache:false,
data: postdata1,
beforeSend:function(){
},
success:function(res){
$(cssSelector.rating_succes).html(res).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
Proccess.php
function implement_ajax5(){
global $wpdb;
$table = $wpdb->prefix."songs";
$table1 = $wpdb->prefix."rating";
$song_title = strip_tags($_POST['trackname']);
$rating_value = strip_tags($_POST['rating']);
$songres = $wpdb->get_row("SELECT * FROM $table WHERE `title`='$song_title'") or die(mysql_error());
$song_id = $songres->id;
$total_votes = $songres->total_votes;
$total_votes = $total_votes+1;
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'song_id' => $song_id,
'rating_value' => $rating_value,
'user_ip' => $ip
);
$check = $wpdb->get_results("SELECT * FROM $table1 WHERE song_id='$song_id' AND user_ip='$ip'");
if(!$check){
$insert = $wpdb->insert($table1,$data);
$wpdb->update(
$table,
array(
'total_votes' => $total_votes,
),
array( 'ID' => $song_id )
) or die(mysql_error());
echo 'Thank you';
}else{echo 'Already rated';}
die();
}
index.php
add_action('wp_ajax_my_special_ajax_call5', 'implement_ajax5');
add_action('wp_ajax_nopriv_my_special_ajax_call5', 'implement_ajax5');//for users that are not logged in.
I dont understand what happen when i alert it shows me right values but not add or update in database.
ok just try this in your Ajax.js at top of the page
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
And every thing goes perfect
and i think in your process page there is no need to update query. If you want to delete this there is no issue.
i get this a lot........ajaxurl needs to be defined, so i've learned that its just easier to not use ajaxurl and put in "/wp-admin/admin-ajax.php" in the url section.
Also i dont see you using non-conflict jQuery? (use the word jQuery instead of $)
You may also have issues with your postdata string, i may be wrong but what you need is action: '' ,
rating: '',
etc.
A good practice is to var_dump $_POST and exit at the beginning of your function to make sure they are passing over correctly. then in success- console.log(res) or whatever you are calling your return data
function bindEvents() {
jQuery(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
jQuery(cssSelector.ratingLevel).click(function() {
var $this = jQuery(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = jQuery(cssSelector.title+':first').text();
//alert(postdata1); -> console.log() is better for looking at objects
jQuery.ajax({
type:'POST',
url: "/wp-admin/admin-ajax.php",
cache:false,
data: {
action: 'my_special_ajax_call5',
rating: rating,
trackname: trackname
}
success:function(output){
console.log(output)
jQuery(cssSelector.rating_succes).html(output).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
see how you get on with that :)
Is there a way I can set a cron to run a view on my Drupal site? I have a jQuery script on it which I would like to run once an hour.
I tried;
php http://mysite/myview
but I guess I am waaay off the mark. I get;
Could not open input file:
Here's the js which I am using on my rss feed;
// $Id
(function ($) {
Drupal.behaviors.tweetcast = {
attach: function (context, settings) {
$('div.tagspeak:not(.tags-processed)', context).addClass('tags-processed').each(function () {
var mynid, sinceid, updateinfo, sinceurl, author, tweethtml;
var currentsinceid = $('.currentsinceid').val();
var firstring = $(this).html();
var twostring = firstring.replace(/\s/g,'').replace(/^%20OR%20/gim,'').replace(/%20OR$/gim,'').replace(/%20OR%20%$/gim,'').replace(/%20OR%20$/gim,'').replace(/%$/gim,'').replace(/%20OR$/gim,'').toLowerCase();
var threestring = twostring.replace(/%20or%20/gim,'%20OR%20');
$(this).text(threestring);
var fourstring = threestring.replace(/%20OR%20/gim,' ');
var fivestring = fourstring.replace(/%23/gim,'#');
$(this).closest('.views-row').append('<div class="views-field views-field-replies"></div>');
tweethtml = $(this).closest('.views-row').find('div.views-field-replies').eq(0);
var twitter_api_url = 'http://search.twitter.com/search.json';
$.ajaxSetup({ cache: true });
$.getJSON( twitter_api_url + '?callback=?&rpp=1&q=' + threestring + '&since_id=' + currentsinceid, function(data) {
$.each(data.results, function(i, tweet) {console.log(tweet);
if(tweet.text !== undefined) {
var tweet_html = '<div class="tweetuser">' + tweet.from_user + '</div>';
tweet_html += ' <div class="sinceid">' + tweet.id + '</div>';
tweethtml.append(tweet_html);
}
});
});
$.fn.delay = function(time, callback){
jQuery.fx.step.delay = function(){};
return this.animate({delay:1}, time, callback);
}
$(this).delay(2000, function(){
title = $(this).closest('.views-row').find('div.views-field-title').eq(0).find('span.field-content').text();
link = $(this).closest('.views-row').find('div.views-field-path').eq(0).find('span.field-content').text();
author = $(this).closest('.views-row').find('div.tweetuser').eq(0).text();
mynid = $(this).closest('.views-row').find('div.mynid').text();
sinceid = $(this).closest('.views-row').find('div.sinceid').eq(0).text();
updateinfo = {sinceid: sinceid, mynid: mynid, author: author, title: title, link: link, tags: fivestring};
sinceurl = Drupal.settings.basePath + 'sinceid';
$.ajax({
type: "POST",
url: sinceurl,
data: updateinfo,
success: function(){}
});
});
});
}}
})
(jQuery);
And here is the php my module;
<?php
// $id:
function sinceid_menu() {
$items = array();
$items['sinceid'] = array(
'title' => 'sinceid',
'page callback' => 'sinceid_count',
'description' => 'sinceid',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function sinceid_count()
{
$sinceid=$_POST['sinceid'];
$mynid=$_POST['mynid'];
$author=$_POST['author'];
$title=$_POST['title'];
$link=$_POST['link'];
$tags=$_POST['tags'];
db_update('node')
->expression('sinceid', $sinceid)
->condition('nid', $mynid)
->execute();
$sql = db_query("SELECT author FROM {authordupe} WHERE author = $author");
$result = db_query($sql);
$how_many_rows = $result->rowCount();
if($how_many_rows == 0) {
db_insert('authordupe')
->fields(array(
'author' => $author,
'title' => $title,
'link' => $link,
'tags' => $tags,
))
->execute();
}
}
The basic code to run a view in Drupal is
$view = views_get_view('<your_view_machine_name>');
$view->set_display('<optional_display_name>');
$view->execute();
That said, you say have a jQuery script that runs within a view. Seriously? What is your script doing? I'd say that jQuery it's best used when you want a script to be run at client's side. Can't you write php code to accomplish whatever you need and put it in a cron hook?