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.
Related
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
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.
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
}
});
}
}
I have a view in which I need after a click to send a javascript variable to a controller which contains a form that I send to the database.
So after the click, I'm using ajax to call my controller and load the html on the same view like this:
$(".month").click(function(){
var click = $(this);
var month = click.val();
var year = $("#years").val();
var url = Routing.generate('av_platform_formulaire');
$.ajax(url,
{
type: 'GET',
data: {"month": month,
"year" : year},
dataType: "html",
success: function (data) {
$('#content').empty();
$('#content').append(data);
},
error : function(jqXHR, textStatus, errorThrown){}
});
});
So far there is no problem, my view containing the form is loading correctly and I receive the data I sent via the ajax request but when I fill my form and try to submit it, the page is refreshing and it's like nothing happens...
Here is my 2 controllers (the second is the problematic one):
public function saisieAction(Request $request){
$thisyear = date("Y");
return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
array(
'year' => $thisyear
));
}
public function formulaireAction(Request $request){
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
//$repository = $em->getRepository('AvPlatformBundle:NoteDeFrais');
// Create the form
$form = $this->get('form.factory')->createBuilder(FormType::class)
->add('ndf', CollectionType::class, array(
'entry_type' => NoteDeFraisType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
))
->getForm();
if ($request->isXmlHttpRequest()){
$month = $request->get('month');
$year = $request->get('year');
$sub_date = $month . '/' . $year;
}
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
// After debugging, the code inside the if is not executed
$notesDeFrais = $form['ndf']->getData();
foreach ($notesDeFrais as $ndf) {
$ndf->setUser($user);
$ndf->setMois($sub_date);
$em->persist($ndf);
}
$em->flush();
}
return $this->render('AvPlatformBundle:Platform:formulaire.html.twig',
array(
'form' => $form->createView()
));
}
My view containing the form:
<div id="ms_form">
{{ form_start(form) }}
<div id="bloc_saisie" class="fieldset">
<fieldset>
<div id="form_ndf" class="form_ndf" data-prototype="
{% filter escape %}
{{ include('AvPlatformBundle:Platform:prototype.html.twig', { 'form': form.ndf.vars.prototype }) }}
{% endfilter %}">
</div>
<div class="buttons">
<button type="button" class="fas fa-plus" id="add_ndf"></button>
<input type="submit" class="btn btn-primary btn-lg" id="next_button" >
</div>
</fieldset>
</div>
{{ form_row(form._token) }}
{{ form_end(form, {'render_rest': false}) }}
</div>
Can someone please tell me how to output data from my controller to an HTML form. I want to change the label of an anchor from "Like" to "Liked" if the user has already clicked the link previously.
Here is the HTML.
<section class="row posts">
<div class="col-md-6 col-md-3-offset">
<header><h3>other posts</h3></header>
#foreach($posts as $post)
<article class="post">
<p>{{ $post->content }}</p>
<div class="info">Posted by {{ $post->user->username }} on {{ $post->created_at }}</div>
<div class="interaction">
Like
#if(auth()->user() === $post->user)
|
Edit |
Delete
#endif
</div>
</article>
#endforeach
</div>
<script>
var token = '{{ session()->token() }}';
var urlLike = '{{ route('like') }}';
</script>
</section>
The JavaScript to get the postid from the form:
...
$('.like').on('click', function (event) {
event.preventDefault();
postId = event.target.dataset.postid;
var isLike = event.target.previousElementSibling==null ? true:false;
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike, postId: postId, _token: token}
})
.done(function () {
//change the page
})
})
...
The route:
Route::post('/like',[
'uses' => 'PostController#postLikePost',
'as' => 'like'
]);
Finally, can someone please tell me how to send the output from the controller to the HTML form?
public function postLikePost(Request $request)
{
$post_id = $request['postId'];
$is_like = $request['isLike'] === 'true' ? true : false;
$post = Post::find($post_id);
if (!$post) {
return null;
}
$user = Auth::user();
$like = $user->likes()->where('post_id', $post_id)->first();
if ($like) { // user already liked the post
$like->delete();
return null; // output to "Like" in the html form here
}
$like = new Like();
$like->post_id = $post->id;
$like->user_id = $user->id;
$like->save(); // output to "Liked" in the html from here
return null;
}
The label of the Like anchor should change from Like to Liked if the user has already like the post.
I'd set up both as POSTs and then in your success block query the result and set to either like or liked. Something like:
success: function (data) {
document.getElementById("something").innerHTML = "Liked";
}
You can do it something like this, change it as per your need though.
public function postLikePost(Request $request)
{
$post = Post::where('id', $request->get('post_id'))->first();
if(!$post){
return response()->json(['status' => 1, 'message' => 'post not found']);
}
if($post->liked == 1)//change it as per your model
{
return response()->json(['status' => 2, 'message' => 'already liked']);
}
$post->status = 1;
$post->save();
return response()->json(['status' => 3, 'message' => 'liked']);
}
and in your ajax success
success: function(response){
if(response.status == 1){
window.alert('Post Not Found')
}
else{
document.querySelector('#likeBtn').innerHTML = 'liked'
}
like button
Like