ajax json form submit - ajax

I have this code for form submit:
index.php
<html>
<head>
<title>My Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myForm").submit(function(){
var tvyalner = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "postForm.ajax.php",
data: tvyalner,
dataType: "json",
success: function(data){
$("#formResponse").removeClass('error');
$("#formResponse").addClass(data.status);
$("#formResponse").html(data.message);
if(data.status === 'success'){$("#myForm table").hide();}
},
error: function(){
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
//make sure the form doens't post
return false;
});
});
</script>
<style type="text/css">
.success{
border: 2px solid #009400;
background: #B3FFB3;
color: #555;
font-weight: bold;
}
.error{
border: 2px solid #DE001A;
background: #FFA8B3;
color: #000;
font-weight: bold;
}
</style>
</head>
<body>
<div class="mfm">
<form id="myForm" name="myForm" method="post" action="" style="margin: 0 auto; width: 300px;">
<div id="formResponse"></div>
<table>
<tr><td>Name:</td><td><input name="name" type="text" value=""></td></tr>
<tr><td>Email:</td><td><input name="email" type="text" value=""></td></tr>
<tr><td>Message:</td><td><textarea name="message" rows="5" cols="20"></textarea></td></tr>
<tr><td> </td><td><input type="submit" name="submitForm" value="Submit Form"></td></tr>
</table>
</form>
</div>
</body>
</html>
postForm.ajax.php
<?php
//function to validate the email address
//returns false if email is invalid
function checkEmail($email){
if(eregi("^[a-zA-Z0-9_]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
return FALSE;
}
list($Username, $Domain) = split("#",$email);
if(#getmxrr($Domain, $MXHost)){
return TRUE;
} else {
if(#fsockopen($Domain, 25, $errno, $errstr, 30)){
return TRUE;
} else {
return FALSE;
}
}
}
//response array with status code and message
$response_array = array();
//validate the post form
//check the name field
if(empty($_POST['name'])){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
//check the email field
} elseif(!checkEmail($_POST['email'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';
//check the message field
} elseif(empty($_POST['message'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
//form validated. send email
} else {
//send the email
$body = $_POST['name'] . " sent you a message\n";
$body .= "Details:\n\n" . $_POST['message'];
mail($_POST['email'], "SUBJECT LINE", $body);
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';
}
echo json_encode($response_array);
?>
After first submit displaying:
Name is blank.
Filling field and submitting again. displaying
There was an error submitting the form. Please try again.
and that's all.
Code not working in localhost.
What is the problem?

I suggest using this error-function to see what the error is:
$.ajax({
/* ... */
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown); // Or use alert()
console.log(textStatus);
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});

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
});

Uncaught ReferenceError: year is not defined in google chart using ajax/codeigniter

Good day. I want to make my column char working with database but I got this error says "Uncaught ReferenceError: year is not defined". here is my code.
JAVASCRIPT
function year()
{
var e = document.getElementById("selectyear");
var year = e.options[e.selectedIndex].text;
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('chartcontroller/chart/')?>/" + year,
type: "GET",
dataType: "JSON",
success: function(data)
{
drawChart1(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart1);
function drawChart1(data) {
var data = google.visualization.arrayToDataTable([
['Courses', 'S.Y. 2011-2012', 'S.Y. 2012-2013','S.Y. 2013-2014'],
for(var i = 1; i < data.length; i++) {
comment = data[i];
[comment.Course, comment.year_a, comment.year_b, comment.year_c],
}
]);
var options = {
title: 'ColumnChart',
hAxis: {title: 'Courses', titleTextStyle: {color: 'blue'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
//ajax end
and my view html
<div class="grid text-center" style="display: block;">
<h1 style=" color: black; font-size: 18px;">Summary of Daily Utilization of Library Holdings per Department</h1>
<div class="input-group">
<span class="input-group-addon">#</span>
<select id="selectyear" class="form-control selectyear" data-mobile="true" name="year" onchange="year();">
<?php
for ($i=$min_year; $i <= $max_year; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
</div>
<h1 style=" color: gray; font-size: 14px;">S. Y. 2011-2012, 2012-2013 & 2013-2014</h1>
<div id="chart_div1" class="chart" style="height: 400px; width: 100%;"></div>
<div id="chart_div2" class="chart" style="height: 400px; width: 100%;"></div>
in my controller
public function chart($year)
{
$data = $this->views->chart($year);
//Either you can print value or you can send value to database
echo json_encode($data);
}
no problem with ajax because when I do a debugging ajax successfully retrieve the value from database, the problem is when I put that value to my column chart like what I did in my code I've got that error.. help me please. this is the last problem I have to my thesis project.. thanks. I want to change the column chart value if the drop down has change.

Onchange() for AJAX

I am trying to display the onchange value of a textbox using ajax. My code is as follows :
ajaxquery.php
<html>
<head>
<title>Changing textbox value based on dropdown list using Ajax and PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
//fuction to return the xml http object
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCurrencyCode(strURL)
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
document.getElementById('cur_code').value=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<body style="font: 12px Verdana, Arial, Helvetica, sans-serif;">
<form style="text-align:center" method="post" action="" name="form1">
<p>Country : <input type="text" name="country" onChange="getCurrencyCode('code.php?country='+this.value)">
</form>
</body>
</html>
code.php
<?php
$country=$_REQUEST['country'];
echo $country;
?>
The value is not displaying. Where am I going wrong?
P.s. I am completely new to ajax and have no knowledge about it. Appreciate any help :)
<p>Country : <input type="text" name="country" onblur="getCurrencyCode('code.php?country='+this.value)">
<p>Country Code : <input type="text" name="cur_code" id='cur_code' ">
Changed the onchange function to onblur and added another input type. It is working perfectly now!

Jquery ajax done and fail not fireing

I have the following ajax call:
$( document ).ready(function() {
$( "#fform" ).submit(function( event ) {
//alert( "Handler for .submit() called." );
event.preventDefault();
$.ajax({
type: "POST",
url: "apply.php",
data: "email="+$("#emaill").val()
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
}).fail(function() {
alert("Sorry. Server unavailable. ");
});
});
});
and in apply.php:
$con=mysqli_connect("some_server","some_usename","some_pass","some_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$r=mysqli_query($con,"INSERT INTO some_table (email, join_date) VALUES ('".$_POST['email']."', CURDATE() )");
if($r)
{
echo 'true';
}
else
{
echo 'false';
}
mysqli_close($con);
The wierd thing is that I get the email in the DB but I'm not getting any alert! please help!
UPDATE:
The form:
<form method="POST" id="fform" >
<fieldset class="clearfixx" style="width: 552px; height: 40px;">
<div class="lp-pom-form-field clearfixx" style="width: 552px; height: 42px; top: 0px;">
<input placeholder="Email Address" type="email" id="emaill" name="email" class="textt" style="top: 0px; left: 58px; width: 520px; font-size: 15px; height: 38px; padding-left: 11px; padding-right: 11px; lineheight: 15px;" required>
</div>
</fieldset>
<input type="submit" class="lp-element lp-pom-button" id="lp-pom-button-25" value="Submit dude"/>
</form>
I get the data on DB after clicking the submit button but I don't get any alerts. Thank you
UPDATE 2:
error: Uncaught TypeError: Object # has no method 'done'
SOLVED
I was using an old version of JQuery thank you all
well the ajax function will only work if the form #fform is submitted.
put a submit button in your form:
<input type="submit" value="submit" />
clicking on the submit button should trigger your function
http://jsfiddle.net/Ashkanvb/4HpG5/
You have a little mistake in your jQuery AJAX call, try this :
$.ajax({
type: "POST",
url: "apply.php",
data: "email="+$("#emaill").val()
}).done(function( msg ) {
alert( "Data Saved: " + msg );
}).fail(function() {
alert("Sorry. Server unavailable. ");
});
I suggest you to use a debug tool like firebug or the chrome developper tool, which permit to easily detect this kind of syntax errors.

submit form from <div> html value in codeigneter

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

Resources