I want to retrieve post values in php in jquery form, so as to submit the form using jquery. I am using jquery.submit() function to submit my form. Example is as below
$('#form').submit(function{
var data = '//post variables from php script here';
$.ajax({
type:'post',
data:data,
url://url to save the data,
success:function(response){
//success message here;
}
});
Can anyone please help me?
I don't know exactly what you want to do, but as far as I can see it seems that you need json_encode php function.
var data = '<?php echo json_encode($_POST)?>';
You cannot directly extract POST variables in JavaScript - which you can with GET since they are part of the URL (?my_get_variable=is_here etc.)
If you really NEED to have access to your POST variables in JavaScript, what you could do is make some PHP iterating over and printing out the post variables. The following code fills a JavaScript array called PostVariables with the post variables passed to your page:
<script type="text/javascript">
var postVariables = new Array();
<?php foreach($_POST as $key => $value): ?>
postVariables['<?=$key?>'] = '<?=$value?>';
<?php endforeach; ?>
</script>
If your POST body is name=John&pet=Cat&friends=Many, you will get the following code:
<script type="text/javascript">
var postVariables = new Array();
postVariables['name'] = 'John';
postVariables['pet'] = 'Cat';
postVariables['friends'] = 'Many';
</script>
Of course, this does require PHP.
If you need the data in that format, just adapt the script:
<script type="text/javascript">
var myData = "";
<?php foreach($_POST as $key => $value): ?>
myData += "<?=$key?>=<?=$value?>&";
<?php endforeach; ?>
</script>
You can post form data with serialize. Example form:
<form id="myForm" method="POST">
<input name="one" value="11" />
<input name="two" value="22" />
<input id="submit" type="submit" value="11" />
</form>
<div id="test"></div>
Javascript
<script type="text/javascript">
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
data: $("#myForm").serialize(),
url:'mypage.php',
success:function(response){
$("#test").html(response);
}
});
});
</script>
mypage.php
<?php var_dump($_POST); ?>
output
array (size=2)
'one' => string '11' (length=2)
'two' => string '22' (length=2)
Solved myself. Had been using the plugin jquery form on my site. Implemented the form submit using same.
http://malsup.com/jquery/form/#ajaxForm
Related
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.
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;
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
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){},
})
I am using JavaScript to pass a variable to another php file. I have a value in javascript, and I want to pass it as a post variable to another php file.
Javascript code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" >
//Important code here to post a variable to bh.php:
$(document).ready(function(){
$('#op_comp_id').load('bh.php').show();
$('#get_value_id').keyup(function() {
$.post('bh.php', { id: form.get_value.value },
function(result){
$('#op_comp_id').html(result).show();
});
});
});
</script>
</head>
<body>
<?$id = $_GET['id'];?>
<form name="form">
<input type="text" id="get_value_id" name="get_value" value="<?php echo $id ?>">
</input>
</form>
<div id="op_comp_id"></div>
</body>
</html>
This was my attempt to pass a variable value from javascript to bh.php in post mode.
bh.php?id=value
Is there an alternative way or better way to do this?
Use following method to pass a JavaScript variable to php with a post:
$(input[name=get_value]).bind('keyup click blur focus change paste',function(){
var id = $(this).val();
$.ajax({
type: "POST",
url: "bh.php",
async: false,
data: "clientId="+id ,
success:function(response){
$('#op_comp_id').html(response).show();
}
});
}
bh.php use following code
<?php
$id = $_REQUEST['clientId'];
// your code
?>
You can also use hidden Inputfields with javascript. The javascript gets the value via getElementbyId and replace it with the value of a hidden input (also with getElementbyId). Then javascript automaticly submit the form with the hidden input in it (document.forms["formID"].submit();). Thats it. The Value will be send via the form method. So you can send it via post very easy.