Angular JS send html to data base - javascript

I m sending html < p >hello< /p>
<div class="input-field">
<input id="price" type="number" ng-model="productData.price" ng-init="productData.price = ''" >
<label for="price">Price</label>
</div>
<div id="editor3" class="ql-container ql-snow">
<div class="ql-editor" data-gramm="false" contenteditable="true">
<p>hello</p>
</div>
</div>
<input type="hidden" ng-model="productData.description">
to angular js code, But it is not working. I am new to angular js. the fifth line below I thing not taking data from HTML code
$scope.addProdcut = function (productData) {
if ($scope.validateProduct(productData)) {
$scope.productLoader = true;
$('#productSubmit').attr('disabled', true);
$scope.productData.description = $('#editor3 .ql-editor').html() != '' ? $('#editor3 .ql-editor').html() : '';
var url = webroot + 'products/addProduct';
$scope.data = {
"type": "json",
"data": productData,
"image": $scope.productImage
};
$http.post(url, $scope.data, {
headers: {
'X-CSRF-Token': token
}
});
}
}
Controller file
public function addProduct()
{
if ($this->request->is('post')) {
$content = $this->request->input('json_decode', true);
$data = $content['data'];
$file = '';
if ($content['image'] != '') {
$file = date('ymd') . time() . '.' . 'jpg';
$path = WWW_ROOT . 'img/products/' . $file;
$this->base64_to_jpeg($content['image'], $path);
}
$products = TableRegistry::get('Products');
$query = $products->query()->insert(['item', 'price', 'description', 'image', 'status', 'added_by', 'created'])
->values([
'item' => $data['name'],
'price' => $data['price'],
'description' => $data['description'],
'image' => $file,
'status' => 1,
'added_by' => $this->loggedInUser['id'] . '||' . $this->loggedInUser['username'],
'created' => date("Y-m-d\TH:i:s"),
])->execute();
echo json_encode(['status' => 'success']);
exit;
}
}
it is a word editor in form, from where I want to save HTML code (from word editor) in data base using a hidden input field. by sending data ng-model to that hidden input field

You are storing the value in $scope.productData.description and then sending productData, instead, you should send $scope.productData.description.
$scope.addProdcut = function(productData) {
if ($scope.validateProduct(productData)) {
$scope.productLoader = true;
$('#productSubmit').attr('disabled', true);
$scope.productData.description = $('#editor3 .ql-editor').html() != '' ? $('#editor3 .ql-editor').html() : '';
var url = webroot + 'products/addProduct';
$scope.data = {
"type": "json",
"data": $scope.productData.description,
"image": $scope.productImage
};
$http.post(url, $scope.data, {
headers: {
'X-CSRF-Token': token
}
});
}
}

Related

Wordpress Category Filtering Stuck

Everytime I click a category it shows only "Filtering..." and not loading all the post.
Filtering Issue
HTML
<div class="filters"> <span class="filter active" data-set="all"><span>Show all</span></span> <?php $categories = get_categories(array( 'hide_empty' => true, 'exclude' => array(1, 143) )); foreach ($categories as $category) : ?> <span class="filter" data-set="<?= $category->slug ?>"><span><?= $category->name ?></span></span> <?php endforeach; ?> </div>
SCRIPT
`(($) => {
const filters = $("#filterBar .filters");
const articles = $("#all-posts .articles");
filters.children('.filter').click(function(e) {
e.preventDefault();
const button = $(this),
loader = $("#loader"),
data = {
'action': 'filterposts',
'category': $(this).data('set')
};
$.ajax({
url : latest_reads_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
articles.html("<span class='message'>Filtering...</span>");
loader.remove();
filters.find('.active').removeClass('active');
button.addClass('active');
},
success : function( data ){
if( data ) {
data = JSON.parse(data);
articles.hide().html(data.posts).slideDown(400);
if (data.max_pages > 1) {
articles.after('<div id="loader">'+
'<span class="ibtn secondary large" id="loaderAction" data-category="'+data.category+'" data-maxpages="'+data.max_pages+'">Load more</span>'+
'</div>');
}
} else {
articles.html("<span class='message'>No post found for filter</span>");
}
}
});
});
})(jQuery);`
I wanted to display all category post

Wordpress how to use Ajax to show new data returned from successful insert_post()?

After a successful Ajax insert of an entry, I would like to see what the ID and url of that same entry is and display it in a modal window without refreshing the page
Any way to get this data from success: function (response) {}? This is the code I have to make a new entry with ajax which works perfect:
<script>
$("#enquiry_email_form").on("submit", function (event) {
event.preventDefault();
var form= $(this);
var ajaxurl = form.data("url");
var detail_info = {
post_title: form.find("#post_title").val(),
post_description: form.find("#post_description").val()
}
if(detail_info.post_title === "" || detail_info.post_description === "") {
alert("Fields cannot be blank");
return;
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
post_details : detail_info,
action: 'save_post_details_form' // this is going to be used inside wordpress functions.php// *esto se utilizará dentro de las functions.php*
},
error: function(error) {
alert("Insert Failed" + error);
},
success: function(response) {
modal.style.display = "block"; * abre la ventana modal*
body.style.position = "static";
body.style.height = "100%";
body.style.overflow = "hidden";
}
});
})
</script>
<button id="btnModal">Abrir modal</button>
<div id="tvesModal" class="modalContainer">
<div class="modal-content">
<span class="close">×</span> <h2>Modal</h2> * Ventana modal mostrar le url y ID generado *
<p><?php ***echo $title_post, $url, $ID*** ?></p>
</div>
</div>
Archive funtions.php
function save_enquiry_form_action() {
$post_title = $_POST['post_details']['post_title'];
$post_description = $_POST['post_details']['post_description'];
$args = [
'post_title'=> $post_title,
'post_content'=>$post_description,
'post_status'=> 'publish',
'post_type'=> 'post',
'show_in_rest' => true,
'post_date'=> get_the_date()
];
$is_post_inserted = wp_insert_post($args);
if($is_post_inserted) {
return "success";
} else {
return "failed";
}
}
When you use wp_insert_postDocs function, it'll return the post id.
It returns the post ID on success. The value 0 or WP_Error on failure.
First you could initiate an empty array and call it, let's say, $response and populate it based on the returned value from wp_insert_post function.
Then, we could use the id to get the permalink as well, using get_permalinkDocs.
And at last, we could send that array back to the client-side by using wp_send_json_successDocs function.
So your code on the php side would be something like this:
function save_enquiry_form_action() {
$response = array(
'error' => '',
'success' => '',
'post_id' => '',
'post_url' => '',
);
$post_title = sanitize_text_field($_POST['post_details']['post_title']);
// Note we could have used 'sanitize_title()' function too!
$post_description = sanitize_textarea_field($_POST['post_details']['post_description']);
$args = array(
'post_title' => $post_title,
'post_content' => $post_description,
'post_status' => 'publish',
'post_type' => 'post',
'show_in_rest' => true,
'post_date' => get_the_date()
);
$post_id = wp_insert_post($args);
if($post_id){
$response['success'] = true;
$response['error'] = false;
$response['id'] = $post_id;
$response['post_url'] = get_permalink($post_id);
}else{
$response['success'] = false;
$response['error'] = true;
}
wp_send_json_success($response);
exit;
}
Note:
I've used sanitize_text_fieldDocs function to sanitize the $_POST['post_details']['post_title'] value and sanitize_textarea_fieldDocs function to sanitize the $_POST['post_details']['post_description'] value.
When you receive the response on the client-side, you could check for $response['success'] and $response['error'] values.
On the javascript side
As you can see on the following screenshot, data returns as data object. To access data you could use response.data.success, response.data.error, response.data.id and response.data.post_url.

Laravel how to retrieve name with user_id using angular?

I'm only able to fetch data with title and body attribute, but when i get data for the name it shows up empty when i refresh the page but shows when i submit automatically.
For some reason angularjs is not retrieving the name successfully.
Note: I'm using laravel.
For example here:
Here is the server side:
PostController
public function getPosts() {
$posts = Post::with('user')->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function storePost(Request $request) {
$data = request()->validate([
'title' => 'required|max:120',
'body' => 'required|max:1000'
]);
$data['user_id'] = auth()->user()->id;
$data['name'] = auth()->user()->name;
$post = Post::create($data);
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
// return redirect('/home')->withMessage('A new post was created.');
return $response;
}
main.js
$scope.myposts = {};
$scope.addPost = function() {
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
console.log(data);
$scope.myposts.push(data.data);
});
$scope.post.title = '';
$scope.post.body = '';
};
$scope.deletePost = function(post) {
var index = $scope.myposts.indexOf(post);
if (index != -1) {
$scope.myposts.splice(index, 1);
}
$http.delete('auth/post/' + post.id);
};
$scope.getPosts = function() {
$http.get('/auth/posts').then(function(data) {
$scope.myposts = data.data;
}).then(function(data, status, header, config) {});
};
HTML:
<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
<div id="eli-style-heading" class="panel-heading">
<% post.title %>
</div>
<div class="panel-body panel">
<figure>
<p>
<% post.body %>
</p>
by:
<p>
<% post.user.name %>
</p>
</figure>
<span><button ng-click="deletePost(post)">x</button></span>
</div>
</div>
When i first add content without refresh(asynchronously)
on page refresh
above
(different log for different post)
Your reload page is okay since
$posts = Post::with('user')->get();
returns
{
"title": "title",
"body": "body",
"user": {
"name": "name"
}
}
and in your angular you display it by
<% post.user.name %>
So the solution to display it when you added is to restructure your json object before pushing to array
$scope.addPost = function() {
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
console.log(data);
data.data['user'] = {
name: data.data.name
}
$scope.myposts.push(data.data);
});
$scope.post.title = '';
$scope.post.body = '';
};

How to get post filedata in jQUERY

I have a form with three post data along with that I have to append a filedata(input type="file"). I didn't get the filedata, when I alert the post data in js. How can I resolve it? please suggest a solution..
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Q0qdk.png
$('#employerid_contactus').click(function (event) {
cs_data_loader_load('#cs_employer_contactus #loader-data');
var default_message = jQuery("#cs_employer_contactus").data('validationmsg');
event.preventDefault();
var ajaxurl = jQuery(".cs-profile-contact-detail").data('adminurl');
var employerid = jQuery(".profile-contact-btn").data('employerid');
var captcha_id = jQuery(".cs-profile-contact-detail").data('cap');
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: "html",
data: $('#ajaxcontactemployer').serialize() + "&employerid=" + employerid + "&action=ajaxcontact_employer_send_mail",
success: function (response) {
jQuery("#ajaxcontactemail").removeClass('has_error');
jQuery("#ajaxcontactname").removeClass('has_error');
jQuery("#ajaxcontactcontents").removeClass("has_error");
var pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
var response_data = response.split("|");
if (jQuery("#ajaxcontactname").val() == '') {
jQuery("#ajaxcontactname").addClass('has_error');
} else
if (!pattern.test(jQuery("#ajaxcontactemail").val())) {
jQuery("#ajaxcontactemail").addClass('has_error');
} else
if (jQuery("#ajaxcontactcontents").val().length < 35) {
jQuery("#ajaxcontactcontents").addClass('has_error');
}
var error_container = '';
if (response_data[1] == 1) {
error_container = '<div class="alert alert-danger"><button aria-hidden="true" data-dismiss="alert" type="button" class="close">×</button><p><i class="icon-warning4"></i>' + response_data[0] + '</p></div>';
jQuery("#ajaxcontact-response").html(error_container);
} else {
error_container = '<div class="alert success"><button aria-hidden="true" data-dismiss="alert" type="button" class="close">×</button><p><i class="icon-warning4"></i>' + response_data[0] + '</p></div>';
jQuery("#ajaxcontact-response").html(error_container);
jQuery("#ajaxcontactcontents").val('');
captcha_reload(ajaxurl, captcha_id);
}
jQuery('#cs_employer_contactus #loader-data').html('');
}
});
return false;
});
this is how form view code:
<div class="input-filed"> <i class="icon-mobile4"></i>
<?php
$cs_opt_array = array(
'id' => '',
'std' => isset($login_user_phone) ? esc_html($login_user_phone) : '',
'cust_id' => "ajaxcontactphone",
'cust_name' => "ajaxcontactphone",
'classes' => 'form-control',
'extra_atr' => 'placeholder="' . esc_html__('Phone Number', 'jobhunt') . '"',
);
$cs_form_fields2->cs_form_text_render($cs_opt_array);
?>
</div>
<div class="input-filed"> <i class="icon-mobile4"></i>
<?php
$cs_opt_array = array(
'id' => '',
'std' => '',
'cust_id' => "ajaxcontactfile",
'cust_name' => "ajaxcontactfile",
'cust_type' => "file",
'classes' => 'form-control',
'extra_atr' => '',
);
$cs_form_fields2->cs_form_text_render($cs_opt_array);
?>
</div>
When serialize the postdata I didn't get the filedata
I need to send an email using ajax. I can send name, email and phone number but not the file. I need to include file along with these fields. When I alert the serialized data in js it not showing the filedata. How can I append the file with postdata. Please help me with this.

Save path image with Ajax in Laravel

I can save all data varchar/text element from my form, but I can't save my path image.
Whats is wrong with my code?
Lets see my create.blade.php I can save value of var deadline but I can't save value of var path:
Form::open(array('url' => 'imagesLoker', 'files' => true))
<form class="form-horizontal">
<div class="box-body">
<div class="form-group">
{!!Form::label('Deadline Lowongan : ')!!}
{!!Form::date('deadline',null,['id'=>'deadline','class'=>'form-control','placeholder'=>'Deadline Lowongan'])!!}
</div>
<div class="form-group">
{!!Form::label('Image Lowongan : ')!!}
{!!Form::file('path') !!}
</div>
</div><!-- /.box-body -->
</form>
{!!Form::close()!!}
This is my Controller:
public function store(Request $request)
{
Lowongan::create($request->all());
return "data all";
}
This is my Ajax to create the data:
$("#createLoker").click(function(){
var datas = $('form').serializeArray();
var route = "http://localhost:8000/lowongan";
var token = $("#token").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post(route,{
deadline: $("#deadline").val(),
path: $("#path").val()
}).done(function(result){
console.log(result);
});
});
I don't know this is important or no to setting parse data in my Modal, but I just put this code in my Modal:
class Lowongan extends Model
{
protected $table = 'Lowongan';
protected $fillable = ['path','deadline'];
public function setPathAttribute($path){
$this->attributes['path'] = Carbon::now()->second.$path->getClientOriginalName();
$name = Carbon::now()->second.$path->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($path));
}
}
And the last I set the directory to save the image. This is setting in the config/filesystem:
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path('imagesLoker'),
],
I can save the data deadline but no for image :( .. If there is any idea for how to save the image path, I will be pleased to know it.
In your form you have to allow file upload option in laravel like.
Form::open(array('url' => 'foo/bar', 'files' => true))
check the file upload section of laravel doc
Hope it helps..
please follow these steps
in view
change {!!Form::file('path') !!} to {!!Form::file('file') !!}
In controller
please note i have set the upload path to root/public/uploads/ folder
public function store(Request $request)
{
$file = Input::file('file');
$path = '/uploads/';
$newFileName = Carbon::now()->second.$file->getClientOriginalName(). '.' . $file->getClientOriginalExtension();
// Move the uploaded file
$upSuccess = $file->move(public_path() . $path, $newFileName);
$result = file_exists(public_path() . $path . $newFileName);
$fileData =[
'fileType' => $file->getClientOriginalExtension(),
'filePath' => substr($path, 1) . $newFileName
];
Input::merge(array('path' => $fileData["filePath"]));
Lowongan::create($request->all());
return "data all";
}

Categories