I'm keen to know how to send and manage 2 values out of one php-form without reloading/refreshing. This is a simple up-down voting formular to vote with one click.
I've startet with the form:
echo "<form id='votingform' method='post'>";
echo "<button id='rateup' /><i class='fa fa-thumbs-o-up fa-2x'></i></button>";
echo "<button id='ratedown' /><i class='fa fa-thumbs-o-down fa-2x'></i></button>";
echo "<input type='hidden' value='".$id."' name='rateid' />";
echo "</form>";
Then I'm using some jquery to prevent formula-submit and add some visible response for testing purposes:
$(document).ready(function() {
var form = $('#votingform');
var submit = $('#rateup'); // submit button
var submit2 = $('#ratedown'); // submit button
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Send Email'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
form.on('submit2', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Send Email'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
And added some action:
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
$vote1 = $_POST['rateup'];
$vote2 = $_POST['ratedown'];
echo $vote1; echo $vote2;
// sql part goes here
}
return;
}
The $vote1 is ok, $vote2 is empty. Does anyone have a clue on this and can help me to solve this problem? Or maybe a smarter way to get this thing working? Thanks for your help in advance!
Button elements do not send their value - hence no POSTed value.
Change your elements to
<form id='rateform' action='' method='post'>
<input type='submit' name='submit' class='votecomment' value='up' />
<input type='submit' name='submit' class='votecomment' value='down' />
<input type="hidden" value="1" name="test" />
</form>
Try this :
$http_post = ('POST' == $_SERVER['REQUEST_METHOD']);
if($http_post)
{
echo $_POST['submit']; // no result
echo $_POST['test'];
}
If you click on up then $_POST['submit'] will echo 'up' and if you click on down then $_POST['submit'] will echo 'down'
Related
I need help. Now I trying to create a function that can detect any change value from PHP form. Now I'm working using CodeIgniter. I explain more detail about this.
I making an e-commerce site. If the user in the cart page and changing the qty but the user not yet checkout and still want to browser more.... when the user has to change qty and press to another page. It will display pop up alert. This pop-up alert have a function to save the changing Qty. But if the user not changing anything. The pop-up alert should not show.
I already set this in the menu.
<?php echo form_open('order_products_execute', 'class="order_form"'); ?>
<?php include(VIEWPATH.'_order_parts.html') ?>
<div class="common_btn_area">
<input type="hidden" name="branch_id" value="<?php echo $branch_id; ?>">
<button type="button" class="add_cart_more">add more</button>
<button type="submit" class="common_save_btn confirmation">Order</button>
</div>
<?php echo form_close(); ?>
<!-- footer menu -->
<ul>
<li>
<a href="<?php echo base_url('top/'); ?>" class="footer_link" onclick="ExitCart('<?php echo base_url('top/'); ?>')" >
<span>Home</span>
</a>
</li>
<li>
<a href="<?php echo base_url('product/'); ?>" class="footer_link" onclick="ExitCart('<?php echo base_url('product/'); ?>')" >
<span>Product</span>
</a>
</li>
</ul>
and set the script
<script>
function ExitCart(link){
var $form = $('.order_form');
#code for compare previous value with changing value
$.ajax( {
type: $form.attr('method'),
url : "/buyer/ajax/compare_form_add_cart",
dataType : "json",
data : $form.serialize(),
success : function(resultdata) {
if(resultdata){
if(confirm("Do you want to save your changes?")){
#if confirm yes
$.ajax({
type: 'post',
url: '/buyer/Ajax/add_order_data_in_cart_session',
data: $('.order_form').serialize(),
dataType: 'json',
success: function(res, textStatus, xhr){
if(res.result) {
location.href = link;
} else {
$( "#loading_layer" ).css('display', 'none');
alert('Failed to save cart data. Please try again.');
}
}
});
}else{
#if confirm not
location.href = link;
};
}else{
return true;
}
}
});
}
</script>
When I implement this ajax code, sometimes the code is working. But sometimes it is not. Is there any code that can detect any change from the form. But without the press submit button.
in jQuery you can bind all the inputs changes
$('.order_form input').change(functon(){
var $form = $('.order_form');
#code for compare previous value with changing value
$.ajax( {
type: $form.attr('method'),
url : "/buyer/ajax/compare_form_add_cart",
dataType : "json",
data : $form.serialize(),
success : function(resultdata) {
if(resultdata){
if(confirm("Do you want to save your changes?")){
#if confirm yes
$.ajax({
type: 'post',
url: '/buyer/Ajax/add_order_data_in_cart_session',
data: $('.order_form').serialize(),
dataType: 'json',
success: function(res, textStatus, xhr){
if(res.result) {
location.href = link;
} else {
$( "#loading_layer" ).css('display', 'none');
alert('Failed to save cart data. Please try again.');
}
}
});
}else{
#if confirm not
location.href = link;
};
}else{
return true;
}
}
});
})
You need to make copies of your input fields for example
// Input Field (TEXT)
< input type="text" id="input1" value="Same Value" />
// Hidden Input for comparison
< input type="hidden" value="Same Value" />
at on click function, you should compare these fields like
function ExitCart(link){
// Get Input Value
var val = $.trim($('#input1').val());
// Get Reference Value from next input
var valChk = $.trim($('#input1').next().val());
if(val != valChk) {
YOUR CODE HERE
}
}
I am working in wordpress and I have one form and two submit buttons. I am using ajax and it is wordpress.
When first submit button is pressed I want statement 1 to be echoed and when submit button number 2 is pressed I want state 2 be echoed. I have followed the code tutorials but when I press submit from the control returns empty or no result and in inspect there is no error in the browser. Below is my code.
HTML Form
<form id="voteform" action="" method="post">
<input name='vote' value='two' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'>
<input name='vote' value='one' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'>
</form>
I am not copying the enqueue code but just the actual php function that executes
function articlevote ()
{
if ($_POST['vote'] == 'one') {
echo json_encode("1 vote button is pressed");
die();
}
else if ($_POST['vote'] == 'two') {
echo json_encode("2 vote button is pressed");
die();
}
}
Ajax and jquery
jQuery(function ($) {
$(document).on("click","input[name=vote]", function() {
var _data= $('#voteform').serialize() + '&vote=' + $(this).val();
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data:_data,
success: function(html){
$("#myresult").html(res);
}
});
return false;
});
});
Again kindly note that I am using wordpress so kindly guide me in this thanks
This should get you what you need:
Html:
<form id="voteform" action="" method="post">
<input type="text" name="field1" value="field one value"/>
<input type="text" name="field2" value="field two value"/>
<input class='vote' value='two' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'/>
<input class='vote' value='one' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'/>
</form>
jQuery
jQuery(function($) {
var yes = {ajaxurl:"mypage.php"}; // created for demo
$('.vote').click(function(e) {
e.preventDefault(); // stop the normal submit
var _data = $('#voteform').serialize()+'&vote=' + $(this).val();
//alert(_data)
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data: _data,
success: function(html) {
$("#myresult").html(html); // you had `res` here
}
});
});
});
$(document).ready(function(){
$('input[value=\'one\'], input[value=\'two\']').on('click', function(){
var _data= $('#voteform').serialize() + '&vote=' + $(this).val();
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data:_data,
success: function(html){
$("#myresult").html(res);
}
});
return false;
});
});
This is an example of my own page.
<?php
$do = $_GET['do'];
switch($do){
case 'finalTask':
if(isset($_POST['url'])){
echo "It's Ok!";
}else{
echo "Problem!";
}
}
This is also written in the same page.
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script>
$(document).ready(function(e){
$('#send').click(function(){
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url:"index.php?do=finalTask",
cache:false,
data:dataStr,
type:"POST",
success:function(data){
$('#info').html(data);
}
});
});
});
</script>
When I try to input and press the send button. Nothing happened..... What's wrong with the code?
Make sure file name is index.php
You need to make sure that you check in the php code when to output the form and when the
Format of ajax post request is incorrect in your case.
You forgot to import JQuery JS script, without that you can not use JQuery. (at least at this point of time)
-
<?php
if (!isset($_GET['do'])) { // Make sure that you don't get the form twice after submitting the data
?>
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#send').click(function () {
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url: "index.php?do=finalTask",
cache: false,
data: {url: dataStr}, // you need to send as name:value format.
type: "POST",
success: function (data) {
$('#info').html(data);
}
});
});
});
</script>
<?php
} else {
error_reporting(E_ERROR); // Disable warning and enable only error reports.
$do = $_GET['do'];
switch ($do) {
case 'finalTask':
if (isset($_POST['url'])) {
echo "It's Ok!";
} else {
echo "Problem!";
}
}
}
?>
There seems to be no form in your page, just form elements. Can you wrap them in a form:
<form method="POST" onSubmit="return false;">
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
</form>
I need any jQuery code to send form data without refreshing the page.
Method (POST): after submit form show "loading..." message or "loading image". If process.php = 1 (true) hide form and display ok message, and if process.php = 2 ( false ) not hide form and display any error message.
var data = new Object();
data['formData'] = $('#form').serializeArray();
$.ajax({
type: 'post',
url: 'process.php',
dataType: 'json',
success: function(response) {
if (response.result == 1) {
$('#form').hide();
} else {
alert('error');
}
}
});
process.php:
//...
echo json_encode(array('result' => 0)); // OR 1
You need to add form ID or any other identificator.
so, if your form is
<div id="message"> </div>
<form method="post" action="" id="myForm">
<input type="submit" name="send" id="sendData" />
</form>
jQuery:
$(document).ready(function() {
$("#sendData").click(function() {
$("#message").html("loading ...");
$.post("process.php", {
submit: 1 //and any other POST data you separate with comma
}, function(response) {
if(response == 1) {
$("#myForm").hide();
$("#message").html("OK");
} else {
$("#message").html("error message");
}
});
});
});
now, after submit form you will get message "loading ..." while posting "process.php", then if process.php returns 1 the form will be hide and display OK else you get an error message.
I have a form like this:
one.php
<form id='myFormId' name='myFormName'>
<input type='text' name='myTextField'>
<a href='two.php'>Show Value</a>
</form>
Question:
I want to pass 'myTextField' textbox value to two.php and want to echo it on screen. I can't use submit button and also can't submit the form. Is there any trick ?
Thanks
You could start by giving the anchor an unique id:
<a id="mylink" href="two.php">Show Value</a>
and then register for the click event handler and send an AJAX request:
$(function() {
$('#mylink').click(function() {
$.ajax({
url: this.href,
data: { myTextField: $('#myFormId input[name=myTextField]').val() },
success: function(result) {
// TODO: use the resulting value
alert(result);
}
});
return false;
});
});
one.php
<form id='myFormId' name='myFormName'>
<input type='text' name='myTextField'>
<a href='two.php?value=myTextField'>Show Value</a>
</form>
two.php
echo $_GET['value'];
<form id='myFormId' name='myFormName'>
<input type='text' name='myTextField'>
<a href='two.php' id='myLink'>Show Value</a>
</form>
jQuery('#myLink').live('click',function() {
$.ajax({
url: this.href,
type: 'POST',
data: $('#myFormId').serialize(),
success: function( data ) {
// TODO: use the resulting value
alert(data);
}
});
return false;
});