I am trying to insert the data but getting fatal error i am seding from script ajax call .Please help me some one.Thanks in advance.Am using this for Wordpress plugin development
include_once($_SERVER['DOCUMENT_ROOT'].'/wordpress/wp-config.php' );
global $wpdb;
$table ='wp_mnggallery';
if(isset($_POST['img'])){
$img = $_POST['img'];
$back_image = $_POST['back_img'];
$url = $_POST['url'];
$data = array(
'id' => "",
'images' => "$img",
'back_image' => "$back_image",
'url'=>"$url"
);
$number_images = count($img);
//Inserting the data
$q = $wpdb->insert($table ,$data);
echo $img.' is updated succefully <br>';
}
Ajax call for this code sending from another page it was :
<script>
$('#submit').submit(function(event){
event.preventDefault();
var img = $('#img').val();
var backimage = $('#back_img').val();
if(img!=''&backimage!=''){
$.ajax({
type: "POST",
url: '<?php echo plugins_url(); ?>/mngimageeffects/post.php',
data: $('#submit').serialize(),
success: function( response ) {
$('#error').html( response );
$('#mng_img').append('<div class="col-md-4"><img src="'+img+'"width="100%"/></div><div class="col-md-2"><button class="btn btn-primary delete" id="delete">Upload</button></div>');
//delete = delete + 1;
$('#img').val('');
$('#back_img').val('');
$('#url').val('');
}
});
}else{
alert('Please Enter The Frent Image and Back Images Urls: ');
}
});
</script>
To use AJAX in Wordpress plugins
jQuery('#submit').submit(function(event){
event.preventDefault();
var img = jQuery('#img').val();
var backimage = jQuery('#back_img').val();
var url = jQuery('#url').val();
var data = {
action: 'submit_data',
img: img,
back_img: backimage,
url : url,
};
if(img!=''&backimage!=''){
jQuery.ajax({
type: "POST",
url: ajaxurl, // if its front end else use else ajaxurl
data:data,
dataType: 'html',
success: function( response ) {
alert(response+'sdfs')
jQuery('#error').html( response );
jQuery('#mng_img').append('<div class="col-md-4"><img src="'+img+'"width="100%"/></div><div class="col-md-2"><button class="btn btn-primary delete" id="delete">Upload</button></div>'); //delete = delete + 1;
jQuery('#img').val(''); jQuery('#back_img').val(''); jQuery('#url').val('');
},
error : function(data){
alert('Error while deleting.');
return false;
}
});
}
else{ alert('Please Enter The Frent Image and Back Images Urls: '); }
});
and in the PHP side,
add_action( 'wp_ajax_my_action', 'submit_data' ); // excutes for users that are logged in.
add_action( 'wp_ajax_nopriv_submit_data', 'submit_data' ); //executes for users that are not logged in.
function submit_data(){
global $wpdb;
$table ='wp_mnggallery';
if(isset($_POST['img'])){
$img = $_POST['img'];
$back_image = $_POST['back_img'];
$url = $_POST['url'];
$data = array(
'id' => "",
'images' => "$img",
'back_image' => "$back_image",
'url'=>"$url"
);
$number_images = count($img);
//Inserting the data
$q = $wpdb->insert($table ,$data);
echo $img.' is updated succefully <br>';
wp_die();
}
}
The url should be url: admin_url( 'admin-ajax.php' ), if its front end else use ajaxurl it will automatically include the necessary files
check
You shouldn't include the config file but wp-load.php when you want to use WordPress functions outside of WordPress
define( 'SHORTINIT', true );
require( '/path/to/wp-load.php' );
// use $wpdb after this
Related
I have a problem with displaying data using AngularJS.
So my application is based on AngularJS and CodeIgniter 3.
I've created a validation in CodeIgniter written in the form, everything works.
public function create()
{
$this->form_validation->set_error_delimiters('','');
$this->form_validation->set_rules( 'login' , 'Imię' , 'required|min_length[3]' );
$this->form_validation->set_rules( 'email' , 'Email' , 'required|valid_email|is_unique[users.email]' );
$this->form_validation->set_rules( 'password' , 'Hasło' , 'required|matches[passconf]' );
$this->form_validation->set_rules( 'passconf' , 'Powtórz hasło' , 'required|matches[password]' );
if ( $this->form_validation->run())
{
$user = $this->input->post('user');
unset($user['passconf']);
$user['password'] = crypt($user['password'], config_item('encryption_key'));
$this->Users_model->create($user);
}
else
{
$errors['login'] = form_error( 'login' );
$errors['email'] = form_error( 'email' );
$errors['password'] = form_error( 'password' );
$errors['passconf'] = form_error( 'passconf' );
echo '{"records":' . json_encode( $errors ) . '}';
}
}
On the AngularJS side, I wanted errory to appear.
controllersAdmin.controller('userCreate', function( $scope, $http, $timeout ){
$scope.user = {};
$scope.user.role = 'user';
$scope.createUser = function( user ){
$http({
method: 'POST', url: 'api/admin/users/create/' ,
data: {
user : user,
login : user.login,
email : user.email,
password : user.password,
passconf : user.passconf
}}
).then(function ( errors ){
if ( errors )
{
$scope.errors = errors;
}
else
{
$scope.success = true;
$timeout(function(){
$scope.success = false;
$scope.user = {};
} , 3000 );
}
},function (error){
console.log('Blad we wczytywaniu danych');
});
}
});
I created $scope.errors = errors;
When I display it with {{errors}} - data is displayed.
{"data":{"records":{"login":"Pole Imię jest wymagane.","email":"Pole Email jest wymagane.","password":"Pole Hasło jest wymagane.","passconf":"Pole Powtórz hasło jest wymagane."}},"status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"api/admin/users/create/","data":{"user":{"role":"user"}},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"OK","xhrStatus":"complete"}
However, when I give {{errors.login}}, the data is not displayed. Can I count on little help?
There's your problem. Login is not a property of the errors object but a sub property. It should be errors.data.records.login.
I am attempting to upload files directly to the browser to S3 using evaporate js.
I followed the tutorial at jqueryajaxphp.com but I am having a problem with the signature
Signature.php
<?php
$to_sign = $_GET['to_sign'];
$secret = 'AWS_SECRET';
$hmac_sha1 = hash_hmac('sha1', $to_sign, $secret, true);
$signature = base64_encode($hmac_sha1);
echo $signature;
Upload function
function largeFileUPload(file) {
var ins = new Evaporate({
signerUrl: './includes/s3-signature.php',
aws_key: "AWS_KEY_XXXXXXX",
bucket: 'bucket-name',
awsRegion: 'eu-west-1',
cloudfront: true,
aws_url: 'http://bucket-name.s3-accelerate.amazonaws.com',
// partSize: 10 * 1024 * 1024,
s3Acceleration: true,
computeContentMd5: true,
cryptoMd5Method: function (data) { return AWS.util.crypto.md5(data, 'base64'); },
cryptoHexEncodedHash256: function (data) { return AWS.util.crypto.sha256(data, 'hex'); }
});
// http://<?=$my_bucket?>.s3-<?=$region?>.amazonaws.com
ins.add({
name: 'evaporateTest' + Math.floor(1000000000*Math.random()) + '.' + file.name.replace(/^.*\./, ''),
file: file,
xAmzHeadersAtInitiate : {
'x-amz-acl': 'public-read'
},
signParams: {
foo: 'bar'
},
complete: function(r){
console.log('Upload complete');
},
progress: function(progress){
var progress = Math.floor(progress*100);
console.log(progress);
},
error: function(msg){
console.log(msg);
}
});
}
I am getting to following response from from the s3 end point
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
I have also tried the blueimp plugin but this fails with files over 200MB
The Signature.php file form the tutorial from jqueryajaxphp.com was causing the problem. I altered the php signature file form the evaporate.js docs and it solved the problem
Signature.php
$to_sign = $_GET['to_sign'];
$secret = 'AWS_SECRET';
$formattedDate = substr($dateTime, 0, 8);
//make the Signature, notice that we use env for saving AWS keys and regions
$kSecret = "AWS4" . $secret;
$kDate = hash_hmac("sha256", $formattedDate, $kSecret, true);
$kRegion = hash_hmac("sha256", "eu-west-1", $kDate, true);
$kService = hash_hmac("sha256", 's3', $kRegion, true);
$kSigning = hash_hmac("sha256", "aws4_request", $kService, true);
$signature = hash_hmac("sha256", $to_sign, $kSigning);
echo $signature;
I am working on my first app, based on Ionic and Angularjs connected to Wordpress REST Api.
I need to display the category name, but the WP-API V2 post list (example.com/wp-json/wp/v2/posts) has only the category ids.
In order to get the categories I need to make a second http request to example.com/wp-json/wp/v2/categories
This is my function in the controller to load all posts and it works fine.
var postsApi = $rootScope.url + 'posts';
$scope.loadPosts = function() {
// Get all of our posts
DataLoader.get( postsApi ).then(function(response) {
$scope.posts = response.data;
$log.log(postsApi, response.data);
}, function(response) {
$log.log(postsApi, response.data);
});
but how do I achieve to parse the category id, that i get from example.com/wp-json/wp/v2/posts with example.com/wp-json/wp/v2/categories to get the category name without making a http request every single loop?
You maybe need to use register_new_field() to modify the response from the api.
Modify response from wp-api v2
In your custom function, you will able to retrieve the post categories in one api call and embed it in the json response.
EDIT:
Here is a working example, to add post category and tag link to the api response, only for the get request:
add_action( 'rest_api_init', 'wp_rest_insert_tag_links' );
function wp_rest_insert_tag_links(){
register_rest_field( 'post',
'post_categories',
array(
'get_callback' => 'wp_rest_get_categories_links',
'update_callback' => null,
'schema' => null,
)
);
register_rest_field( 'post',
'post_tags',
array(
'get_callback' => 'wp_rest_get_tags_links',
'update_callback' => null,
'schema' => null,
)
);
}
function wp_rest_get_categories_links($post){
$post_categories = array();
$categories = wp_get_post_terms( $post['id'], 'category', array('fields'=>'all') );
foreach ($categories as $term) {
$term_link = get_term_link($term);
if ( is_wp_error( $term_link ) ) {
continue;
}
$post_categories[] = array('term_id'=>$term->term_id, 'name'=>$term->name, 'link'=>$term_link);
}
return $post_categories;
}
function wp_rest_get_tags_links($post){
$post_tags = array();
$tags = wp_get_post_terms( $post['id'], 'post_tag', array('fields'=>'all') );
foreach ($tags as $term) {
$term_link = get_term_link($term);
if ( is_wp_error( $term_link ) ) {
continue;
}
$post_tags[] = array('term_id'=>$term->term_id, 'name'=>$term->name, 'link'=>$term_link);
}
return $post_tags;
}
I believe that your only way is to change your API in a way that it returns in the first call everything you need and not only the ids, or create a new service in the API.
If you send an id and recieve the data of the post is not a way of doing that to various post in a single call.
I am posting the data to back-end using postman, which works fine. Using the same api I am trying to post the data through angular gives me the issue. But I understand that something going on wrongly between my form data with post process which i am not able to understand.
here is the post function:
.post(function( req, res ){
console.log(' called ', req.body ); 1. //getting all properties
var family = new Family();
family.username = req.body.username,
family.password = req.body.password,
family.familyLeader = req.body.familyLeader,
family.husband = req.body.husband,
family.wife = req.body.wife,
family.kids = req.body.kids;
console.log( 'family username', req.body.username ); 2.//undefined? not getting
family.save(function( err, newFamily ) {
if( err ) {
if ( err.code == 11000) {
return res.json({ success: false, message: 'A user with that username already exists. '});
}
else {
return res.send( err );
}
}
res.json({ message: 'Family created!', newFamily: newFamily });
});
})
There is 2 console I have in above call, in the first console I am getting the properties like this: ( I guess here is the issue, properties being as lable!? )
called { '{"username":"arif","password":"sadfdsa","familyLeader":"sadffsa","husband":"sadfsad","wife":"sadfsad","kids":2}': '' }
and the next console give the value like this:
family username undefined
I have removed header from $http request, and it works fine.
my code with issue is : with header
vm.createNewFamily = function() {
$http({
method : 'POST',
url : '/api/family',
data : vm.form,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success( function ( data ) {
console.log('retured!', data );
})
}
and the solution is : ( header removed )
vm.createNewFamily = function() {
$http({
method : 'POST',
url : '/api/family',
data : vm.form
}).success( function ( data ) {
console.log('retured!', data );
})
}
Experts - Please confirm the solution!
I am sending a simple post request from AngularJS to Laravel API containing a name and an image. The problem is when I submit the request, it becomes pending for a long time. I have checked the code but I do not think there's anything which causes the request to take that much time.
I am using ng-file-upload and here's what I am doing in the Angular side:
service.store = function(hotel){
console.log('uploading..');
return Upload.upload({
url: 'api/hotels',
method: 'POST',
fields: hotel,
file: [hotel.logo],
fileFormDataName: 'file[]',
headers:{
'Content-Encoding': 'gzip'
}
}).success(function (response){
console.log(response)
service.result = response;
}).error(function (response){
service.errors = response;
});
};
and for the Laravel side:
try{
$hotel = new Hotel;
$hotel->name = $request->name;
$hotel->booking_availability = 0;
$hotel->save();
$slug = str_slug($request->name, "-");
$hotel->slug = $slug."-".$hotel->id;
$hotel->save();
if(isset($_FILES['file'])){
$type = explode("/", $_FILES['file']['type'][0]);
$name = date_timestamp_get(date_create()) . "." . $type[1];
$target = 'img/hotels/logo/original/'.$name;
$tmp_name = $_FILES['file']['tmp_name'][0];
move_uploaded_file($tmp_name, "$target");
$hotel->logo = $name;
$hotel->logo_path = $target;
$hotel->save();
}
return response()->json(['hotel' => $hotel], 200);
}catch(Exception $e){
return response()->json(['error' => $e], 500);
}
What could be the possible error that takes such amount of time? How can I further debug this issue?
EDIT:
I tried using gzip to compress the content before sending the post request in order to reduce the time needed but nothing changed.