I'm trying to make an ajax request with jquery/codeigniter. Well, there seems to be a problem. i do get it to work, but it seems like the POST is not sent, for some reason...
Javascript
$('#profileUpdateButton').click(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
From the codeigniter controller
if($this->input->is_ajax_request()) {
echo $this->input->post('profileUpdate');
}
If i replace the "echo $this->" etc.. with just echo "Hello" i do get an alertbox with "Hello", why don't i get the text from the box?
html
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
Change your html markup to this...
<div id="statusUpdate"> <!-- Use ID not NAME here |v| -->
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
you were setting the form's name and you were selecting $('#statusUpdateForm') which means the id of statusUpdateForm, not the name attribute...
Related
I'm editing woocommerce form-edit-account.php, in this template there is a form that allows users to change name, surname, address etc. I added ajax requests to save the data without reloading the page. The data is saved correctly, so the ajax request works fine. The only step I can't get to work properly are handling error messages.
The problem
when click on submit button and the data is saved successfully, two messages appear.
The first message is the original woocommerce message: "Account details changed successfully", and can be found at https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-form-handler.html#source-view.346. The second message is what I wrote in my functions.php with wc_add_notice.
Expectations
I should only get the message I added to functions.php with wc_add_notice, why am I getting the original message as well? What am I doing wrong ?
Hope someone can help me with this, I can't figure out where the mistake is. I appreciate any help and thank you for any replies.
Js which handles updating fields and error / success message
$(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error msg
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data) {
$('.newdiv').html(data);
}, 'json'
);
//Ajax Save settings
$.ajax({
type: "POST",
data: $(".mts-edit-account").serialize(),
beforeSend: function() {
$(".container_loader").show();
},
success: function(data) {
$(".container_loader").hide();
}
});
});
});
Handling error in functions.php
// Validate - my account
add_action( 'woocommerce_save_account_details_errors', array( &$user, 'save_account_details' ), 10, 1);
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
function save_account_details( &$user ) {
if (isset( $_POST['account_first_name'] ) == '') {
wc_add_notice("<b>Nome</b> è un campo obbligatorio", "error");
$response = wc_print_notices(true);
} else if (isset($_POST['account_first_name']) ) {
wc_add_notice("Modifiche salvate con successo", "success");
$response = wc_print_notices(true);
}
echo json_encode($response);
exit();
}
Example of my form html
<form name="Form" class="mts-edit-account" method="post" action="<?php echo admin_url('admin-ajax.php'); ?>" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> >
<?php do_action( 'woocommerce_edit_account_form_start' ); ?>
<!-- Fist & Last Name Field -->
<div class="row name_surname">
<div class="form-row">
<label class="t3" for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" class="field-settings" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div class="form-row">
<label class="t3" for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" class="field-settings" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />
</div>
</div>
<!-- Other fields -->
<!-- Save Info Settings -->
<div style="margin-bottom: 0px!important;">
<?php wp_nonce_field( 'save_account_details', 'save-account-details-nonce' ); ?>
<button type="submit" class="edit-account-button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>"><?php esc_html_e( 'Salva modifiche', 'woocommerce' ); ?></button>
<input type="hidden" name="action" value="save_account_details" />
</div>
</form>
I create a form with hidden input forms that submit the value to a PHP script and store each value in an array of sessions by reloading the page with AJAX. It returns an HTML success alert message to <p id ="msg"></p>. I need help on how to send $count to <p id="count"></p> and success alert message to <p id ="msg"></p> at the point of success: in AJAX. And also I will like the success alert to disappear after 3 seconds of the display. Below is my code:
my_add_cart.php
<?php
session_start();
$_SESSION['title'][]=$_POST['title'];
$_SESSION['price'][]=$_POST['price'];
$_SESSION['img_src'][]=$_POST['img_src'];
$count = count($_SESSION["title"]);
echo $count;
echo '<div class="alert">
<span class="closebtn" onclick="this.parentElement.style.display=\'none\';">×</span>
<center>Product added successfully to cart.</center>
</div>';
exit();
?>
Above is my_add_cart.php and below is my HTML and javascript:
<script type="text/javascript">
function clickButton(){
var title=document.getElementById('title').value;
var price=document.getElementById('price').value;
var img_src=document.getElementById('img_src').value;
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src
},
cache:false,
success: function (html)
{
$('#msg').html(html);
}
});
return false;
}
</script>
<html>
<p id="msg"></p>
<p id="count"></p>
<form onsubmit="clickButton()">
<input type="hidden" value="<? echo $title ?>" name = "title" id="title" >
<input type="hidden" value="<? echo number_format($price); ?>" name = "price" id="price" >
<input type="hidden" value="<? echo "https://mikeandcathy.com.ng/admin/UploadFolder/".$row_product_img[0]; ?>" name = "img_src" id="img_src">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton();">Add Cart</button>
</form>
</html>
I Suggest turning your server code into a json api
Solution
change my_add_cart.php to this
<?php
session_start();
$_SESSION['title'][]=$_POST['title'];
$_SESSION['price'][]=$_POST['price'];
$_SESSION['img_src'][]=$_POST['img_src'];
$count = count($_SESSION["title"]);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(
[
'count' => $count,
'message' => '<div class="alert"><span class="closebtn" onclick="this.parentElement.style.display=\'none\';">×</span> <center>Product added successfully to cart.</center></div>';
]
);
exit();
?>
change your frontend code to this
<script type="text/javascript">
function clickButton(){
var title=document.getElementById('title').value;
var price=document.getElementById('price').value;
var img_src=document.getElementById('img_src').value;
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src
},
cache:false,
success: function (data)
{
$('#msg').html(data['message']);
$('#count').html(data['count']);
}
});
return false;
}
</script>
<html>
<p id="msg"></p>
<p id="count"></p>
<form onsubmit="clickButton()">
<input type="hidden" value="<? echo $title ?>" name = "title" id="title" >
<input type="hidden" value="<? echo number_format($price); ?>" name = "price" id="price" >
<input type="hidden" value="<? echo "https://mikeandcathy.com.ng/admin/UploadFolder/".$row_product_img[0]; ?>" name = "img_src" id="img_src">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton();">Add Cart</button>
</form>
</html>
I am trying to submit a form using ajax. However, it is not showing the message that the code is wrong. I push errors the same way on the entire website so that part works.
This is my code:
<script type="text/javascript" src="jquery.js"></script>
<div id="showerrors"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#showerrors').load('errors2.php')
}, 1000);
});
</script>
<form id="formoid" method="post" action="data/newpass.php">
<div class="row2">
<input type="email" class="form-control2" placeholder="email adres" aria-describedby="basic-addon1" name="email" required>
</div>
<div class="row2">
<input type="text" class="form-control2 pull-left" placeholder="Enter code" aria-describedby="basic-addon1" name="captcha" style="width: 70%;" required>
<div class="capbg1">
<input type="text" class="disable1b pull-right" value="<?php echo $capcode3;?>" name="captcha" style="width: 29%;" disabled>
</div>
</div>
<div class="row2"></div>
<div class="row2">
<button type="submit" class="w3-black pull-left" name="req_new_pw">Request new password</button>
</div>
</form>
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : { email: $('#email').val(), captcha: $('#captcha').val() },
});
});
</script>
// newpass.php - action in the form
<?php
error_reporting(E_ALL);
session_start();
ob_start();
$db = mysqli_connect(***);
if (isset($_POST['req_new_pw']))
{
$captcha = mysqli_real_escape_string($db, $_POST['captcha']);
$email = mysqli_real_escape_string($db, $_POST['email']);
if(isset($_SESSION['capcode3']))
{
if($_SESSION['capcode3'] != $captcha)
{
array_push($errors, "- Code is incorrect.");
}
}
}
?>
//errors.php
<?php if (count($errors) > 0) : ?>
<div class="isa_error">
<i class="fa fa-times-circle"></i>
<b>Oops..</b><br>
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
//errors2.php - display errors above form
<?php
include('errors.php');
if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</div>
</h3>
</div>
<?php endif ?>
When i submit the form, nothing happens.
What am i doing wrong?
You don't send $_POST['req_new_pw'] and you are asking if it's set.
You can use serialize() to send all form element by post:
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : $('#formoid').serialize(),
});
});
</script>
Make sure you are setting $_SESSION['capcode3'] either.
This works like a charm:
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
});
Codeigniter offers you a tutorial to get to know it and how to use it. This tutorial teaches you to create elements in a table in a database, but doesn't teach you how to update this elements. I am trying to make an update query using the codeigniter libraries, but the form from de update view doesn't submit.
AT NEWS_MODEL:
public function update_news($slug)
{
$this->load->helper('url');
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
$this->db->where('slug', $slug);
$this->db->update('news', $data);
}
AT NEWS CONTROLLER:
public function update($slug)
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Update a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
// The form was NOT posted
// So we load the view
$data['news_item'] = $this->news_model->get_news($slug);
$this->load->view('templates/header', $data);
$this->load->view('news/update', $data);
$this->load->view('templates/footer');
}
else
{
// The form was submitted
$data = array(
'title' => $this->input->post('title'), //-->post variable
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text')
);
$this->news_model->update_news($slug, $data);
$this->load->view('news/success');
}
}
AT UPDATE VIEW:
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ;?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update news item" />
</form>
I've tested the code with "console.log()" and the problem seems to be that the form of the update view doesn't submit, but I cannot figure why, because the form is similar to the create form, which does work perfectly:
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
your problem is :
you use === instead of == in this line:
if ($this->form_validation->run() === FALSE)
i am using form in my page like this
<form method='post' action='' class='myform'>
<input type='text' name='name'>
<input type='text' name='email'>
<input class='btn' type='submit' name='submit' >
</form>
what i want i will get the values of form and then disable all its fields , now this is my code to disable all fields when form is submitted
$(document).on('click', '.btn', function(event) {
var currentForm = $(this).closest('form');
currentForm.find('input').prop('disabled', true);
});
and before this i'm trying to get values from $_POST like this
if(isset($_POST["submit"])){
$name= $_POST["name"];
$email= $_POST["email"];
}
but problem is that as i press submit button fields get disabled and i dont get any posted values , how do i get values first and then disable fields ?
Your mistake - You are disabling the input field by
currentForm.find('input').prop('disabled', true);
So when you submit the form, the field will be in disabled state and will not be posted.
Solution - please change the line to
currentForm.find('input').prop('readonly', true);
look this example or try with it....
if(isset($_POST["submit"]))
{
$name= $_POST["name"];
$email= $_POST["email"];
}
?>
<form method='post' action='' class='myform'>
<?php
if($name != '' && $email != '')
{
?>
<input type='hidden' name='name' value="<?php echo $name?>">
<input type='hidden' name='email' value="<?php echo $email?>">
<?php
}
?>
<input type='text' name="<?php echo ($name != ''?'hidden_name':'name')?>" <?php echo ($name != ''?'disabled':'')?> value="<?php echo $name?>">
<input type='text' name='<?php echo ($email != ''?'hidden_email':'email')?>' <?php echo ($email != ''?'disabled':'')?> value="<?php echo $email?>">
<input class='btn' type='submit' name='submit' >
</form>
You can use ajax for that like this:
$('.btn').bind('click', function() {
$.ajax({
url: "your page url here",
type: 'POST',
async:false,
success: function(response) {
$('input').prop('disabled', true);
}
});
});
you don't pass submit parameter to formdata, that's why you can't get it.
try this
<?php if(isset($_POST['name'])){ echo $_POST['name'] }?>