Increment by one when pressing a button (in Ajax call) - php

I have some markup <span class="points-count">0</span>. When pressing a button I would like to increment this value by one in php. How do I achieve this?

You can done this using jQuery ,javascript etc., if you want only in PHP then check this code
<?php
$current_value = 0;
if($_POST['count']){
$current_value = $_POST['count'];
$current_value++;}
?>
<form action="" method="POST">
<span class="points-count"><?=$current_value?></span>
<input type="hidden" name="count" value="<?=$current_value?>">
<button type="submit">Add</button>
</form>

If you really want to make a counting number using ajax call here is the sample:
counter.php:
<?php
$counter = $_GET['current_value'] + 1; //value is increase here
echo json_encode(['new_value' => $counter]); //return the value in JSON format
?>
Your HTML File:
<span class="points-count">0</span>
<button onclick="count()">Increase</button>
<script type="text/javascript">
function count() {
$.ajax({
url : "counter.php",
type : "GET",
dataType: "json",
data : {
current_value: $(".points-count").html() //set value here
},
success: function(data) {
$(".points-count").html(data.new_value); //finally, get the returned value of the php script
}
});
}
</script>

Instead of using php.
you can use jquery or javascript for this. php is for server side render only.

Related

How to get result from php to html use ajax?

Updated: It still not work after I add "#".
I am new to ajax. I am practicing to send value to php script ,and get result back.
Right now, I met one issue which I can not show my result in my html page.
I tried serves answers online, but I still can not fix this issue.
My index.html take value from the form and send form information to getResult.php.
My getResult.php will do calculation and echo result.
How do I display result into index.html?
Hers is html code
index.html
<html>
<body>
<form name="simIntCal" id="simIntCal" method="post"
>
<p id="Amount" >Amount(USD)</p>
<input id="amount_value" type="text" name="amount_value">
<p id="annual_rate" >Annual Rate of Interest
(%)</p>
<input id="rate_value" type="text" name="rate_value">
<p id="time_years" >Time (years)</p>
<input id="time_value" type="text" name="time">
<input id="calculate" type="submit" value="Calculate">
</form>
<p id="amount_inteCal" >The Amount (Acount
+ Interest) is</p>
<input id="result" type="text">
</body>
</html>
ajax script :
<script>
$('#simIntCal').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'getResult.php',
data: $('#simIntCal').serialize(),
success: function (result) {
$("#result").text(result);// display result from getResult.php
alert('success');
}
});
});
</script>
getResult.php
<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
//do some calculation
$result=10;//set result to 10 for testing
echo $result;
}
?>
You are missing the '#' in front of your css selector for result.
$("result").text(result);// display result from cal.php
Should be
$("#result").text(result);// display result from cal.php
index.php
----php start---------
if(isset($_POST['name'])){
echo 'Thank you, '.$_POST['name']; exit();
}
----php end ---------
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function test(){
var formDATA = {'name': $('#input_name').val()}
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
$('#result').html();
}
});
}
</script>
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code.
Also don't forget to include your jquery resources.
In your html file where you want the result to display, you probably want to be using a div.
Currently your code is using an input field:
<input id="result" type="text">
And what you probably want is something like this:
<div id="result"></div>
Unless you were intending to have the result show up in an input field inside your form, and in that case, the input field isn't actually inside your form code.

PHP page not recieving POSTed jquery ajax request

I have my first PHP page having search form:
<form action="#" class="form-inline" id="form_srch">
<input type="text" id="toSearch" name="toSearch" placeholder="Enter Application Number" class="form-control" style="width:250px" required >
<button type="button" class="btn btn-primary" onclick="search()">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
<i><b><p style="display:none;color:red" id="result">** Empty Value</p></b></i>
</form>
<div id="ajax"></div>
and a javascript function
<script>
function liveCheck() {
$("#result").show();
}
function search() {
var inp = $("#toSearch").val();
if(jQuery.trim(inp).length > 0)
{
jQuery.ajax({
url: "load_search_prereg.php",
data:{ to : inp },
type: "POST",
success:function(data){
$("#ajax").load('load_search_prereg.php');
//alert(data);
},
error:function (){}
});
}
else{
liveCheck();
}
}
</script>
And i have my second PHP page named load_search_prereg.php to process the POSTed input and the code is
<?php
require '../backend/_classes.php';
$x = new DB();
$id = $_POST['to'];
$sql=$x->select(1,'*','tblregistration','app_number',"'$id'");
$fetch = $sql->fetchObject();
var_dump($fetch);
The problem is when i clicked the search button in my first PHP page, It displays no array of posted data while im using the $("#ajax").load('load_search_prereg.php'); method in my javascript. But when i use alert(data);, it returns the expected result. Does the problem occur in $("#ajax").load('load_search_prereg.php'); method ? Help pls.
Not:
$("#ajax").load('load_search_prereg.php');
But:
$("#ajax").html(data);
I've assumed you just want to write this data into div
edit:
instead of var_dump($fetch); you must return your data a JSON object, eg:
$fetch = $sql->fetchObject();
echo json_encode($fetch);
Then you can do in js what you want
It should be method:"POST" instead of type: "POST".
By default method is set to GET.

$_POST for text in DIV elements

Because of my web style, i don't want to use input & textarea and get information by using $_POST[] and i need to get information that is in DIV element.
For example , I want to get information in this :
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
and :
$_POST[myname];
But i can't do it with $_POST , How can i do it ??
And if this method can't do this , do you know any other method to get information from DIV like this ?
you can call a onsubmit function and make a hidden field at the time of form submission like this
HTML
need to give a id to your form id="my_form"
<form action="submit.php" method="post" id="my_form">
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="submit" value="submit" name="submit" />
</form>
Jquery call on submit the form
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.mine').text();
$(this).append("<input type='hidden' name='myname' value=' " + hvalue + " '/>");
});
});
PHP : submit.php
echo $_POST['myname'];
You can use this method. First, with javascript get content of <div>
Code:
<script type="text/javascript">
var MyDiv1 = Document.getElementById('DIV1');
</script>
<body>
<div id="DIV1">
//Some content goes here.
</div>
</body>
And with ajax send this var to page with get or post method.
You would need some JavaScript to make that work, e.g. using jQuery:
$.post('http://example.org/script.php', {
myname: $('.mine').text()
});
It submits text found inside your <div> to a script of your choosing.
You can use following structure;
JS:
$(document).ready(function() {
$("#send").on("click", function() {
$.ajax({
url: "your_url",
method: "POST",
data: "myname=" + $(".mine").text(),
success: function(response) {
//handle response
}
})
})
})
HTML:
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="button" name="send" id="send" value="Send"/>
You can see a simulation here: http://jsfiddle.net/cubuzoa/2scaJ/
Do this in jquery
$('.mine').text();
and post data using ajax.
Put the content of DIV in a variable like below:
var x = document.getElementById('idname').innerHTML;

compact all form-data with javascript

I would like to compact all data from a huge HTML-form with over a 1000 variables to circumvent the max_input_vars limit in PHP versions before 5.3.9.
How can I read all data in the HTML-form with javascript, serialize it (or create json) to put it all in only one hidden field that contains the whole data then?
On the receiving side I would uncompress it with PHP (for example with json_decode)
Just sent a ajax post?
form.html with javascript
<form action="process.php" method="post" id="form">
<input type="text" name="name">
<input type="text" name="username">
<button type="submit" id="sendForm">Send</button>
</form>
<!-- YOUR JAVASCRIPT -->
<script type="text/javacript">
$('#sendForm').click(function() {
$.ajax({
type: 'POST',
url: $('#form').attr('action'),
data: $('#form').serialize(),
success: function(data) {
// WHATEVER YOU WANT HERE
}
});
return false;
});
</script>
process.php
<?php
$name = $_POST['name'];
// other form fields here
}
Serialize it using JQuery. You can then parse the URL string using PHP.
perhaps serialize and JSON.stringify may work together, though I have not tried it.
I created a script that does the job on all post forms automatically:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
// this disables all form elements and creates only one new element that contains all data serialized
$('form[method="post"]').submit(function() {
var num_form_elements=$(this).find('input, select, textarea').not('[type="submit"]').length;
var num_elements_already_disabled=$(this).find('input:disabled, select:disabled, textarea:disabled').length;
enabled=(num_form_elements-num_elements_already_disabled);
if($('textarea[name="serialized_data"]', this).length > 0) {
alert("Backbutton is not supported yet!");
return false;
}
if($('textarea[name="serialized_data"]', this).length > 0 || enabled<=0) {
alert("Reload of the form is not supported yet!");
return false;
}
var data=$(this).serialize();
$(this).find('input, select, textarea').not('[type="submit"]').attr("disabled", true);
$(this).append(' <input type="hidden" name="num_form_elements" value="'+num_form_elements+'">');
$(this).append(' <input type="hidden" name="num_elements_already_disabled" value="'+num_elements_already_disabled+'">');
$(this).append(' <textarea style="display:true" name="serialized_data">'+(data)+'</textarea>');
// maybe in the textarea I have to .replace(/</g,'<') ?
});
</script>
On the receiving side you cannot use the PHP parse_str() function because the max_input_vars directive affects this function too, so you need something else: I took my_parse_str() from https://gist.github.com/rubo77/6821632
<?php
$params=my_parse_str($_REQUEST['serialized_data']);
echo count($params,1)." serialized variables:<br>";
var_export($params);
?>
Example script on https://gist.github.com/rubo77/6815945

sending form data to php using ajax

I Have an requirement to pass form data to php using ajax and implement it in php to calculate the sum , division and other arithmetic methods I am a new to ajax calls trying to learn but getting many doubts....
It would be great help if some one helps me out with this
index.html
<script type="text/javascript">
$(document).ready(function(){
$("#submit_btn").click(function() {
$.ajax({
url: 'count.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data');
}
})
});
</script>
</head>
<form name="contact" id="form" method="post" action="">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
In count.php i want to implement
<?php
$FNO = ($_POST['FNO']);
$SNO=($_post['SNO']);
$output=$FNO+$SNO;
echo $output;
?>
(i want to display output in count.php page not in the first page index.html)
Thanks for your help in advance.
You can use a simple .post with AJAX. Take a look at the following code to be able to acheive this:
$('#form').submit(function() {
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("count.php",$(this).serialize(),function(data){
alert(data); //check to show that the calculation was successful
});
return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});
This sends all of your form variables to count.php in a serialized array. This code works if you want to display your results on the index.html.
I saw at the very bottom of your question that you want to show the count on count.php. Well you probably know that you can simply put count.php into your form action page and this wouldn't require AJAX. If you really want to use jQuery to submit your form you can do the following but you'll need to specify a value in the action field of your form:
$("#submit_btn").click(function() {
$("#form").submit();
});
I have modified your PHP code as you made some mistakes there. For the javscript code, i have written completely new code for you.
Index.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<form name="contact" id="contactForm" method="post" action="count.php">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
<label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
<!-- The following div will use to display data from server -->
<div id="result"></div>
</body>
<script>
/* attach a submit handler to the form */
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
//Get the first value
value1 = $form.find( 'input[name="SNO"]' ).val(),
//get second value
value2 = $form.find( 'input[name="FNO"]' ).val(),
//get the url. action="count.php"
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { SNO: value1, FNO: value2 } );
/* Put the results in a div */
posting.done(function( data ) {
$( "#result" ).empty().append( data );
});
});
</script>
</html>
count.php
<?php
$FNO = $_POST['FNO'];
$SNO= $_POST['SNO'];
$output = $FNO + $SNO;
echo $output;
?>
There are a few things wrong with your code; from details to actual errors.
If we take a look at the Javascript then it just does not work. You use the variable data without ever setting it. You need to open the browser's Javascript console to see errors. Google it.
Also, the javascript is more complicated than is necessary. Ajax requests are kind-of special, whereas in this example you just need to set two POST variables. The jQuery.post() method will do that for you with less code:
<script type="text/javascript">
$(document).ready(function(){
$("#form").on("submit", function () {
$.post("/count.php", $(this).serialize(), function (data) {
alert(data);
}, "text");
return false;
});
});
</script>
As for the HTML, it is okay, but I would suggest that naming (i.e. name="") the input fields using actual and simple words, as opposed to abbreviations, will serve you better in the long run.
<form method="post" action="/count.php" id="form">
<label for="number1">Enter First no:</label>
<input type="number" name="number1" id="number1">
<label for="number2">Enter Second no:</label>
<input type="number" name="number2" id="number2">
<input type="submit" value="Calculate">
</form>
The PHP, as with the Javascript, just does not work. PHP, like most programming languages, are very picky about variables names. In other words, $_POST and $_post are not the same variable! In PHP you need to use $_POST to access POST variables.
Also, you should never trust data that you have no control over, which basically means anything that comes from the outside. Your PHP code, while it probably would not do much harm (aside from showing where the file is located on the file system, if errors are enabled), should sanitize and validate the POST variables. This can be done using the filter_input function.
<?php
$number1 = filter_input(INPUT_POST, 'number1', FILTER_SANITIZE_NUMBER_INT);
$number2 = filter_input(INPUT_POST, 'number2', FILTER_SANITIZE_NUMBER_INT);
if ( ! ctype_digit($number1) || ! ctype_digit($number2)) {
echo 'Error';
} else {
echo ($number1 + $number2);
}
Overall, I would say that you need to be more careful about how you write your code. Small errors, such as in your code, can cause everything to collapse. Figure out how to detect errors (in jQuery you need to use a console, in PHP you need to turn on error messages, and in HTML you need to use a validator).
You can do like below to pass form data in ajax call.
var formData = $('#client-form').serialize();
$.ajax({
url: 'www.xyz.com/index.php?' + formData,
type: 'POST',
data:{
},
success: function(data){},
error: function(data){},
})

Categories