submit form from <div> html value in codeigneter - codeigniter

i have problem using form in codeigneter when to submit value from div html,
example view
<label for="title">Title:</label>
<input type="text" class="form_field" id="title" name="title" size="30" value="<?php echo set_value('title', isset($default['title']) ? $default['title'] : ''); ?>" />
<div class="form_field" name="contentbox" id="contentbox" contenteditable="true">
<?php echo set_value('contentbox', isset($default['contentbox']) ? $default['contentbox'] : ''); ?></div>
in div id="contentbox" is set contenteditable="true", and i will get dinamic value,
controller
....
$data = array( 'title' => $this->input->post('title'),
'content' => $this->input->post('contentbox'));
$this->my_model->add($data);
....
but in controller i can't get value div id="contentbox" , i have problem input to database,when i'm typing "sometext" in div id="contentbox" value always "0"

You can use the jquery cookie plugin to grab CI csrf token and include it before this function
jQuery
(function($){
var do_ajax = function(data, scope){
// depending on your version of CI csrf token name will differ
// newer versions of CI use the name in your application/config file
data = {content : data, csrf_token : $.cookie('csrf_token')}
$.ajax({
url : BASE_PATH + 'some_class/some_method',
data: data,
context : scope,
type : 'POST',
dataType : 'json',
success : function(callback){
//check the status first!
var $this = $(this);
$this.find(".msg").fadeIn();
$this.find("#contentbox").html(data);
}
});
}
var contents = {
init: function(){
if($("#editme"))
this.contentEditable();
},
contentEditable : function(){
var scope = $("#editme"),
eicon = $(".icon-editable").hide(),
emessage = $(".msg").hide(),
econtent = $("#contentbox");
econtent.hover(function(){
eicon.show();
}, function(){
eicon.hide();
});
econtent.blur(function(){
do_ajax($(this).html(), scope);
});
}
}
$(function(){
contents.init();
});
})(jQuery);
HTML
<div id="editme" class="editme">
<span class="icon-editable">✎</span>
<span class="msg">Content updated!</span>
<h4>Some relevant title</h4>
<div id="contentbox" class="contentbox" contenteditable="true">
This is editable...
</div>
</div>
CSS
div.editme{
position:relative;
background:#ffffff;
padding:30px 8px 8px 8px;
}
span.icon-editable, span.msg{
position:absolute;
top:0;
}
span.icon-editable{
left:0;
border:1px solid #d1d1d1;
border-top:0;
border-left:0;
font-size:1em;
line-height:1.2em;
}
span.msg{
right:0;
font-size:0.8em;
line-height:1.2em;
color:#fafafa;
background:green;
padding:3px;
}
PHP
class some_class extends Controller{
public function some_method(){
if($this->input->is_ajax_request())
{
$data = array(
'content' => $this->input->post('content')
);
if($this->my_model->add($data))
{
$responce = array(
'status' => 'ok'
);
}
else
{
$responce = array(
'status' => 'notok'
);
}
echo json_encode($responce);
}
else
{
show_404();
}
}
}
Test version without ajax request
CLICK HERE

Related

Why it is a bad request Ajax WordPress?

I want to publish wordpress post from front end but I am getting error 400 bad request. I have added both hooks in my php file as well. Please let me know where I am mistaken.
PHP code has two functions. 1 for adding form on front end and my ajax handler for handling ajax request. If I use core PHP, I got no error but I want to use ajax just to avoid reloading. Here I am stuck and need help from an expert. I would appreciate any help, hint or link to to useful resource.
AJAX Code:
jQuery(document).ready(function($) {
$('#submit').on('click', function(e){
e.preventDefault();
let title = $('#title').val();
let content = $('#content').val();
var formData = new FormData();
formData.append('image', document.getElementById('image-input').files[0]);
formData.append('var1', title);
formData.append('var2', content);
$.ajax({
url: 'http://localhost/wpdemo/wp-admin/admin-ajax.php',
type: 'POST',
data: formData,
processData: false, //add this
contentType: false, //and this
success: function(response) {
console.log(response);
}
});
})
});
PHP Code:
<?php
/*
Plugin Name: Notification Plugin Beta Version
Plugin URI: https://www.amirsandila.com/
Description: My first ever plugin n history of technology. You will love this plugin.
Version: 1.0
Author: Amir Sandila
Author URI: https://www.amirsandila.com
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: amirsandila
Domain Path: /languages
*/
define("version", strtotime(date("Ymd")));
function my_theme_enqueue_scripts() {
wp_enqueue_script( 'custom-jquery', 'https://code.jquery.com/jquery-3.5.1.min.js', array(), version, true );
wp_enqueue_script('ajax-script', '/wp-content/plugins/wp-plugin-demo/js/script.js',array(), version, true );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( '/admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
function my_ajax_handler() {
if (isset($_FILES['image'])){
$post_title = $_POST['var1'];
$image = $_FILES['image'];
$post_content = $_POST['var2'];
$new_post = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
'post_name' => 'pending',
);
$pid = wp_insert_post($new_post);
add_post_meta($pid, 'meta_key', true);
if (!function_exists('wp_generate_attachment_metadata'))
{
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES)
{
foreach ($_FILES as $file => $array)
{
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK)
{
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload( $file, $pid );
}
}
if ($attach_id > 0)
{
//and if you want to set that image as Post then use:
update_post_meta($pid, '_thumbnail_id', $attach_id);
}
}
}
add_action("wp_ajax_my_ajax_handler", "my_ajax_handler");
add_action("wp_ajax_nopriv_my_ajax_handler", "my_ajax_handler");
function form_shortcode_func() {
$output = '<style>
.form-container {
width: 70%;
margin: 0 auto;
border: 1px solid #ccc;
padding: 20px;
}
.form-container input[type="text"], .form-container textarea {
width: 100%;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
.form-container input[type="submit"] {
background-color: #333;
color: #fff;
border: 0;
padding: 10px 20px;
cursor: pointer;
}
</style>
<h2> Sumit Your Article! </h2>
<div class="form-container">
<form method="POST" enctype="multipart/form-data">
<input type="text" id="title" name="title" placeholder="Post Title">
<textarea name="message" id="content" rows="20" cols="30" placeholder="Post Body"></textarea>
<input type="file" id="image-input" name="image">
<button id="submit"> submit </button>
</form>
</div>';
return $output;
}
add_shortcode('form', 'form_shortcode_func');
?>
you are missing the action parameter so wordpress doesnt know which function you want.
in your js:
var formData = {
'action' : 'my_ajax_handler',
image: document.getElementById('image-input').files[0],
var1: title,
var2: content
};
$.ajax({
//Do your ajax
});
you should really be defining your ajax url differently:
$.ajax({
url: my_ajax_object.ajax_url,
//Do your ajax
});

Wordpress Sending email through Ajax without page refresh hangs on admin_ajax.php

I have this test page on a website - https://piclits.com/test-slideshow/
It displays a bunch of images/PICLITS and grabs them randomly from a folder 12 at a time into a slideshow.
I want to email the main image without refreshing the page (which would bring up 12 new images) from the email button which opens up a popup to add email addresses.
All is good - I can grab the image and mail it but the script does something wacky where it flashes on the page and then hangs up at admin-ajax.php rather than just staying on the page and sending the email.
My Form:
<div class="ajax-form-container" style="float: left">
<form id="ajaxformid" action="" method="POST">
<p>Email this PIC-LIT to a friend.<br />You may include multiple emails if you separate them with a comma.</p>
<ul style="list-style-type: none;">
<li>Email: <textarea name="piclit_email" id="piclit_email" rows="4" cols="50" autofocus=""></textarea><input type="hidden" name="founder_piclit" id="founder_piclit" value=""></li>
<li><input type="hidden" name="piclit_bcc" class="piclit_bcc" value="0"></li>
<li>bcc: <input type="checkbox" name="piclit_bcc" class="piclit_bcc" value="1">
<?php wp_nonce_field( 'fiveb_ajax_nonce', 'fiveb_nonce_field' ); ?></li>
<li><input type="submit" name="submit" value="Send"></li>
</ul>
</form>
<div id="ajax_success" style="display: none">Email sent.</div>
<div id="ajax_error" style="display: none">There was an error. Sorry your email was not sent.</div>
</div>
Javascript
<script>
jQuery('#ajaxformid').submit(function(e) {
e.preventDefault();
var piclit_email = jQuery( "#piclit_email" ).val();
if (piclit_email == '')
alert("Please fill in all fields to send an email.");
else {
var founder_piclit = jQuery( "#founder_piclit" ).val();
// alert (founder_piclit);
var piclit_bcc = jQuery('.piclit_bcc').val();
var formData = {
piclit_email: piclit_email,
founder_piclit: founder_piclit,
piclit_bcc: piclit_bcc,
action: 'fiveb_ajax_mail',
};
jQuery.ajax({
type : 'POST',
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>',
dataType : 'json',
data : formData,
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
}
});
</script>
and php:
function fiveb_function() {
$subject = 'View A Founder PIC-LIT from piclits.com';
$piclit_email = strval($_REQUEST['piclit_email']);
$founder_piclit = strval($_REQUEST['founder_piclit']);
$piclit_bcc = strval($_REQUEST['piclit_bcc']);
if ($piclit_bcc) {
$headers[] = 'Bcc: '.$piclit_email;
}
$message = '<html><head><title>Founder PIC-LIT</title></head><body><table border="0" cellspacing="2" cellpadding="20" bgcolor="#ffffff" width="100%"><tbody><tr><td></td><td width="600"><p style="text-align: center">Hello!<br />View A Founder PIC-LIT from piclits.com.</p></td><td></td></tr><tr><td></td><td><img src="'.$founder_piclit.'" alt="Founder PIC-LIT" width="600" style="display:block;width:100%" /></td><td></td></tr></tbody></table></body></html>';
$headers[] = 'From: PIC-LITS <hello#piclits.com>';
$headers[] = 'Content-Type: text/html; charset=UTF-8';
if ($bcc) $sent_mail = wp_mail( "", "$subject", $message, $headers );
else $sent_mail = wp_mail( "$piclit_email", "$subject", $message, $headers );
if ($sent_mail) {
echo ('email sent');
die();
} else {
echo ('There was an error. Sorry your email was not sent.');
die();
}
}
add_action("wp_ajax_fiveb_function", "fiveb_function");
add_action("wp_ajax_nopriv_fiveb_function", "fiveb_function");
Seems like I am so close but I cannot get the script to stop hanging up on admin-ajax.php. Any help would be so appreciated! Maybe it has something to do with my popup? I am out of ideas
Your code will look like this.
Note - Form action should be blank.
<form action="" method="POST" id="ajaxformid">
</form>
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
wp_localize_script( 'custom-js', 'fiveb_ajax_mail', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
add_action("wp_ajax_fiveb_ajax_mail", "fiveb_ajax_mail");
add_action("wp_ajax_nopriv_fiveb_ajax_mail", "fiveb_ajax_mail");
function fiveb_ajax_mail()
{
$formdata = $_post['formdata'];
wp_mail($to,$subject,$message,$header);
return 'true';
wp_die();
}
//add below js in custom.js file
$('#ajaxformid').submit(function (e) {
e.preventDefault();
jQuery.ajax({
type: "post",
dataType: "json",
url: fiveb_ajax_mail.ajax_url,
data : {action: "fiveb_ajax_mail","formdata":"your form data variable place here"},
success: function(msg){
console.log(msg);
}
});
}
In my local system, it is working fine.

How upload an image in nuxt js and laravel 7

I develop an ecommerce application in nuxtjs frontend and laravel backend.But it is difficult to upload image and save it in the database.Can anyone help me solve the problem ?
Here example of Nuxt Or Vuejs image uploader with Laravel API. I left a comment inside the code for you.
First of all, you must make upload.vue component with this content.
<template>
<div class="container">
<label class="custom-file" for="file">
{{files.length ? `(${files.length}) files are selected` : "Choose files"}}
<input #change="handleSelectedFiles" id="file" multiple name="file" ref="fileInput" type="file">
</label>
<!--Show Selected Files-->
<div class="large-12 medium-12 small-12 cell">
<div class="file-listing" v-for="(file, key) in files">{{ file.name }} <span class="remove-file" v-on:click="removeFile( key )">Remove</span></div>
</div>
<!--Submit Button && Progress Bar-->
<div>
<button #click="upload">Start Upload</button>
- Upload progress : {{this.progress}}
</div>
</div>
</template>
<script>
export default {
data() {
return {
files : [],
progress: 0
}
},
computed: {
/*The FormData : Here We Make A Form With Images Data To Submit.*/
form() {
let form = new FormData();
this.files.forEach((file, index) => {
form.append('files[' + index + ']', file);
});
return form;
}
},
methods : {
handleSelectedFiles() {
let selectedFiles = this.$refs.fileInput.files;
for (let i = 0; i < selectedFiles.length; i++) {
/*Check Already Has Been Selected Or Not ...*/
let isFileExists = this.files.find(file => file.type === selectedFiles[i].type && file.name === selectedFiles[i].name && file.size === selectedFiles[i].size && file.lastModified === selectedFiles[i].lastModified);
if (!isFileExists)
this.files.push(selectedFiles[i]);
}
},
removeFile(key) {
this.files.splice(key, 1);
},
upload() {
const config = {
onUploadProgress: (progressEvent) => this.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
};
this.$axios.post('host-url/upload-image', this.form, config)
.then(res => {
this.progress = 0;
this.files = [];
console.log(res)
})
.catch(err => console.log(err))
}
}
}
</script>
<style>
.custom-file {
padding: 1.2rem;
border-radius: .8rem;
display: inline-block;
border: 2px dashed #a0a0a0;
}
.custom-file input {
display: none;
}
</style>
After this, we must make an endpoint in Laravel API routes like this:
Route::post('/upload-image', 'UploadController#image');
In the last, Put this codes on upload
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function image(Request $request)
{
$request->validate([
'files' => ['required', 'array'],
'files.*' => ['required', 'image','min:5','max:5000']
]);
$uploadedFiles = [];
foreach ($request->file('files') as $file) {
$fileName = bcrypt(microtime()) . "." . $file->getClientOriginalExtension();
$file->move('/uploads', $fileName);
array_push($uploadedFiles, "/uploads/{$fileName}");
}
return response($uploadedFiles);
}
}
Attention: Progress in localhost is so fast, then if you want to test it in local upload a file largest than 50 MB.

ajax is not able to call the function of codeigniter

This is Welcome controller method
public function send_otp()
{
echo 'in';
die;
$phone = $_POST['mobile'];
if ($phone != '') {
$mobile_detail = $this->welcome_model->check_if_already_mobile_no($phone);
if (!empty($mobile_detail)) {
if ($mobile_detail['is_verified'] == 'yes') {
$message = 'Already Verified.';
echo json_encode(array('status' => 'error', 'message' => $message));
exit;
} else {
$this->welcome_model->delete_mobile_no($phone);
}
}
$otp = self::generateRandomNo();
$this->welcome_model->insert_mobile_detail($phone, $otp);
$link = file_get_contents("http://49.50.67.32/smsapi/httpapi.jsp?username=aplusv&password=aplusv1&from=APLUSV&to=$phone&text=$otp&coding=0");
$status = '';
if ($link != '') {
$status = 'success';
$message = 'Successfully Otp send to your no.';
} else {
$status = 'error';
$message = 'Error in sending OTP.';
}
echo json_encode(array('status' => $status, 'message' => $message));
exit;
}
}
This is model
public function check_if_already_mobile_no($mobile_no = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no));
return $query->row_array();
}
public function get_mobile_details($mobile_no = null, $otp = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no, 'otp' => $otp));
return $query->row_array();
}
public function insert_mobile_detail($phone, $otp)
{
$this->mobile_no = $phone;
$this->otp = $otp;
$this->is_verified = 'no';
$this->created_at = date('Y-m-d H:i:s');
$this->db->insert('mobile_sms', $this);
}
This is view
<div class="container" style="margin-top: 25px;">
<div class="row">
<div class="col-md-12" id="response_msg"></div>
<div class="col-md-4" id="enter_mobile">
<form method="POST" action="#">
<div class="form-group">
<label for="phone">Phone </label>
<input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter Mobile">
</div>
<button type="button" name="send_mobile" id="send_otp" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
// var base_url = "<?php echo base_url();?>";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(function () { // start of doc ready.
$("#send_otp").on('click', function (e) {
var mobile = $('#mobile').val();
alert(mobile);
$.ajax({
url: '<?php echo site_url('index.php/welcome/send_otp'); ?>',
data: {'mobile': mobile},
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == 'success') {
$('#response_msg').html('<div class="alert alert-success" role="alert">' + data.message + '</div>');
$('#mobile_no').val(mobile);
$('#enter_mobile').hide();
$('#verify_otp_form').show();
} else {
$('#response_msg').html('<div class="alert alert-danger" role="alert">' + data.message + '</div>');
}
}
});
});
in ajax is not getting call ie $.ajax is not working here and my controller ie welcome with method send_otp is not called here.
why my function in controller is not getting called
how to solve the issue
what is the proper way to call the controller function using base_url
i have check the console also it is not showing any error
I noticed that you are using site_url() slightly incorrectly: don't write index.php there, just use site_url('welcome/send_otp')
Don't forget you have an unconditional die() at the top of your send_otp method - it will prevent any code below itself from executing

ajax form request from a while - confuse variable

I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.

Resources