submiting with ajax and displaying the data on input or div - php

I have this php script to count button clicks to a txt file
<?php
if (isset($_POST['clicks1'])) {
incrementClickCount1();
}
function getClickCount1() {
return (int) file_get_contents("count_files/clickcount1.txt");
}
function incrementClickCount1() {
$count = getClickCount1() + 1;
file_put_contents("count_files/clickcount1.txt", $count);
}
if (isset($_POST['clicks2'])) {
incrementClickCount2();
}
function getClickCount2() {
return (int) file_get_contents("count_files/clickcount2.txt");
}
function incrementClickCount2() {
$count2 = getClickCount2() + 1;
file_put_contents("count_files/clickcount2.txt", $count2);
}
?>
this is my html
<?php
include ('counter.php');
?>
<div class="count_right"><?php echo getClickCount1(); ?></div>
<div class="count_left"><?php echo getClickCount2(); ?></div>
<form action="counter.php" method="post" >
<button type="submit" class="vote_right" name="clicks1" ></button>
<button type="submit" class="vote_left" name="clicks2"></button>
</form>
What I'm trying or want to do is to update the counts on the divs but without refreshing the page.
I've tried using ajax but could not get the click value to show in the divs.
i thought about using text feilds insted, but dont realy know how.
This is a part of my jquery ajax code i used :
$('.vote_right, .vote_left').click(function(){
$.ajax({
url: 'counter.php',
type: 'post',
dataType:'html', //expect return data as html from server
data: $('.form1').serialize(),
});
});
I assume i made a bit of a mess, but thats why I'm here :)
EDIT
thanks guys, forgot to mention.. the code works but my problame is that its:
refreshes the page after submiting
not working when i use onSubmit="return false"
not displaying changes with e.preventDefault();

Add e.preventDefault(); to your click handler:
$('.vote_right, .vote_left').click(function(e){
e.preventDefault();
$.ajax({
url: 'counter.php',
type: 'post',
dataType:'html', //expect return data as html from server
data: $('.form1').serialize(),
});
});

You should use ajax.
Html
<?php
include ('counter.php');
?>
<div class="vote_right"><?php echo getClickCount1(); ?></div>
<div class="vote_left"><?php echo getClickCount2(); ?></div>
<form action="counter.php" method="post" >
<input type="button" class="vote_right" name="clicks1" >
<input type="button" class="vote_left" name="clicks2" >
</form>
jquery
$('.vote_right, .vote_left').click(function(){
class_count = $(this).attr("class");
count = $("."+class_count).text();
type = class_count == "vote_right" ? "right" : "left";
$.ajax({
url: 'counter.php',
type: 'post',
data: {"type": type,"count" : count},
success: function(data){
$("."+class_count).text(data);
}
});
});
In your php you will get which button it clicked by $_REQUEST["type"](left or right) and current count of this button by $_REQUEST["count"] . Add these lines at the top of your php file.
php
if(isset($_REQUEST["type"]){
if($_REQUEST["type"] == "right" )
$_POST['clicks1'] = "1";
else
$_POST['clicks2'] = "1";
}
It should done your work;

Related

Detect any change from PHP form without using submit button

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

wizard-form tow button different call ajax

I apologize for the ease of this question for you.
But I looked at your beautiful site for an answer to my problem, but I was not lucky.
I'm trying to build my own,form-wizard for student registration, in easy steps as a graduate project for university.
I use PHP, JQuery and AJAX to send data .
My problem:
I have a single form and to button ,
The first three input are searched in the database via the submit button and it is worked good ,
then automatically form-wizard moves to the next fieldset and then displays the inpust field to
student to enter his information .
finally thir is button to save data to database
by AJAX and this button is my problem .
the php say undefined index .
this is code for html wizard-form
$('form').on('submit', function(e) {
var $formInput = $(this).find('.fi');
$formInput.each(function(i) {
if (!$(this).val()) {
e.preventDefault();
$(this).addClass('input-error');
return false;
} else {
if ($formInput.length === i + 1) {
var id_high_school = $('[name="id_high_school"]').val();
var SEC_SCHOOL_YEAR = $('[name="SEC_SCHOOL_YEAR"]').val().toString();
var sum_high_school = $('[name="sum_high_school"]').val();
alert(SEC_SCHOOL_YEAR);
$.ajax({
url: "select_for_modal_serch.php",
method: "post",
data: {
id_high_school: id_high_school,
SEC_SCHOOL_YEAR: SEC_SCHOOL_YEAR,
sum_high_school: sum_high_school
}
}).done(function(datas) {
$('#studint_detail').html(datas);
$('#dataModal').modal("show");
}).fail(function() {
alert('fail..');
});
}
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form name="mainForm" action=" <?php echo $_SERVER['PHP_SELF'] . '#form1' ?> " id="form1" method="POST" enctype="multipart/form-data">
<!-- condetion for regster -->
<fieldset>
<iframe src="license.html"></iframe>
<input class="form-check-input" id="check_qury" type="checkbox" value="yes">
<div class="wizard-buttons">
<button type="button" class="btn btn-next">التالي</button>
</div>
</fieldset>
<fieldset>
<!-- 3 <input type = text > to search for data from mysql -->
<!--her is the submit button and is get data by ajax -->
<input type="submit" class="form-control btn btn-primary view-data" id="submit_high_school" value="بحث" name="submit_high_school" />
<!-- by ajax is work and then is go to the next filedset -->
</fieldset>
<fieldset>
<!-- mor data <input type = text > to search for data from mysql -->
<button type="button" id="sava_data_to_tables" name="sava_data_to_tables" class="btn btn-next">
<!-- this is the button of my problem cant send this form data to mysql -->
</fieldset>
I doing this code to solve the problem but nothing work :
$('#sava_data_to_tables').on('click', function (event) {
var form_data = $(this).parents('form').serialize();
var colage = $('[name="colage"]').val();
var spichelest = $('[name="spichelest"]').val();
// and rest of input type
$.ajax({
url: "insert_into_info_contact.php",
method: "POST",
data: form_data,
success: function (data) {
alert(data);
}, cache: false,
contentType: false,
processData: false
});
});
and my PHP :
<?php
// isset($_POST['sava_data_to_tables'])
//$_SERVER['REQUEST_METHOD']==='POST'
// !empty($_POST)
if ($_SERVER['REQUEST_METHOD']==='post')
{ echo "you submit data"
;}
else {
echo "its not work" ; }
?>
I found some help from a friend ..
He just change this :
var form_data = $(this).closest('form').serialize();
to this :
var form_data = new FormData($(this).closest('#form1').get(0));
He solved my problem.
I honestly did not understand what the problem was, but he told me I had sent a different kind of data >> Thanks every One . :)

PHP Jquery Ajax POST call, not work

As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>

Getting data from PHP page on form submit

I have index.php with a form. When it gets submitted I want the result from process.php to be displayed inside the result div on index.php. Pretty sure I need some kind of AJAX but I'm not sure...
index.php
<div id="result"></div>
<form action="" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
</form>
process.php
<?php
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
?>
You really don't "need" AJAX for this because you can submit it to itself and include the process file:
index.php
<div id="result">
<?php include('process.php'); ?>
</div>
<form action="index.php" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
<input type="submit" name="submit" value="Submit">
</form>
process.php
<?php
// Check if form was submitted
if(isset($_GET['submit'])){
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
}
?>
Implementing AJAX will make things more user-friendly but it definitely complicates your code. So good luck with whatever route you take!
This is a jquery Ajax example,
<script>
//wait for page load to initialize script
$(document).ready(function(){
//listen for form submission
$('form').on('submit', function(e){
//prevent form from submitting and leaving page
e.preventDefault();
// AJAX goodness!
$.ajax({
type: "GET", //type of submit
cache: false, //important or else you might get wrong data returned to you
url: "process.php", //destination
datatype: "html", //expected data format from process.php
data: $('form').serialize(), //target your form's data and serialize for a POST
success: function(data) { // data is the var which holds the output of your process.php
// locate the div with #result and fill it with returned data from process.php
$('#result').html(data);
}
});
});
});
</script>
this is jquery Ajax example,
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
How about doing this in your index.php:
<div id="result"><?php include "process.php"?></div>
Two ways to do it.
Either use ajax to call your process.php (I'd recommend jQuery -- it's very easy to send ajax calls and do stuff based on the results.) and then use javascript to change the form.
Or have the php code that creates the form be the same php code that form submits to, and then output different things based on if there are get parameters. (Edit: MonkeyZeus gave you specifics on how to do this.)

issue sending and retrieving value using ajax

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
}
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Looks like you never tell AJAX that the POST name is 'centro', try to change this:
data: $("#form_"+i).serialize(),
for this
data: { 'centro' : $("#form_"+i).serialize()},
I've run into the same problem with my ajax calls that I call via the POST method. My data was actually getting passed in the message body. I had to access it through the following method:
php://input
This is a read only wrapper stream that allows you to read raw data from the message body.
For more information on this wrapper visit this link.
Tray adding the following to your PHP file:
$centro = file_get_contents("php://input");
// Depending on how you pass the data you may also need to json_decode($centro)
echo json_encode($centro);
// See if you get back what you pass in
This read the message body (with my posted data) and I was able to access the value there.
Hope this helps.
try to using this code in your ajax post :
jQuery('#centro_'+i).click( function() {
$.ajax({
data: $("#centro_"+i).closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$('#cuentas').html(data);
alert(data);},
type:"post",
url:"load_cuentas.php"
});
});
Try this:
HTML
<?php
$i=0;
$f=0;
$consulta = $db->consulta("SELECT * FROM centro");
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){ ?>
<form id="form_<?php echo $f++; ?>"> //begin form with its id
<div class="centro" id="centro_<?php echo $i++; ?>">
<?php echo $resultados1['nombre_centro']; ?>
<br>
<input type="hidden" name="centro" value="<?php echo $resultados1['id_centro']; ?>">
<!--this is the data that is going to be sent. I set up a hidden input to do it.-->
</div>
</form>
<div id="cuentas" class="cuentas">
<!--where data is going to be displayed-->
</div>
<br>
<?php
}
}
?>
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('.centro').on('click',function() {
var formElem=jQuery(this).closest('form');
jQuery.ajax({
url: 'load_cuentas.php',
cache: true ,
type:'POST',
dataType: 'json',
data: $(formElem).serialize(),
success: function(output_string){
jQuery(formElem).next('div.cuentas').html(output_string);
alert(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
Server page:
<?php
include ('mysql.php');
$db = new mysql();
$centro = $_POST['centro']; //this is not getting any data. the whole ajax thing
$consulta = $db->consulta("SELECT * FROM cuenta WHERE id_center = '$centro'");
$output_string=array();
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){
$output_string []= 'test text';
}
}
mysql_close();
echo json_encode($output_string);
?>

Categories