if/else in php script not working on ajax request - javascript

I'm working on a website with heavy Ajax, and I'm using codeigniter for building it.
I've got a form with post method, and this form is being posted using ajax request which call a function with if/else statement, like this:
if(isset($_POST['save']))
{
$data['phase'] = 'translating';
}
elseif(isset($_POST['submit']))
{
$data['phase'] = 'waiting_approve';
}
The if/else statement check which button is being clicked, and it works 100% after posting the data of the form in the usual way, but never works when posting it using ajax request.
My ajax request:
$('#workspace-content').delegate('form#article', 'submit', function(){
var that = $('form#article'),
url = that.attr('action'),
type = that.attr('method'),
data = {};
data = that.serialize();
$.ajax({
type: type,
url : url,
data : data,
dataType: 'json',
success: function(data){
$('#header-search-field').append(data.msg).delay(3000).fadeOut(500, function(){
var that = $(this);
that.html('').fadeIn();
});
}
});
return false;
});
Any suggestion or solution?!!
The HTML form:
<button id="save-article" type="submit" name="save" class="btn btn-info btn-xs pull-left">
<span class="glyphicon glyphicon-floppy-save"></span>
</button>
<input name="title" type="text" value="<?php echo $work->title;?>" class="form-control" id="title" placeholder="" />
<textarea row="10" name="article" class="form-control" id="article" placeholder=""><?php echo $work->article;?></textarea>
<button id="submit-article" type="submit" name="submit" class="btn btn-info btn-block">Send</button>
<input name="slug" type="hidden" value="<?php echo $work->slug;?>" />

When you submit a form normally, the button that you used to submit it will be included in the POST data. But when you submit with AJAX, and use that.serialize(), the POST data just includes the input fields -- the submit button isn't included. You need to attach your submit code to the buttons, so you can add the appropriate values to the data.
$('#workspace-content').on('click', 'form#article .btn', function(){
var that = $(this).closest("form"),
url = that.attr('action'),
type = that.attr('method'),
data = that.serialize();
data += '&' + this.name + '=1';
$.ajax({
type: type,
url : url,
data : data,
dataType: 'json',
success: function(data){
$('#header-search-field').append(data.msg).delay(3000).fadeOut(500, function(){
var that = $(this);
that.html('').fadeIn();
});
}
});
return false;
});

Related

multiple forms on the same page, AJAX action on submit

I am looking to use AJAX to submit multiple forms on submit. I need to get the value of a hidden field to use in the AJAX call. I have the first submit working just fine and returns the response expected.
example:
<form name="add_to_cart-12345" action="add_product" method="post">
<input type="hidden" name="products_id" value="12345" />
<input class="quantity" id="product_quantity" min="1" name="cart_quantity" value="1" step="1" type="number">
<input type="submit" class="add-to-cart" value="Add to Cart" id="addProduct-12345" />
This code can repeat 1 to n times with the values 12345 changing and being unique.
My Javascript is:
<script>
$(function() { // begin document ready
$('#addProduct').on('click', function(e) {
e.preventDefault();
var cart_quantity = document.getElementById('product_quantity').value;
var products_id = parseInt(document.getElementsByName('products_id').value);
var form = $(this).closest('form');
// AJAX request
$.ajax({
url: 'ajax_add_product.php',
type: 'POST',
dataType : "html",
data: {cart_quantity, products_id},
success: function(response){
console.log(response)
var TotalInCart = parseInt(document.getElementById('cartTotal').innerText);
var cartQuantity = parseInt(document.getElementById('product_quantity').value);
var headerTotal = cartQuantity + TotalInCart;
$("#cartTotal").html(headerTotal);
$("#cartProducts").html(response);
$("#ShoppingCartModal").modal({show:true});
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
$( document ).ajaxError(function() {
$( ".log" ).text( "Triggered ajaxError handler." );
});
});
</script>
What I need to do is to be able to submit any form when clicked. And push the product id, product quantity to the AJAX call.

Send Form Data to Controller (Codeigniter)

I have a pop up menu and inside that I have a form and a text box. I want to retrieve that value and submit it to my controller. Once submitted I want my pop up to close and go back to the other page. I tried with AJAX but I might be doing something wrong.
<form onsubmit="return(testing());" method="POST">
<input type="text" name="vip_text_box" id="vip" value="<?php echo $total_amount ?>"> <br>
<input type="submit" name="Redeem" value="Redeem">
</form>
Now My Javascript
function testing() {
$test = document.getElementById("vip").value;
var url = base_url + '/index.php/home/redeeming_form_value';
$.ajax({
type : 'POST',
url : url,
data : {'myvalue':test},
success: function(data){
alert(data);
}
});
};
In my controller
function redeeming_form_value() {
$amount = $this->input->post('myvalue');
return $amount;
In the AJAQ I have a success, and want to alert my data(the value) to make sure it even works but it does nothing. When i click submit my pop up view just goes away.
Try adding dataType: "json", to your Ajax
dataType: "json",
Then in your controller use json_encode to return your data
$arr = array('amount' => $amount);
return json_encode($arr);
Test the response in success
console.log(data.amount);
Try it..
HTML
<form action="" method="POST">
<input type="text" name="vip_text_box" id="vip" value="<?php echo $total_amount ?>"> <br>
<input type="submit" name="Redeem" id="submit" value="Redeem">
</form>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var test = $("#vip").val();
var base_url= 'http://localhost/shop';
var url = base_url + '/index.php/home/redeeming_form_value';
$.ajax({
type : 'POST',
dataType: 'json',
url : url,
data :'myvalue='+test,
success: function(data){
msg= eval(data);
amount= msg.amount;
alert(amount);
}
});
});
});
</script>
At your Controller
function redeeming_form_value()
{
$amount = $this->input->post('myvalue');
echo json_encode(array('amount'=>$amount));
}

Submitting form with AJAX not working. It ignores ajax

I've never used Ajax before, but from researching and other posts here it looks like it should be able to run a form submit code without having to reload the page, but it doesn't seem to work.
It just redirects to ajax_submit.php as if the js file isn't there. I was trying to use Ajax to get to ajax_submit without reloading anything.
Is what i'm trying to do even possible?
HTML form:
<form class="ajax_form" action="ajax_submit.php" method="post">
<input class="input" id="license" type="text" name="license" placeholder="License" value="<?php echo htmlentities($person['license1']); ?>" />
<input class="input" id="license_number" type="text" name="license_number" placeholder="License number" value="<?php echo htmlentities($person['license_number1']); ?>" />
<input type="submit" class="form_button" name="submit_license1" value="Save"/>
<input type="submit" class="form_button" name="clear1" value="Clear"/>
</form>
in scripts.js file:
$(document).ready(function(){
$('.ajax_form').submit(function (event) {
alert('ok');
event.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize(),
success: function (data) {alert('ok');}
});
});
});
in ajax_submit.php:
require_once("functions.php");
require_once("session.php");
include("open_db.php");
if(isset($_POST["submit_license1"])){
//query to insert
}elseif(isset($_POST['clear1'])) {
//query to delete
}
I have "<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>"
in the html head
form.serialize() doesn't know which button was used to submit the form, so it can't include any buttons in the result. So when the PHP script checks which submit button is set in $_POST, neither of them will match.
Instead of using a handler on the submit event, use a click handler on the buttons, and add the button's name and value to the data parameter.
$(":submit").click(function(event) {
alert('ok');
event.preventDefault();
var form = $(this.form);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize() + '&' + this.name + '=' + this.value,
success: function (data) {alert('ok');}
});
});
Your ajax call is working perfectly. You have few conceptual error with your code -
form.serialize() will not attach submit button's info.
If you want to clear your form, you can do it using something like this
$('#resetForm').click(function(){
$('.ajax_form')[0].reset();
});
Lastly complete your task & return success or failed value to ajax call using echo like echo 'successful' or echo failed etc. Use an else condition with your code. It will be more clearer to you.
Remove the "action" and "method" attributes from the form. You shouldn't need them.

Retrieve the name of the submit button in a form using jQuery

I am working with PHP and jQuery. I have 2 files
test.php
<script>
$(document).ready(function(){
$(".form-register").submit(function (e) {
var form_data = $(this).serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "test2.php",
data: form_data,
dataType: 'json',
success: function(){
alert(form_data);
}
});
});
});
</script>
<form class="form-register">
<input name="email" type="text"/>
<input name="name" type="text"/>
<input type="submit" name="register"/>
</form>
and the second file is test2.php:
<?php
if(isset($_POST['register'])){
echo json_encode('Message from test2.php');
}else{
echo json_encode('post no received');
}
It seems like I am unable to retrieve $_POST['register'] because when I check alert(form_data); only the email and the name are displayed.
Is there anyway for me to get $_POST['register']?
Add value attribute to submit button and use $('form').serializeArray() . Try:
$(".form-register").submit(function (e) {
var formData = $(this).serializeArray();
var name = $(this).find("input[type=submit]").attr("name");
var value = $(this).find("input[type=submit]").val();
formData.push({ name: name, value: value });
//now use formData, it includes the submit button
$.ajax({
type: "POST",
url: "test2.php",
data: formData,
dataType: 'json',
success: function(){
alert(form_data);
}
});
});
Neither .serialize() nor .serializeArray() will serialize the submit button value.
.serialize()
...No submit button value is serialized since the form was not submitted using a button.
.serializeArray()
...No submit button value is serialized since the form was not submitted using a button.
Only successful controls are serialized.
The input submit element is actually a successful control, but as mentioned above since the form is not submitted using the submit button, the input submit value attribute will not be included by jquery serialization.
If you want to use .serializeArray() just add the input submit elements name and value attribute values as an object to the serialized array like so.
$(document).ready(function(){
$(".form-register").submit(function (e) {
var form_data = $(this).serializeArray();
var $submit = $(this).find('input[type="submit"]');
form_data.push({name: $submit.prop("name"), value: $submit.val()});
console.log(form_data);
// do your ajax request here...
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-register">
<input name="email" type="text"/>
<input name="name" type="text"/>
<input type="submit" name="submit" value="register"/>
</form>
If you want to use .serialize() just add the values of the value and name attributes of the submit element to the text string created by the .serialize() method. Be careful, the string needs to be URL-encoded.
$(document).ready(function(){
$(".form-register").submit(function (e) {
var form_data = $(this).serialize();
var $submit = $(this).find('input[type="submit"]');
form_data = form_data + "&" + $submit.prop("name") + "=" + $submit.val();
console.log(form_data);
// do your ajax request here...
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-register">
<input name="email" type="text"/>
<input name="name" type="text"/>
<input type="submit" name="submit" value="register"/>
</form>

PHP Ajax Call Navigating to Action Page on Form Submit

I have this ajax call in my php code that still navigates to action page. I want the ajax call to stay on the same page and only update part of the page. What I'm doing wrong here:
<form method="post" id="holderSave" action="student_add_scene.php">
<h3> Save to Holder</h3><br/>
<div id="cutfrom">
<input placeholder="Cut from" name="from" id="from">
<button href="#" onclick="captureElapsed('elapseFrom', 'from');
return false;">capture</button>
</div>
<div id="cutto">
<input placeholder="Cut to" name="to" id="to" >
<button href="#" onclick="captureElapsed('elapseTo', 'to');
return false">capture</button>
</div>
<div id="savecapt">
<input placeholder="add label" id="label" name="label"/>
<input type='submit' value='Save' class='button'>
</div>
</form>
<script>
$('#holderSave').on("submit", (function (e) { // catch the form's submit event
e.preventDefault();
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
var posting = $.post( url, { from: $('#from').val(), label:$('#label').val(), to: $('#to').val()});
posting.done(function(response)){
$('#holderSave').html(response); // update the DIV
alert(response);
}
});
return false;
}));
</script>
This is a syntax error:
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
You seem to be trying to treat the object literal you pass to ajax as a function body. It isn't, so you can't just write statements in it.
Since you make the ajax request with $.post later, $.ajax is entirely pointless. Remove that line and it should work.
Fixed code. Aside from the pointless half-a-call to .ajax, you had a bunch of syntax errors which I've fixed while reformatting it.
Use your browser's developer tools console. Use http://jshint.com/
// Remove pointless ( from before the second argument of the call to on().
$('#holderSave').on("submit", function(e) {
e.preventDefault();
// Remove half a call to .ajax
var $form = $(this),
url = $form.attr('action');
var posting = $.post(url, {
from: $('#from').val(),
label: $('#label').val(),
to: $('#to').val()
});
posting.done(function(response) {
$('#holderSave').html(response);
alert(response);
// Remove line with extra } here
});
return false;
// Remove extra ) here
});
Change submit into button with id
<input type='button' id="save" value='Save' class='button'>
Trigger click event for button, serialize the form data and post the data via ajax
$(document).ready(function() {
$('#save').click(function(){ // catch the form's submit event
var form = $('#holderSave');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form .serialize(),
success: function( response ) {
console.log( response );
}
} );
});
});

Categories

Resources