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.
Related
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
});
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.
I created multiple file uploader dynamically using javascript within the div FileUploadContainer.while i put btnSubmit outside the form tag i get Request.Files.Count as zero.I need to call the PopUp() through Json .If i put btnSubmit inside the form tag
it does not call the Save() on javascript and will call PopUp() method on form submit.
I need to call the PopUp() through Json and need to get the Request.Files.Count .Pls help.
#using (Html.BeginForm("PopUp", "EnergyCatagory", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="FixedHeightContainer">
<div id="FileUploadContainer">
</div>
<input type="button" id="btnAddAttachment" name="btnAddAttachment" class="ZWidgetTitle"
value="Add More Attachments" onclick="AddFileUpload()" />
</div>
<div id="NewAttachment">
<div style="background-color: #DADADA;">
<center>
<label style="font-family: Verdana; font-size: 13px; font-weight: bold; color: black;
height: 30px; width: 100%; padding-top: 20px;" id="lblMessage">
</label>
</center>
</div>
</div>
<div class="horizSep">
</div>
<div id="buttons">
</div>
} <button id="btnSubmit" class="buttons" onclick="Save()">
Attach</button>
function Save()
{$.ajax({
url: '/EnergyCatagory/PopUp',
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("success");
}
});
}controller-----
public ActionResult PopUp()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase PostedFile = Request.Files[i];
if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
var path1 = Path.Combine(Server.MapPath("~/Files/"), FileName);
//PostedFile.SaveAs(Server.MapPath("Files\\") + FileName);
PostedFile.SaveAs(path1);
return Json(
new
{
CustomMessage = "My message",
});
}
}
If the form is getting submitted and don't calling the function onclick is because the input type is a button, you can change it to html a link tag.
also calling a inline javascript (onclick) is not good practice, i notice you use jquery so why don't do it with jquery?
function Save(){
$.ajax({
url: '/EnergyCatagory/PopUp',
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("success");
}
});
$("#btnSubmit").click(function(){
Save();
});
#using (Html.BeginForm("PopUp", "EnergyCatagory", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="FixedHeightContainer">
<div id="FileUploadContainer">
</div>
<input type="button" id="btnAddAttachment" name="btnAddAttachment" class="ZWidgetTitle"
value="Add More Attachments" onclick="AddFileUpload()" />
</div>
<div id="NewAttachment">
<div style="background-color: #DADADA;">
<center>
<label style="font-family: Verdana; font-size: 13px; font-weight: bold; color: black;
height: 30px; width: 100%; padding-top: 20px;" id="lblMessage">
</label>
</center>
</div>
</div>
<div class="horizSep">
</div>
<div id="buttons">
</div>
<a id="btnSubmit" class="buttons">Attach</a>
}
i think you are getting Request.Files.Count equals zero is because you don't have any input type file? do you?
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.");
}
});
I have a form and I'm trying to perform Ajax posts.
With the default submit button the dialog window closes, with the jQuery button, nothing happens.
I want the dialog window to stay open so I can keep doing Ajax requests uninterrupted and only close when I press Esc or click the big "X".
Thanks
<div id="formBox" style="display: hidden;">
<form>
<fieldset>
<legend>File System Space Calculator</legend>
<p>
<label for="curr_alloc">Current Space Allocation:</label>
<br />
<input type="text" size="5" name="curr_alloc" id="curr_alloc" />
KB <input type="radio" name="curr_unit" value="KB" />
MB <input type="radio" name="curr_unit" value="MB" />
GB <input type="radio" name="curr_unit" value="GB" checked/>
TB <input type="radio" name="curr_unit" value="TB" />
</p>
<p>
<label for="curr_percent">Current Usage Percentage:</label>
<br />
<input type="text" size="5" name="curr_percent" id="curr_percent" />
</p>
<p>
<label for="desired_percent">Desired Usage Percentage:</label>
<br />
<input type="text" size="5" name="desired_percent" id="desired_percent" />
</p>
<br />
<p>
<input type="submit" value="calculate"/></p>
</fieldset>
</form>
</div>
<div id="calcBox" style="display: none;"> </div>
<script>
$(document).ready(function() {
$("#formBox").dialog({
bgiframe: true,
autoOpen: false,
height: 500,
width: 500,
modal: false,
closeOnEscape: true,
title: "Calculator",
closeText: 'Close',
buttons:
{
"Calculate": function()
/* form post */
$("#calcQuery").submit(function(){
$.post("calc.php", $("#calcQuery").serialize(),
function(data){
if (data.length > 0)
{
$("#calcBox").html(data);
$("#calcBox").show();
}
else
{
$("#calcBox").html("<h1>nuttin' here yet</h1>");
}
}, "html");
return false;
});
/* form post */
}
}
});
$('#calcButton').click(function(){
$('#formBox').dialog('open');
return false;
});
});
</script>
In your button method, just make the post. You shouldn't have to do anything else.
buttons:{
"Calculate":function(){
$.post("calc.php", $("#calcQuery").serialize(), function(data){ if (data.length > 0) {
$("#calcBox").html(data);
$("#calcBox").show();
}
else
{
$("#calcBox").html("<h1>nuttin' here yet</h1>");
}
}, "html");
});
}
I apologize for the formatting. I worked with what you gave me without opening an editor. You shouldn't need to return false in a jQuery-UI button.
This works (except for form reset which is addressed in another post)
// form popup
$(document).ready(function()
{
$("#formBox").dialog({
bgiframe: true,
autoOpen: false,
height: 600,
width: 400,
modal: false,
closeOnEscape: true,
title: "Calculator",
buttons: {
"Calculate": function() {
// form post
$.ajax({
type: "POST",
url: "calc.php",
data: $("#calcQuery").serialize(),
dataType: "html",
success: function(response)
{
$("#calcBox").html(response);
$("#calcBox").show();
},
error: function
(xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
}).responseText;
// form post
}
}
});
$('#calcButton').click(function(){
$('#formBox').dialog('open');
});
});