WordPress: jQuery Ajax and PHP example - php

Before I submit a form in WordPress, I try to pass some form values to a PHP script using jQuery Ajax to check whether similar posts already exist.
The first part of the jQuery works fine. However I am unsure, if the ajax passes the values to the PHP, because it always throws the alert('something went wrong');. I'm quite a bit lost, it's the first time, that I try to use Ajax.
jQuery(document).ready(function($) {
$('.madison').each(function(){
var _this = $(this) // get the loop item's div.madison
_this.find("select[name='trainingsort']").change( function() {
var _trainingsort = $("select[name='trainingsort']").val();
var vonzeit = "select[name='von-uhrzeit-" + _trainingsort + "']";
var biszeit = "select[name='bis-uhrzeit-" + _trainingsort + "']";
var _vonzeit = $(vonzeit).val();
var _biszeit = $(biszeit).val();
var _tag = $("input[name='tag']").val();
var _reitanlage_id = $("input[name='reitanlagen_id']").val();
var ort = _trainingsort + ' / ' + _vonzeit + ' / ' + _biszeit + ' / ' + _reitanlage_id + ' / ' + _tag;
alert( "Yes! " + ort );
_this.find("input[name='wpcf-rask-name-des-menschen']").val(ort);
// ----- everything works fine above this line ---------------------
$.ajax({
type: "POST",
url: "https://test.cuteberry.de/wp-content/toolset-customizations/trainingsanlagen-2-0__ajax-notification.php",
data: {trainingsort: _trainingsort, vonzeit: _vonzeit, biszeit: _biszeit, reitanlagen_id: _reitanlage_id, tag: _tag},
success: function(data){
alert(data);
},
error: function(data){
alert('something went wrong');
}
});
});
});
});
and the PHP ....
PHP:
<?php
/**
* New custom code snippet (replace this with snippet description).
*/
toolset_snippet_security_check() or die( 'Direct access is not allowed' );
// Put the code of your snippet below this comment.
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$trainingsort=isset($_POST['trainingsort'])?json_decode($_POST['trainingsort']):null; $vonzeit=isset($_POST['vonzeit'])?json_decode($_POST['vonzeit']):null; $biszeit=isset($_POST['biszeit'])?json_decode($_POST['biszeit']):null;
$reitanlagen_id=isset($_POST['reitanlagen_id'])?json_decode($_POST['reitanlagen_id']):null; $tag=isset($_POST['tag'])?json_decode($_POST['tag']):null;
$response = "";
// ----- everything works fine below this line ---------------------
if (isset($reitanlagen_id) && !empty($reitanlagen_id)) {
for ($i = $vonzeit; $i <= $biszeit; $i++) {
// Warteliste_Posts suchen
$query = new WP_Query(
array(
'post_type' => 'rask',
'post_status' => 'publish',
'posts_per_page' => -1,
'toolset_relationships' => array(
'role' => 'child',
'related_to' => $reitanlagen_id,
'relationship' => 'reitanlage-rask'
),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'wpcf-rask-ort-des-geschehens',
'value' => $trainingsort,
'compare' => '='
),
array(
'key' => 'wpcf-rask-welches-journal-termine',
'value' => 1,
'compare' => '='
),
array(
'key' => 'wpcf-rask-von-tag',
'value' => $tag,
'type' => 'numeric',
'compare' => '='
),
array(
'key' => 'wpcf-rask-von-uhrzeit-15-minuten',
'value' => $i,
'type' => 'numeric',
'compare' => '<='
),
array(
'key' => 'wpcf-rask-bis-uhrzeit-15-minuten',
'value' => $i ,
'type' => 'numeric',
'compare' => '>='
),
)
)
);
$pferde_posts = $query->posts;
$count = count($pferde_posts);
// ----- everything works fine above this line ---------------------
if ($count >= 0) {
$response = json_encode("existiert");
break;
}
}
}
echo $response;
I'm thankfull for any hints in the right direction : )

Related

Wordpress Plugin Endpoint returning 404

I'm trying to create a react widget for WordPress using static data and rest api (for practice).
The problem: I have registered an endpoint, but can't get it to access the data at the registered endpoint. I keep getting a 404 error.
Here's the link that gets me to my worpress dashboard: http://penguin.linux.test/wordpressLocal/wp-admin and here's the full code:
<?php
/*
Plugin Name: WP Dashboard Widget
*/
function enqueue_react_scripts() {
wp_enqueue_script( 'react', 'https://unpkg.com/react#17/umd/react.development.js', array(), '17', true );
wp_enqueue_script( 'react-dom', 'https://unpkg.com/react-dom#17/umd/react-dom.development.js', array(), '17', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_react_scripts' );
function react_app_container() {
echo '<div id="react-app-container"></div>';
}
// Callback function to get the data for the chart
function get_chart_data() {
$data = array(
array(
'name' => 'Jan',
'uv' => 4000,
'pv' => 2400,
),
array(
'name' => 'Feb',
'uv' => 3000,
'pv' => 1398,
),
array(
'name' => 'Mar',
'uv' => 2000,
'pv' => 9800,
),
array(
'name' => 'Apr',
'uv' => 2780,
'pv' => 3908,
),
array(
'name' => 'May',
'uv' => 1890,
'pv' => 4800,
),
);
return rest_ensure_response( $data );
}
// Register a custom endpoint
add_action( 'rest_api_init', function () {
register_rest_route( 'getsdata/v1', '/chart_data/', array(
'methods' => 'GET',
'callback' => 'get_chart_data',
) );
} );
function react_dashboard_widget_script() {
?>
<script type= "text/javascript" >
const React = window.React;
const ReactDOM = window.ReactDOM;
const GraphWidget =()=>{
const [ChartData, setChartData]=React.useState([]);
console.log("pepper")
React.useEffect(() => {
fetch('http://penguin.linux.test/wordpressLocal/wp-json/getsdata/v1/chart_data')
.then(response => response.json())
.then(data => setChartData(data))
.catch(error => console.error(error));
},[]);
return (
<LineChart width={500} height={300} data={ChartData.length > 0 ? ChartData : ChartData}>
<XAxis dataKey="name"/>
<YAxis/>
<CartesianGrid stroke="#eee" strokeDasharray="5 5"/>
<Line type="monotone" dataKey="uv" stroke="#8884d8" />
<Line type="monotone" dataKey="pv" stroke="#82ca9d" />
</LineChart>
);
};
ReactDOM.render(
<GraphWidget />,
document.getElementById('react-app-container')
);
</script>
<?php
}
add_action('admin_footer','react_dashboard_widget_script');
function register_react_dashboard_widget() {
wp_add_dashboard_widget( 'react_dashboard_widget', 'React Dashboard Widget', 'react_app_container' );
}
add_action( 'wp_dashboard_setup', 'register_react_dashboard_widget' );
I have tried moving the callback function block and changing the namespace. I expected the api link http://penguin.linux.test/wordpressLocal/wp-json/getsdata/v1/chart_data to fetch the data from the callback function, but I'm getting a 404 error.

PHP include another file, loop over array and run function for each record

I would like to access the values of an array in another php file ... loop over it and run a function over each record. I can't seem to access the values though ... I'm getting an internal error. How to properly do this? That's my setup:
contacts.php
<?php
$contacts_de = array(
'name01' => array(
'firstName' => 'FirstName01',
'lastName' => 'LastName01',
'gender' => 'm',
'language' => 'de',
'email' => 'email01'
),
'name02' => array(
'firstName' => 'FirstName02',
'lastName' => 'LastName02',
'gender' => 'f',
'language' => 'de',
'email' => 'email02'
)
);
mail.php
<?php
include('contacts.php');
function renderContacts($arr) {
global $lang,$contacts_de;
$d = '';
foreach($arr as $i) {
if ($i['gender'] == 'm') {
.$d = 'Mr. '.$i['firstName'].' '.$i['lastName']
} else if ($i['gender'] == 'm') {
.$d = 'Ms. '.$i['firstName'].' '.$i['lastName']
}
}
echo $d;
}
renderContacts();
default.js
$('#sendbtn').on('click', function() {
$.ajax({
type: "POST",url: '/mail.php',
success: function(response,textStatus,jqXHR) {
console.log(response);
},
error: function (jqXHR, status, err) {
console.log(err);
}
});
});
Desired Console.log
Mr. FirstName01 LastName01
Ms. FirstName02 LastName02
The simple answer to what you're asking is:
<?php # contacts.php
$contacts = array(
'name01' => array(
'firstName' => 'FirstName01',
'lastName' => 'LastName01',
'gender' => 'm',
'language' => 'de',
'email' => 'email01'
),
'name02' => array(
'firstName' => 'FirstName02',
'lastName' => 'LastName02',
'gender' => 'f',
'language' => 'de',
'email' => 'email02'
)
);
and
<?php # whatever.php
require __DIR__ . '/contacts.php';
function render_contacts(array $contacts) {
foreach ($contacts as $contact) {
$prefix = $contact['gender'] == 'm' ? 'Mr' : 'Ms';
printf("%s. %s %s\n", $prefix, $contact['firstName'], $contact['lastName']);
}
}
render_contacts($contacts);
A non-separated sandbox can be seen here: http://sandbox.onlinephpfunctions.com/code/6daa0147671fcaac9c51fe919c4a8f916181fad1
I've also cleaned up your code a little bit for you, removing things like the global keyword, some syntax errors, and the JavaScript you linked, as it's irrelevant to the issue.
GL.

Secure Ajax call

I have a dataTable with server-side processing but I don't know how to secure the ajax call because if anyone go to the ajax php file can read all the content.
This is my jquery:
$(document).ready(function() {
$('#netflow').DataTable( {
aaSorting: [[ 5, "desc" ]],
responsive: {
details: {
renderer: function ( api, rowIdx ) {
var data = api.cells( rowIdx, ':hidden' ).eq(0).map( function ( cell ) {
var header = $( api.column( cell.column ).header() );
return '<p style="color:#00A">'+header.text()+' : '+api.cell( cell ).data()+'</p>'; // changing details mark up.
} ).toArray().join('');
return data ? $('<table/>').append( data ) : false;
}
}
},
processing: true,
serverSide: true,
ajax: "/adm/includes/netflow_processing.php",
} );
var oTable = $('#netflow').dataTable();
var table = $('#netflow').DataTable();
$('#netflow_filter input').unbind();
$('#netflow_filter input').bind('keyup', function(e) {
if(e.keyCode == 13) {
oTable.fnFilter(this.value);
}
});
// AƱadir filtro para cad acelda
$('#netflow tfoot th').each( function (i) {
$(this).html( '<input type="text"/style = "width: 100%; " placeholder="Filtra...">' );
} );
// Aplicar filtro al introducir en cada celda
table.columns().eq( 0 ).each( function ( colIdx ) {
$( 'input', table.column( colIdx ).footer() ).on( 'keyup change', function () {
table
.column( colIdx )
.search( this.value )
.draw();
} );
} );
} );
And this is the ajax script:
<?php
$table = 'netflow';
$primaryKey = 'id';
$columns = array(
array( 'db' => 'flow_src', 'dt' => 0 ),
array( 'db' => 'flow_dst', 'dt' => 1 ),
array( 'db' => 'flow_proto', 'dt' => 2 ),
array( 'db' => 'out_packets', 'dt' => 3 ),
array( 'db' => 'in_packets', 'dt' => 4 ),
array( 'db' => 'flow_start', 'dt' => 5 )
);
$sql_details = array(
'user' => '6g43tfr3',
'pass' => 'XXXXXXXXX',
'db' => 'DBNAME',
'host' => 'bbdd.localdomain'
);
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
How can I make a hash/token request?
You could simply check HTTP_REFERER. HTTP_REFERER is overwritten by the browser and cannot be altered meaning you cannot fake a request as it was called from within your script. So if name of the page (referer) that legally may access your script is
http://example.com/page42
(check what your script is called by echoing out $_SERVER['HTTP_REFERER']) then add
<?
if ($_SERVER['HTTP_REFERER'] != 'http://example.com/page42') {
header('HTTP/1.0 403 Forbidden');
die('You are not allowed to access this script.');
}
...
as the very first lines to your /adm/includes/netflow_processing.php script.
First of all, I can't see any check that the user is logged, or some other check. You can create user with levels. Admin user, normal user and give him access code. You can use this pseudo code.
$access = false;
$user == isAdmin() {
$access = true;
}
if($access == false) return redirect;
Second, you can make some check that is AJAX requirest.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here */
}
And in this scopes you can make additional check ( for login, access level, etc. ) , BUT there's no 100% way to detect if the request was made via ajax. Even if someone sends header with
"X-Requested-With: XMLHttpRequest"

Yii webcam extension

In Yii,Iam using yii-jpegcam webcam extension used for taking photos in my application and it works fine with the following url format
index.php?r=user/newphoto
But my application is in "/" format (index.php/user/newphoto). So this extension not working with my url format. How it can be solved?
Extension Link used : http://www.yiiframew...on/yii-jpegcam/
http://www.yiiframework.com/extension/yii-jpegcam/
And my view code is :
<?php $onBeforeSnap = "document.getElementById('upload_results').innerHTML = '<h1>Uploading...</h1>';";
$completionHandler = <<<BLOCK
if (msg == 'OK') {
document.getElementById('upload_results').innerHTML = '<h1>OK! ...redirecting in 3 seconds</h1>';
// reset camera for another shot
webcam.reset();
setTimeout(function(){window.location = "index.php?r=user/index";},3000);
}
else alert("PHP Error: " + msg);
BLOCK;
$this->widget('application.extensions.jpegcam.EJpegcam', array(
'apiUrl' => 'index.php?r=user/jpegcam.saveJpg',
'shutterSound' => false,
'stealth' => true,
'buttons' => array(
'configure' => 'Configure',
'takesnapshot' => 'Take Snapshot!'
),
'onBeforeSnap' => $onBeforeSnap,
'completionHandler' => $completionHandler
)); ?>
If urlManager enabled in config, you should change apiUrl value with createUrl method :
$this->widget('application.extensions.jpegcam.EJpegcam', array(
'apiUrl' => Yii::app()->urlManager->createUrl('index.php/user/jpegcam.saveJpg'),
'shutterSound' => false,
'stealth' => true,
'buttons' => array(
'configure' => 'Configure',
'takesnapshot' => 'Take Snapshot!'
),
'onBeforeSnap' => $onBeforeSnap,
'completionHandler' => $completionHandler
));

File exceeds the defined ini size when using iframe

I am using fancy box iframe to display my page which has the file upload button. when i click form submit i got the "File exceeds the defined ini size". i checked some of links under google and stackoverflow. But not able to find. I have enctype="multipart/form-data" in my form. Following is my code
public function createForm($data = array())
{
$this->setMethod(Zend_Form::METHOD_POST);
$this->setEncType(Zend_Form::ENCTYPE_MULTIPART);
$this->setAttrib('id', 'createsub');
$this->setAction(
$this->getView()->getHelper('url')->url(array(
'controller' => 'test',
'action' => 'create'
))
);
$this->setDecorators(array(
'Description',
'FormElements',
'Form'
));
$fnameNotEmpty = new Zend_Validate_NotEmpty();
$fnameNotEmpty->setMessage('Name cannot be empty.');
$fnameStrlen = new Zend_Validate_StringLength(1, 20);
$name = new Zend_Form_Element_Text('name', array(
'label' => 'Name:',
'value' => '',
'class' => 'text-size text',
'tabindex' => '1',
'required' => true,
'validators' => array(
array($fnameNotEmpty, true),
array($fnameStrlen, true)
),
'decorators' => $this->requiredElementDecorators,
'description' => '<img src="../../'.$baseurl.'/images/star.png" alt="required" />',
'filters' => array('StringTrim')
));
$this->addElement($name);
.... ..... .....
$brochure = new Zend_Form_Element_File('brochure', array(
'label' => 'Brochure:*',
'value' => '',
'class' => 'text-size text',
'tabindex' => '3',
'required' => true,
'filters' => array('StringTrim')
));
$this->addElement($brochure);
$submit = $this->createElement('button','addtbtn',array('class'=>'Test','label'=>'Create'));
$submit->setIgnore(true);
$this->addElement($submit);
return $this;
}
Also if i did not use iframe, I can able to upload my image...Very Strange.
I make the validation using Ajax by following code ,
<script type="text/javascript">
var Path="<?php echo $this->eurl; ?>"
$(function()
{
vReg=0
$("#addtbtn").click(function()
{
if(vReg == 1)
{
return true;
}
else{
var url = 'validateform';
var data = {};
$("input").each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$("select").each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$("textarea").each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$.post(url,data,function(resp)
{
vError=""
for(id in resp){
oResp=resp[id];
for(key in oResp){
vError +=oResp[key]+"\n"
}
}
if(vError == ''){
vReg=1
$("#createform").attr('target','_top');
$("#createform").submit();
return true;
}
else{
$("#createform").attr('target','_self');
alert(vError)
return false;
}
},'json');
}
});
});
</script>
Also Has the following function in my controller
public function validateformAction()
{
$this->_helper->viewRenderer->setNoRender();
$this->_helper->getHelper('layout')->disableLayout();
$p = new Admin_Model_DbTable_Test();
$p = $p->getData();
foreach($p AS $k => $v)
{
$p[$v['catid']] = $v['name'];
}
$form = new Admin_Model_Form_SubTest();
$f = $form->createForm(array('parents' => $p));
$f->isValid($this->_getAllParams());
$json = $f->getMessages();
echo Zend_Json::encode($json);
}
So this will call the function which i gave on the top of the post and do the validation and return the error.But here i always getting "File exceeds the defined ini size " What I done wrong this code.
Kindly help me on this.
Check the upload_max_filesize setting in your .ini file(s). That's where this error comes from.
When you call .val() on your file input, you get the path of the file you have selected, while your validator will be expecting the file itself, hence the strange error. Most people opt to skip file inputs when doing ajax validation, and just check it on submit.

Categories