Hi am trying to upload an image and insert data into items table ( phpmyadmin ) It works if i don't user ajax but when i tried to upload using ajax it didn't work
This is my html5 script
<form id="InsertItemTodatabase" enctype="multipart/form-data" action="requests/newItem.php" method="post" class="add-new-item-form-form">
<div class="form-group">
<input type="text" name="itemName" placeholder="Item name" class="form-control" id="itemNameJs">
</div>
<div class="form-group">
<input type="text" name="itemDesc" placeholder="Item Description" class="form-control" id="itemDescJs">
</div>
<div class="form-group">
<input type="text" name="itemPrice" placeholder="Item Price" class="form-control" id="itemPriceJs">
</div>
<div class="form-group">
<?php $fetch = fetchData( '*', 'category', '' , '', '', $fetch="fetchAll" ); ?>
<select class="form-control" name="category" id="itemCatJs">
<option value="0">Select Category</option>
<?php
foreach ($fetch as $data) {
echo '<option value="' . $data[ 'cat_id' ] . '">' . $data[ 'cat_name' ] . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<input type="text" name="itemAmount" placeholder="Amount" class="form-control" id="itemAmountJs">
</div>
<div class="form-group">
<label for="uploadItemPic" class="btn btn-primary">Upload Item Picture</label>
<input type="file" id="uploadItemPic" name="itemPic" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="submitAddItemForm" id="submitNow">
<i class="ti-plus"></i>
Add Item
</button>
</div>
</form><!-- /.add-new-item-form-form -->
And this is my jQuery/Ajax script for uplaoding data.
$(document).on( 'submit', '#InsertItemTodatabase', function(e){
e.preventDefault();
var file_data = $('#uploadItemPic').prop('files')[0],
name = $( '#itemNameJs' ).val(),
desc = $( '#itemDescJs' ).val(),
price = $( '#itemPriceJs' ).val(),
cat = $( '#itemCatJs option:selected' ).val(),
amount = $( '#itemAmountJs' ).val(),
image = $( '#uploadItemPic' ).val();
var file = new FormData();
file.append('file',$('#uploadItemPic')[0].files[0]);
var ajaxUrl = $(this).attr('action');
alert(file);
$.ajax({
url: ajaxUrl, // point to server-side PHP script
type: 'POST',
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: {
name : name,
desc : desc,
price : price,
cat : cat,
amount : amount,
image : image,
file
},
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
And this is my newItem.php
<?php
if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ){
include "../database\connect.php";
$item_name = $_POST[ 'itemName' ];
$item_desc = $_POST[ 'itemDesc' ];
$item_price = $_POST[ 'itemPrice' ];
$item_amount = $_POST[ 'itemAmount' ];
$item_category = $_POST[ 'category' ];
$formErrors = array();
if( empty( $item_name ) ){
$formErrors[] = 'You should type the item name';
}
if( empty( $item_desc ) ){
$formErrors[] = 'You should add item description';
}
if( empty( $item_price ) ){
$formErrors[] = 'You should add item price';
}
if( empty( $item_amount ) ){
$formErrors[] = 'You should type item amount';
}
if( $item_category == 0 ){
$formErrors[] = 'You should select item category';
}
$item_picture = $_FILES[ 'itemPic' ];
$picture_name = $item_picture[ 'name' ];
$picture_temp = $item_picture[ 'tmp_name' ];
$picture_size = $item_picture[ 'size' ];
$picture_type = $item_picture[ 'type' ];
if( empty( $picture_name ) ){
$formErrors[] = 'You should select item picture';
}
/*
Picture Extension
-------------------
*/
$extensions = array( "png", "jpg", "jpeg", "gif" );
$picture_name_explosion = explode('.', $picture_name);
$extension_name = end( $picture_name_explosion );
$extension = strtolower( $extension_name );
if( !in_array($extension, $extensions) && !empty( $picture_name ) ){
$formErrors[] = 'This extension is not allowed';
}
if($picture_size > 4194304){
$formErrors[] = 'Image Can\'t Be Larger Than 4MB';
}
if( empty( $formErrors ) ){
$item_image = rand( 0, 1000000 ) . '_' . $picture_name;
move_uploaded_file($picture_temp, '../layouts/images/items' . $item_image);
$stmt = $db->prepare( "INSERT INTO Items( item_name, item_description, item_pic, item_price, amount, added_date, cat_id ) VALUES( :zname, :zdesc, :zpic, :zprice, :zamount, :zdate, :zcat ) " );
$stmt->execute( array(
'zname' => $item_name,
'zdesc' => $item_desc,
'zpic' => $item_image,
'zprice' => '$' . $item_price,
'zamount' => $item_amount,
'zdate' => date( 'Y-m-d h:i:s' ),
'zcat' => $item_category
) );
echo date( 'Y-m-d h:i:s' );
}
foreach ($formErrors as $error) {
var_dump( $error );
}
}
When i tried to upload i get an error that $_POST data is not defined in newItem.php
Please help me in that, And thanks in advance!
You don't need to write so much of code, instead
try to give name attribute to your form tab.
<form id="jqdata" enctype="multipart/form-data" method="post" class="add-new-item-form-form" name="jqdata" action="requests/newItem.php">
Now your ajax call:
var ajaxUrl = $(this).attr('action');
$(document).ready(function(){
$('#submitNow').click(function(e){
e.preventDefault();
var form = $("#jqdata");
var formdata = new FormData(form[0]);
$.ajax({
url: ajaxUrl,
data: formdata,
processData: false,
contentType: false,
type: 'POST',
success: function (output) {
alert(output);
$("#jqdata")[0].reset(); //reset all data from form.
}
});
});
});
Try this and do let me know if it works.
Change your variable assignments as mentioned below:
$item_name = $_POST[ 'name' ];
$item_desc = $_POST[ 'desc' ];
$item_price = $_POST[ 'price' ];
$item_amount = $_POST[ 'amount' ];
$item_category = $_POST[ 'cat' ];
The Data posted to newitems file is the one that you have set in your ajax request. So the field names that you are using should be changed to match the ones set in your ajax data.
Related
I am trying to insert data in custom table in wordpress while creating plugin using AJAX. But I failed to do.
here is the code of contact.php where I register scripts
add_action('wp_enqueue_scripts', 'setting_up_scripts_contact_form_wp');
function setting_up_scripts_contact_form_wp() {
wp_register_style( 'contact-custom-style',plugins_url('public/css/style.css', __FILE__) );
wp_enqueue_style( 'contact-custom-style');
wp_enqueue_script( 'cfajax-con', plugins_url('includes/submit-form.js', __FILE__),array(),false,true );
// wp_enqueue_script( 'wpforajax_con_test', plugins_url('public/js/test.js', __FILE__) );
// wp_register_script('wpforajax_con_test', plugin_dir_url(__FILE__) . 'test.js', true);
wp_localize_script(
'jsforcon-frontend-js',
'jsforcon_globals',
[
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'jsforcon_insert_nonce' )
]
);
}
contact form is
<div class="container">
<div class="row display_big justify-content-center">Contact Us</div>
<div class="row justify-content-center">
<div class="col-md-6 ">
<form>
<input type="text" id="conName" class="txt_trans txt_full " name="conName" placeholder="Name" required><br><br>
<input type="text" id="conMail" name="conMail" class="txt_trans txt_full" placeholder="Mail" required><br><br>
<small id="emailHelp" class="form-text text-muted p-0 m-0">We takes your mail id for sending reply to you.</small>
<textarea id="conContant" class="txt_a_trans txt_full " name="conContant"cols="30" rows="10" placeholder="content" required></textarea>
<div class="con_error_msg"></div>
<button type="button" class="btn_submit" id="saveContact" value="load data" >Contact Us</button><br><br><br><br>
</form>
</div> </div></div>
<?php echo "<script type='text/javascript'>var ajaxurl = '".admin_url('admin-ajax.php')."'</script>"; ?>
and the insert.php file is here
<?php
function my_contact_form(){
require( dirname(__FILE__).'/wp-load.php' );
global $wpdb;
$table_name = 'wp_contact_form';
$wpdb->insert(
$table_name,
array(
'con_name' => $your_name,
'con_main' => $your_mail,
'contant' => $your_content,
'con_status' => 'unview',
'con_rep_status' => 'notReplied',
'con_date' => time()
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)
);
}
?>
javascript code for implementing ajax
var cf_saveContact = document.getElementById("cf_saveContact");
cf_saveContact.addEventListener('click', function() {
var conName = document.getElementById("conName").value;
var conMail = document.getElementById("conMail").value;
var conContant = document.getElementById("conContant").value;
if(conName == "" || conMail == "" || conContant == ""){
document.querySelector(".con_error_msg").innerHTML = "<p style='color:red'>all fields are required</p>";
}else{
var action = "jsforcon-insert";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",jsforwp_globals.ajax_url+"?action="+action+"&_ajax_nonce="+jsforcon_globals.nonce+"&name="+conName+"&mail="+conMail+"&content="+conContant,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
conName = document.getElementById("conName").value = "";
conMail = document.getElementById("conMail").value = "";
conContant = document.getElementById("conContant").value = "";
document.querySelector(".con_error_msg").innerHTML = "<p style='color:green'>Successfully Sent</p>";
} } }
});
I use the ajax code outside wordpress work but in wordpress not works.
I just want to insert data using ajax in wordpress table. If you have any other method than suggest.
You added the wrong handler name to wp_enqueue_script for submit-form.js.
add_action('wp_enqueue_scripts', 'setting_up_scripts_contact_form_wp');
function setting_up_scripts_contact_form_wp() {
wp_register_style( 'contact-custom-style',plugins_url('public/css/style.css', __FILE__) );
wp_enqueue_style( 'contact-custom-style');
wp_enqueue_script( 'jsforcon-frontend-js', plugins_url('includes/submit-form.js', __FILE__),array(),false,true );
// wp_enqueue_script( 'wpforajax_con_test', plugins_url('public/js/test.js', __FILE__) );
// wp_register_script('wpforajax_con_test', plugin_dir_url(__FILE__) . 'test.js', true);
wp_localize_script(
'jsforcon-frontend-js',
'jsforcon_globals',
[
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'jsforcon_insert_nonce' )
]
);
}
And change jsforwp_globals.ajax_url to jsforcon_globals.ajax_url
var cf_saveContact = document.getElementById("cf_saveContact");
cf_saveContact.addEventListener('click', function() {
var conName = document.getElementById("conName").value;
var conMail = document.getElementById("conMail").value;
var conContant = document.getElementById("conContant").value;
if(conName == "" || conMail == "" || conContant == ""){
document.querySelector(".con_error_msg").innerHTML = "<p style='color:red'>all fields are required</p>";
}else{
var action = "jsforcon-insert";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",jsforcon_globals.ajax_url+"?action="+action+"&_ajax_nonce="+jsforcon_globals.nonce+"&name="+conName+"&mail="+conMail+"&content="+conContant,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
conName = document.getElementById("conName").value = "";
conMail = document.getElementById("conMail").value = "";
conContant = document.getElementById("conContant").value = "";
document.querySelector(".con_error_msg").innerHTML = "<p style='color:green'>Successfully Sent</p>";
}
}
}
});
You say you're doing this in an AJAX call? Are you writing out the response from the AJAX call to be sure that you're not getting errors? Always check the XMLHttpRequest's status and response for errors before proceeding.
I try to login the user in wordpress, but it works only for users registered in UI, not for the ones added by program.
The Login is done as a response to Ajax login request:
//wp_clear_auth_cookie();
$usr = wp_set_current_user ( $user->ID, $user->user_login);
wp_set_auth_cookie ( $user->ID );
There is log output for each step, and for any type of user. It is successfully registered in database, loaded from database, and even login is ok. And even a session is created for both kind of users. It can be seen in the database. But after all login flow, when page is redirected or refreshed, only the UI registered users enters the site. The programmatic ones are just not loaded after all successful steps: silently not working, no errors messages, no warnings, no failures. Looks like it needs some additional steps to enable or to activate. All kind of users are shown in dashboard in UI.
I suspect the programmatically added user is not complete or is not activated. This is how the user is registered as response to Ajax registration request:
function register_user($username, $usertype, $externalid)
{
$user_email = 'theuseremail#mail.com';
$result = wp_insert_user(array('user_login' => $username,
'nice_name' => $username,
'user_email' => $user_email,
'user_pass' => '***********' ));
$fb_user_id = $result;
add_user_meta( $fb_user_id, 'specific_attribute', $specific_id, true );
$user = get_user_by('id', $fb_user_id);
return $user;
}
The same code is used for both kind of users, the ones registered by UI and the ones registered programatically. There is how the user is loaded from Database as response to Ajax login request:
function load_user($usertype, $specific_id)
{
$user = get_users(array(
'meta_key' => 'specific_attribute',
'meta_value' => $specific_id
));
return $user [0];
}
The login uses a metadata field specific_attribute in both cases. For users registered by UI this attribute is added manually in the database, because there is no such UI field. For the other ones it is added automatically in the function register_user. The same thing happens when I try to login any user by using standard login/password form.
Workflow update:
1. PHP:
$user = load_user(request['usertype'], request['specific_id'])
if not load then register_user(request['username'], request['usertype'], request['specific_id'])
//wp_clear_auth_cookie();
$usr = wp_set_current_user ( $user->ID, $user->user_login);
wp_set_auth_cookie ( $user->ID );
do_action( 'wp_login', $user->user_login );
return $user; //<-- this is returned to javascript Ajax request
}
Javascript:
function onClick()
{
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
window.location = redirectaddress; //redirect
//or window.location=window.location;//just refresh
}
}
xhttp.open("POST", "/wp-json/register_or_login", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(JSON.stringify(request));
}
In this snippet of code:
$user = load_user(request['usertype'], request['specific_id'])
if not load then register_user(request['username'], request['usertype'], request['specific_id'])
//wp_clear_auth_cookie();
$usr = wp_set_current_user ( $user->ID, $user->user_login);
wp_set_auth_cookie ( $user->ID );
do_action( 'wp_login', $user->user_login );
return $user; //<-- this is returned to javascript Ajax request
}
On the fourth line the $user won't be set to anything if it was just created.
Also on that same line you spelled $user as $usr
I've actually done this exact same thing before. Below is the relevant part of the code that I used when I was doing this.
$user_id = lookup_user_id();
// Create the user in the WordPress DB if it does not exist
if ($user_id === false){
$username = $_POST['username'];
$email = $_POST['email'];
// We're never going to know the password stored in the WordPress DB, but that is alright
// because we will only authenticate this user against our SSO server and not the WordPress DB
$password = wp_generate_password(33, true, true);
$user_id = wp_insert_user( array('user_login'=>$username, 'user_pass'=>$password, 'user_email'=>$email, 'display_name'=>$_POST['username']) );
}
// Login the user
wp_set_auth_cookie($user_id, false);
if (isset($_POST['redirect'])){
header('Location: '.$_POST['redirect']);
}
Here I have written script to login and register in WordPress programmatically
Have created an ajax request for login
add_action( 'wp_ajax_gs_user_login_action', 'gspre_user_login');
add_action( 'wp_ajax_nopriv_gs_user_login_action', 'gspre_user_login');
function gspre_user_login(){
$creds = array();
$username = $creds['user_login'] = $_POST['user_login'];
$creds['user_password'] = $_POST['user_pass'];
$userbyname = get_user_by( 'login', $username );
if ($userbyname) {
$user = $userbyname;
}
$userbyemail = get_user_by('email', $username);
if ($userbyemail) {
$user = $userbyemail;
}
if ($user) {
$user_roles = implode(', ', $user->roles);
$user = wp_signon( $creds, true );
if ( is_wp_error($user) ){
$myArr = array(
'response' => 'Invalide username and password',
'redirect_url' => '',
'message' => $user->get_error_message()
);
}else{
wp_set_current_user( $user->ID );
wp_set_auth_cookie( $user->ID );
if ($user_roles == "administrator") {
$redirect_url = home_url('wp-admin/');
}else{
$redirect_url = home_url();
}
$myArr = array(
'response' => 'Login successfully',
'redirect_url' => $redirect_url,
'message' => 'Login successfully'
);
}
}else{
$myArr = array(
'response' => 'Invalide username and password',
'redirect_url' => '',
'message' => $user->get_error_message()
);
}
$myJSON = json_encode($myArr);
echo $myJSON;
die();
}
Have created an ajax request for registration
add_action( 'wp_ajax_gs_user_reg_action', 'gspre_user_reg');
add_action( 'wp_ajax_nopriv_gs_user_reg_action', 'gspre_user_reg');
function gspre_user_reg(){
//Create user
//start: Fill you details here
$user_login = $_POST['user_login'];
$user_email = $_POST['email'];
$user_pass = $_POST['password'];
$display_name = $_POST['display_name'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$role = 'administrator';
//end: Fill you details here
$flag_1 = 0;
$flag_2 = 0;
$check_username_exists = username_exists( $user_login );
if ($check_username_exists) {
$flag_1 = 1;
}
$check_email_exists = email_exists($user_email);
if ($check_email_exists) {
$flag_2 = 1;
}
if ($flag_1 == 0 && $flag_2 == 0) {
$userdata = array(
'user_login' => $user_login,
'user_pass' => $user_pass,
'user_email' => $user_email,
'display_name'=> $display_name,
'first_name' => $first_name,
'last_name' => $last_name
);
$user_id = wp_insert_user($userdata);
wp_update_user( array ('ID' => $user_id, 'role' => $role) );
if(is_wp_error($user_id)){
//echo $user->get_error_message();
$myArr = array(
'response' => 'register xyz',
'message' => $user->get_error_message()
);
}else{
//echo "User created successfully";
$myArr = array(
'response' => 'register xyz',
'message' => 'User created successfully'
);
}
}else{
//echo "User already exist";
$myArr = array(
'response' => 'register xyz',
'message' => 'User already exist'
);
}
$myJSON = json_encode($myArr);
echo $myJSON;
die();
}
Also, Have created a shortcode for login form
Shortcode:: [gsuserlogin]
add_shortcode('gsuserlogin', 'gsuserlogin_shortcode_function');
function gsuserlogin_shortcode_function(){
if (is_user_logged_in()) {
return 'You have Logged in';
}
?>
<form name="loginform" id="loginform" action="" method="post">
<div class="msg_ajax"></div>
<div>
<label for="gs_user_login"><?php echo _e('Username or Email', 'gs-users'); ?></label>
<input type="text" name="gs_user_login" id="gs_user_login" class="input" value="" size="20">
</div>
<div>
<label for="gs_user_pass"><?php echo _e('Password', 'gs-users'); ?></label>
<input type="password" name="gs_user_pass" id="gs_user_pass" class="input" value="" size="20">
</div>
<div>
<label><input name="gs_user_rememberme" type="checkbox" id="gs_user_rememberme" value="true"> <?php echo _e('Remember Me', 'gs-users'); ?></label>
</div>
<input type="hidden" name="action" value="gs_user_login_action">
<input type="button" id="login_btn" value="Login">
</form>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(document).on('click', '#login_btn', function(){
var target = jQuery(this);
var user_login = jQuery('#gs_user_login').val();
var user_pass = jQuery('#gs_user_pass').val();
//Ajax
jQuery.ajax({
url: '<?php echo admin_url( 'admin-ajax.php');?>',
type: "POST",
data: {'action': 'gs_user_login_action', user_login: user_login, user_pass: user_pass},
cache: false,
dataType: 'json',
beforeSend: function(){
},
complete: function(){
},
success: function (response) { console.log(response);
jQuery('.msg_ajax').text(response['message']);
console.log(response['redirect_url']);
console.log(response['message']);
if (response['redirect_url']!="") {
window.location.href = response['redirect_url'];
}
}
});
//Ajax
});
});
</script>
<?php
}
Created a shortcode for registration form
Shortcode:: [gsuserreg]
add_shortcode('gsuserreg', 'gsuserreg_shortcode_function');
function gsuserreg_shortcode_function(){
if (is_user_logged_in()) {
return 'You have Logged in';
}
?>
<form name="regform" id="regform" action="" method="post">
<div class="msg_ajax"></div>
<div>
<label for="first_name"><?php echo _e('first_name', 'gs-users'); ?></label>
<input type="text" name="first_name" id="first_name">
</div>
<div>
<label for="last_name"><?php echo _e('last_name', 'gs-users'); ?></label>
<input type="text" name="last_name" id="last_name">
</div>
<div>
<label for="user_login"><?php echo _e('user_login', 'gs-users'); ?></label>
<input type="text" name="user_login" id="user_login">
</div>
<div>
<label for="email"><?php echo _e('email', 'gs-users'); ?></label>
<input type="text" name="email" id="email">
</div>
<div>
<label for="password"><?php echo _e('password', 'gs-users'); ?></label>
<input type="password" name="password" id="password">
</div>
<input type="hidden" name="action" value="gs_user_reg_action">
<input type="button" id="btn_reg" value="Send My Message">
</form>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(document).on('click', '#btn_reg', function(){
var target = jQuery(this);
var first_name = jQuery('#first_name').val();
var last_name = jQuery('#last_name').val();
var user_login = jQuery('#user_login').val();
var email = jQuery('#email').val();
var password = jQuery('#password').val();
//Ajax
jQuery.ajax({
url: '<?php echo admin_url( 'admin-ajax.php');?>',
type: "POST",
data: {'action': 'gs_user_reg_action', first_name: first_name, last_name: last_name, user_login: user_login, email: email, password: password},
cache: false,
dataType: 'json',
beforeSend: function(){
},
complete: function(){
},
success: function (response) { console.log(response);
jQuery('.msg_ajax').text(response['message']);
console.log(response['response']);
console.log(response['message']);
}
});
//Ajax
});
});
</script>
<?php
}
Paste above code to the theme functions.php
I hope it will work you thank you :)
i am building a wordpress theme and in that i have a custom contact form which stores data in a custom post type Messages when a user fills that form and submit it.
here is the code below
Contact-form.php
<form id="salmanlateefContactForm" class="salmanlateef-contact-form" action="#" method="post" data-url="<?php echo admin_url('admin-ajax.php'); ?>">
<div class="form-group">
<input type="text" class="form-control salmanlateef-form-control" placeholder="Your Name" id="name" name="name" required="required">
<small class="text-danger form-control-msg">Your Name Is Required</small>
</div>
<div class="form-group">
<input type="email" class="form-control salmanlateef-form-control" placeholder="Your Email" id="email" name="email" required="required">
<small class="text-danger form-control-msg">Your Email Is Required</small>
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control salmanlateef-form-control" required="required" placeholder="Your Message"></textarea>
<small class="text-danger form-control-msg">A Message Is Required</small>
</div>
<div class="text-center">
<button type="submit" class="btn btn-default btn-lg btn-salmanlateef-form">Submit</button>
<small class="text-info form-control-msg js-form-submission">Submission in process, please wait...</small>
<small class="text-success form-control-msg js-form-success">Message successfully submitted, thank you!</small>
<small class="text-danger form-control-msg js-form-error">There was an error while submitting the message, please try again</small>
</div>
JQuery
/* contact form submission */
$('#salmanlateefContactForm').on('submit', function(e){
e.preventDefault();
$('.has-error').removeClass('has-error');
$('.js-show-feedback').removeClass('js-show-feedback');
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
message = form.find('#message').val(),
ajaxurl = form.data('url');
if( name === '' ){
$('#name').parent('.form-group').addClass('has-error');
return;
}
if( email === '' ){
$('#email').parent('.form-group').addClass('has-error');
return;
}
if( message === '' ){
$('#message').parent('.form-group').addClass('has-error');
return;
}
form.find('input, button, textarea').attr('disabled', 'disabled');
$('.js-form-submission').addClass('js-show-feedback');
$.ajax({
url : ajaxurl,
type : 'post',
data : {
name : name,
email : email,
message : message,
action: 'salmanlateef_save_user_contact_form'
},
error : function( response ){
$('.js-form-submission').removeClass('js-show-feedback');
$('.js-form-error').addClass('js-show-feedback');
form.find('input, button, textarea').removeAttr('disabled');
},
success : function( response ){
if( response == 0 ){
setTimeout(function() {
$('.js-form-submission').removeClass('js-show-feedback');
$('.js-form-error').addClass('js-show-feedback');
form.find('input, button, textarea').removeAttr('disabled');
},1500);
} else {
setTimeout(function() {
$('.js-form-submission').removeClass('js-show-feedback');
$('.js-form-success').addClass('js-show-feedback');
form.find('input, button, textarea').removeAttr('disabled').val('');
},1500);
}
}
});
});
Ajax.php
add_action( 'wp_ajax_nopriv_salmanlateef_save_user_contact_form', 'salmanlateef_save_contact' );
add_action( 'wp_ajax_salmanlateef_save_user_contact_form', 'salmanlateef_save_contact' );
function salmanlateef_save_contact(){
$title = wp_strip_all_tags($_POST["name"]);
$email = wp_strip_all_tags($_POST["email"]);
$message = wp_strip_all_tags($_POST["message"]);
$args = array(
'post_title' => $title,
'post_content' => $message,
'post_author' => 1,
'post_status' => 'publish',
'post_type' => 'salmanlateef_contact',
'meta_input' => array(
'_contact_email_value_key' => $email
)
);
$postID = wp_insert_post( $args );
if ($postID !== 0) {
$to = get_bloginfo( 'admin_email' );
$subject = 'Salman Lateef Contact Form - '.$title;
$header[] = 'From: '.get_bloginfo( 'name' ).' <'.$to.'>';
$header[] = 'Reply-To: '.$title.' <'.$email.'>';
$header[] = 'Content-Type: text/html: charset=UTF-8';
wp_mail( $to, $subject, $message, $headers );
echo $postID;
} else {
echo 0;
}
die();
}
What i want is use the same logic to post comments to a post using comments form. Hope i am clear on the question. Looking forward for a reply. Thanks in advance
Since Version 2.8, The JavaScript global variable ajaxurl can be used in case you want to separate your JavaScript code from php files into JavaScript only files. This is true on the administration side only. If you are using AJAX on the front-end, you need to make your JavaScript aware of the admin-ajax.php url.
So please use admin-ajax rather than the ajaxurl in your theme.
$args = array(
'comment_author' => $author,
'comment_author_email' => $email,
'comment_content' => $comment,
'comment_parent' => $commentParent,
'comment_post_ID' => $postID,
'user_id' => $userID,
);
$commentID = wp_new_comment( $args );
if ($commentID !== 0) {
echo $commentID;
} else {
echo 0;
}
i used the wp_new_comment() function and it served my purpose. however i am still trying to figure out a way to append the newly generated comment into the comments list in the single.php
this is my view i am submitted form using jquery,then I want to check which button is clicked either 'ADD PRODUCT' or SUBMIT button in controller
<?php echo form_open_multipart('itemcontroller/submit'); ?>
<div class="col-md-6">
<div class="add-name">
<label>Product Name</label>
<input type="text" id="product_name" name="product_name" placeholder="Product name">
<span id="pnerror" style="display: none;">Please enter Product Name</span>
</div>
<div class="add-name">
<label>Product Image</label>
<input type="file" id="user_file" name="user_file">
<span id="imgerror" style="display: none;">Please select an Image</span>
</div>
<div class="add-name">
<label>Product Category</label>
<?php $attributes = 'id="cat"';
echo form_dropdown('cat', $cat, set_value('cat'), $attributes); ?>
<span id="caterror" style="display: none;">Please select Category</span>
</div>
</div>
<div class="col-md-6">
<div class="add-name">
</div>
<div class="add-name">
<label>Product Description</label>
<textarea class="form-control" rows="8" id="product_description" name="product_description" placeholder="Product Description"></textarea>
<span id="pderror" style="display: none;">Please enter Product Description</span>
</div>
</div>
<div class="sub-add">
<button type="submit" form="form1" id="fill" name="fill" value="add">ADD PRODUCT</button>
</div>
<div class="sub-add">
<button type="submit" id="go" name="go" form="form1" value="go">SUBMIT</button>
</div>
<?php echo form_close(); ?>
this is my jquery code for ADD PRODUCT button.
<script type="text/javascript">
$('#fill').click(function(event){
var product_name = $('#product_name').val();
var image = $('#user_file').val();
var cat = $('#cat').val();
var product_description = $('#product_description').val();
if(product_name.length == 0)
{
$('#pnerror').show();
}
if(image.length == 0)
{
$('#imgerror').show();
}
if(cat == 0)
{
$('#caterror').show();
}
if(product_description.length == 0)
{
$('#pderror').show();
}
else if(product_name.length != 0 && image.length != 0 && cat != 0 && product_description.length != 0)
{
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
this is my SUBMIT button
<script type="text/javascript">
$('#go').click(function(event){
var product_name = $('#product_name').val();
var user_file = $('#user_file').val();
var cat = $('#cat').val();
var product_description = $('#product_description').val();
if(product_name.length == 0)
{
$('#pnerror').show();
}
if(user_file.length == 0)
{
$('#imgerror').show();
}
if(cat == 0)
{
$('#caterror').show();
}
if(product_description.length == 0)
{
$('#pderror').show();
}
else if(product_name.length != 0 && user_file.length != 0 && cat != 0 && product_description.length != 0)
{
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
This is my controller code:
public function submit()
{
print_r($_POST);
if($this->input->post('go'))
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 2048;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('user_file'))
{
$data = array('prod_data' => $this->upload->data());
$user_file = $data['prod_data']['raw_name']."".$data['prod_data']['file_ext'];
$id = $this->session->userdata['record']['id'];
$com_id = $this->session->userdata['record']['com_id'];
$sam = array(
'title' => $this->input->post('product_name'),
'type' => 'product'
);
$this->load->model('registermodel');
$chk = $this->registermodel->insertsam($sam);
if ($chk == TRUE)
{
$id = $this->registermodel->getsampleid();
$data = array(
'product_name' => $this->input->post('product_name'),
'image' => 'images/'.$user_file,
'product_description' => $this->input->post('product_description'),
'cat_id' => $this->input->post('cat'),
'com_id' => $com_id,
'id' => $id
);
$check = $this->registermodel->insertproduct($data);
if($check == TRUE)
{
echo "<script>
alert('Data Submitted Succesfully');
</script>";
redirect('/homecontroller');
}
else
{
echo "Value insertion Failed";
}
}
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
else if($this->input->post('fill'))
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 2048;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('user_file'))
{
$data = array('prod_data' => $this->upload->data());
$user_file = $data['prod_data']['raw_name']."".$data['prod_data']['file_ext'];
$id = $this->session->userdata['record']['id'];
$com_id = $this->session->userdata['record']['com_id'];
$sam = array(
'title' => $this->input->post('product_name'),
'type' => 'product'
);
$this->load->model('registermodel');
$chk = $this->registermodel->insertsam($sam);
if ($chk == TRUE)
{
$id = $this->registermodel->getsampleid();
$data = array(
'product_name' => $this->input->post('product_name'),
'image' => 'images/'.$user_file,
'product_description' => $this->input->post('product_description'),
'cat_id' => $this->input->post('cat'),
'com_id' => $com_id,
'id' => $id
);
$check = $this->registermodel->insertproduct($data);
if($check == TRUE)
{
echo "<script>
alert('Product added Succesfully');
</script>";
$data['category'] = $this->linkmodel->get_category();
$data['cat'] = $this->registermodel->get_category();
$this->load->view('itemview',$data);
}
else
{
echo "Value insertion Failed";
}
}
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
}
print_r($_POST);
this returns only this :
Array ( [product_name] => Multifunction Printer Machine [cat] => 82 [product_description] => Approx Price: Rs 80,000 / Piece)
not return ADD PRODUCT OR SUBMIT button name, please anyone tell me what i am doing wrong ?
You may have to use <input type="submit" ...> instead of <button ...>. It should append buttons' name and value to $_POST.
Add input hidden field in your form and set different value in each JavaScript code.
<?php echo form_open_multipart('itemcontroller/submit'); ?>
<!-- your existing code --->
<input type="hidden" name="submit_type" id="submit_type" value="" />
<?php echo form_close(); ?>
JavaScript code Modification
<script type="text/javascript">
$('#go').click(function(event){
<!-- your existing code --->
$('#submit_type').val('SUBMIT');
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
<script type="text/javascript">
$('#fill').click(function(event){
<!-- your existing code --->
$('#submit_type').val('ADD PRODUCT');
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
how to Getting error when submitting a form by ajax to page msg.php
file 1 = msg.php
<?php
$id = $_SESSION['id'];
$touser = htmlspecialchars($_GET['iduser']);
$postid = htmlspecialchars($_GET['post']);
?>
<div id="send">
<div id="title">صندوق المحادثة</div>
<form id="my-form" method="post" enctype="multipart/form-data">
<textarea id="_text" name="text" required=""></textarea>
<input id="_from" name="from" type="hidden" value="<?php echo $id; ?>"/>
<input name="to" type="hidden" value="<?php echo $touser; ?>"/>
<input name="post" type="hidden" value="<?php echo $postid ?>" />
<div class="file">
<li>ملفات .zip فقط</li>
<input class="up" type="file" name="up" />
</div>
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token_madmoun']; ?>" />
<button class="submit">ارسال الان</button>
</form>
<script>
$( '#my-form' )
.submit( function( e ) {
$.ajax({
url: 'chat_a.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
document.getElementById("my-form").reset();
});
</script>
</div>
chat_a.php
<?php
include "config.php";
if(!$user->is_logged_in()){
header('Location: unregistered.php');
exit();
}
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token_madmoun']) {
$id = $_SESSION['id'];
$data = date('Y-m-d');
$time = time();
$post = htmlspecialchars($_POST['post']);
$to = htmlspecialchars($_POST['to']);
$file_name = $_FILES['up']['name'];
$file_size = $_FILES['up']['size'];
$FileType = pathinfo($file_name,PATHINFO_EXTENSION);
if(!empty($_POST['text'])){
if(empty($FileType)) {
$sqladdcontent = $db->prepare("INSERT INTO chat_a SET _from = :_from, _to = :_to, _post = :_post, _data = :_data, _time = :_time, _text = :_text");
$sqladdcontent->bindParam(':_from', $id);
$sqladdcontent->bindParam(':_to', $to);
$sqladdcontent->bindParam(':_post', $post);
$sqladdcontent->bindParam(':_data', $data);
$sqladdcontent->bindParam(':_time', $time);
$sqladdcontent->bindParam(':_text', htmlspecialchars($_POST['text']));
$sqladdcontent->execute();
}else {
if($FileType != "zip" && $FileType != "ZIP") {
$error = "<center><div id='no-ok'>قم برفع ملفات بصيغة .zip فقط</div></center>";
}else {
if ($file_size > 104857600) {
$error = "<div id='no'>ممنوع حجم الملف اكبر من 100 ميجا</div>";
}else {
$time_digit = time() . '_';
$new_file_name = $time_digit.'.zip';
move_uploaded_file($_FILES['up']['tmp_name'], "upload-msg/".$new_file_name);
$sqladdcontent = $db->prepare("INSERT INTO chat_a SET _from = :_from, _to = :_to, _post = :_post, _data = :_data, _time = :_time, _text = :_text, _file = :_file");
$sqladdcontent->bindParam(':_from', $id);
$sqladdcontent->bindParam(':_to', $to);
$sqladdcontent->bindParam(':_post', $post);
$sqladdcontent->bindParam(':_data', $data);
$sqladdcontent->bindParam(':_time', $time);
$sqladdcontent->bindParam(':_text', htmlspecialchars($_POST['text']));
$sqladdcontent->bindParam(':_file', $new_file_name);
$sqladdcontent->execute();
}
}
}
}
}
?>
how to Getting error when submitting a form by ajax to page msg.php
The name of the variable is the error = $error
collect errors in php script as $errors array, then finaly ouput it as JSON:
print json_encode($errors);
and process it in success event handler
<script>
$( '#my-form' )
.submit( function( e ) {
$.ajax({
url: 'chat_a.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(msg)
{
json = $.parseJSON(msg);
if (json.error[1] != "") //
$("#div-error-1").html(json.error[1]);
if (json.error[2] != "") //
$("#div-error-2").html(json.error[2]);
// and so on. Or you can use foreach construction. it will make code more universal
}
} );
e.preventDefault();
document.getElementById("my-form").reset();
});
</script>