$.post with serialize doesn't send post variables and values - php

I want to post data with jquery to process.php, and return everything what happens in the process.php file.
I already managed to load the file with ajax. if I type
echo "Hello world!";
it does return Hello world! but it does not return the echoes where I use $_POST.
The form
<form class="calc" method="POST" action="process.php">
<input id="calc-average" type="text" name="calc-average" placeholder="Goal"/>
<input id="calc-weight" type="text" name="calc-weight" placeholder="Weight"/>
<input id="calc-calculate" type="hidden" name="calc-calculate" value="1" />
<input type="submit" class="btn btn-primary calc-submit" value="Calculate">
</form>
The script
$(".calc").submit(function(event) {
event.preventDefault();
$.post( 'process.php', $(".calc").serialize(),
function( data ) {
$(".result").append(data);
}
);
});
Process.php
if(isset($_POST["calc-calculate"])&&isset($_POST["calc-weight"])&&isset($_POST["calc-average"])){
if(!$_POST["calc-calculate"]==""&&!$_POST["calc-weight"]==""&&!$_POST["calc-average"]==""){
if($_POST["calc-calculate"]==$subjectid){
$a = $_POST["calc-weight"];
$y = $_POST["calc-average"];
$q = $weights;
$z = $average;
$tobe = (-($a*$y+$q*$y-$q*$z)/$a)*-1;
if($tobe>10 or $tobe<0){
echo " | Not possible yet";
}else{
echo " | The grade you need is: " . round($tobe,1);
}
}
}
}
echo "Hello wordl!";
If I remove the if statements it returns that they are unidentified.
So does anyone know how I can get this to work?
Thanks!

hi can you please try this in your jquery code
$(".calc").submit(function(event) {
event.preventDefault();
$.post( 'process.php', $(".calc :input").serialize(),
function( data ) {
$(".result").append(data);
}
);
});

This code is working fine for me.
try adding return false after post request.
$(".calc").submit(function(event) {
event.preventDefault();
$.post( 'process.php', $(".calc").serialize(),
function( data ) {
$(".result").append(data);
}
);
return false;
});

I already had the same problem. My code had a duplicate "id" on the page. That was my issue.
Please, make sure you have an exclusive id or class "calc" in the form to "serialize" command call the correct element.

Related

Submit form checkbox value without page refresh Ajax php

Still learning ajax.
Now i go stuck at this point.
Am trying to get the value of the checkbox on my form.
Below is my HTML code
<form method="post">
<input type="text" name="mytext" id="text">
<br>
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<input type="submit" id="form4" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax Script
$(document).ready(function() {
$("#form4").click(function(event) {
var action = 'another_test';
var text = $("#text").val();
var agreed = $("#agreed").val();
event.preventDefault();
$.ajax({
type: "POST",
url: "test3.php",
data: {
mytext:text,
test:agreed,
action:action
},
success: function (response)
{
$(".form-message").html(response);
}
});
});
});
Then this is my PHP code below which is on a different page
<?php
if (isset($_POST['action']))
{
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$mytext = $_POST["mytext"];
$errorEmpty = false;
if (empty($mytext)) {
echo "<p>enter your text</p>";
$errorEmpty = true;
}
elseif (empty($test)) {
echo "<p>Click the checkbox</p>";
$errorEmpty = true;
}
else {
echo "<p>Correct</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
It works for text, textarea input but not for checkbox. I know am wrong. Am still learning though.
Please help me. Thanks in advance.
Using $("#agreed").val() you only receive the value you setted in the "value" attribute on your input checkbox tag. To get a boolean value of checkbox's state you have to do use .is() function
$("#agreed").is(":checked");

Ajax won't post form data to PHP script

I got a form with some data that needs to be sent and I want to do it with ajax. I got a function that respond on an onclick event of a button. When I click the button I got some post data in firebug but it just doesn't reach my PHP script. Does anyone know what's wrong?
JS:
function newItem() {
var dataSet = $("#createItem :input").serialize();
confirm(dataSet); //Below this code box is the output of this variable to check whether it is filled or not
var request = $.ajax({
type: "POST",
url: "/earnings.php",
data: dataSet,
dataType: "json"
});
request.done(function(){
$('.create_item').children(".row").slideUp('100', 'swing');
$('.create_item').children("h2").slideUp('100', 'swing');
confirm("succes");
});
request.fail(function(jqXHR, textStatus) {
confirm( "Request failed:" + textStatus );
});
}
dataSet result when the form is completly filled in:
id=123&date=13-09-2013&amount=5&total=6%2C05&customer=HP&invoicenumber=0232159&quarter=1&description=Test
The PHP:
<?php
include('includes/dbconn.php');
function clean_up($string){
$html = htmlspecialchars($string);
$string = mysql_real_escape_string($html);
return $string;
}
if($_POST){
$date = clean_up($_POST['date']);
$amount = clean_up($_POST['amount']);
$total = clean_up($_POST['total']);
$customer = clean_up($_POST['customer']);
$invoicenumber = clean_up($_POST['invoicenumber']);
$quarter = clean_up($_POST['quarter']);
$description = clean_up($_POST['description']);
$sql = ("INSERT INTO earnings (e_date, e_amount, e_total, e_customer, e_invoicenumber, e_quarter, e_description)
VALUES ($date, '$amount', '$total', '$customer', $invoicenumber, $quarter, '$description')");
echo $sql;
if($mysqli->query($sql) === true){
echo("Successfully added");
}else{
echo "<br /> \n" . $mysqli->error;
}
}
?>
The form works fine without the ajax but with it it just doesn't work.
Your help is appreciated!
Try this snippet code bro...
<form id="F_login">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: '/earnings.php',
data: parm,
success: function (data,status,xhr) {
console.info("sukses");
},
error: function (error) {
console.info("Error post : "+error);
}
});
});
Reply me if you try this...
prevent your form submitting and use ajax like this:
<form id="createItem">
<input id="foo"/>
<input id="bar"/>
<input type="submit" value="New Item"/>
</form>
$('#createItem).on("submit",function(e){
e.preventDefault;
newItem();
});
Try this
<input type="text" id="foo"/>
<input type="text" id="bar"/>
<input type="button" id="btnSubmit" value="New Item"/>
<script type="text/javascript">
$(function() {
$("#btnSubmit").click(function(){
try
{
$.post("my php page address",
{
'foo':$("#foo").val().trim(),
'bar':$("#bar").val().trim()
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>

PHP AJAX Postback with JQUERY

me again, i'm really getting into php now i just need to know a few things first. First of all i'm trying to do a postback to a the server without reloading the client page. Here's an example of what i want to do: I have to textboxe, now when the user enters a number into both textboxes and clicks the add button, the total value should be calculated and displayed in the third textbox without reloading the page, i've read a bit on ajax but i'm having trouble implementing it.
<?php
if (isset($_POST["add"]))
{
$val1 = $_POST["val1"];
$val2 = $_POST["val2"];
$result = $val1 + $val2;
}
?>
<html>
<head>
<title></title>
<script src="jquery-1.9.1.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
if ($("#btn").click)
{
var request = $.ajax({
url: "postback.php",
type: "POST",
data: {
val1 : "what goes here?",
val2 : "what goes here?"
}
});
request.done(function(msg) {
$("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
});
</script>
</head>
<body>
<input type="input" name="val1">
<input type="input" name="val2">
<input type="input" name="result" value="<?php echo $result ?>">
<input type="submit" id="btn" name="add">
</body>
</html>
Don't mix your JavaScript and your PHP logic. Separate them.
You need your jQuery POSTing to another file, and in this file, echo out the result of your PHP.
This result will then be placed in the .done() method (although I would use .success(), and you use jQuery / JavaScript to update the contents of your HTML).
By the end of this you should have no PHP whatsoever in your HTML / JS file.
Your PHP Code in test.php
From this, we can see you need to post a val1 and a val2 through, so here is a really basic script.
if (isset($_POST))
{
$val1 = isset($_POST["val1"]) ? $_POST["val1"] : 'No value 1 passed through';
$val2 = isset($_POST["val2"]) ? $_POST["val2"] : 'No value 2 passed through';
if (is_int($val1) && is_int($val2))
{
// They're integers, add them
$result = $val1 + $val2;
}
else
{
// They're strings, append them
$result = $val1 . $val2;
}
echo $result;
}
That is all you need in your PHP.
Your HTML / JS
$(document.ready(function() {
$("#add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: {
'val1' : $("#val1").val(),
'val2' : $("#val2").val()
},
success: function(data, status) {
$("#result").html(data)
}
});
});
});
<div id="result">Result should appear here</div>
<form>
<input type="text" id="val1" name="val2" />
<input type="text" id="val2" name="val2" />
<input type="submit" id="add" name="add" />
</form>
And that's it. Pretty simple. Note, untested, so give it a try.
If you don't want to separate your JS and PHP follow this:
1. You should set your input type as button <input type="button" id="btn" name="add">
2. You should also post add in your ajax call
3. You should get the values from textboxs $('#val1').val()
4. You should stop the code after echoing two values because if you don't, ajax returns the rest of html codes and page contents.
5. And at last you should add the new value to the third input by JavaScript, not php because it's ajax and the page is not going to reload.
Try this:
<?php
if(isset($_POST["add"])){
$val1 = $_POST["val1"];
$val2 = $_POST["val2"];
$result = $val1+$val2;
echo $result;
die();
}
?>
<html>
<head>
<title></title>
<script src="jquery-1.9.1.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function(){
var request = $.ajax({
url: "postback.php",
type: "POST",
data: {
val1 : $('#val1').val(),
val2 : $('#val2').val(),
add : "ok"
}
});
request.done(function(msg) {
console.log(msg);
$("#result").val( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
</head>
<body>
<input type="input" id="val1">
<input type="input" id="val2">
<input type="input" id="result" value="">
<input type="button" id="btn" name="add">
</body>
</html>
You need to return the result of
$result = $val1 + $val2;
use
echo $result;
exit;

JQuery issue on Ipad

I have a popup form on which a user provides a key to get access to the site. I validate the user provided key with Jquery. It is working fine on my local system but when I submit the form using ipad it does not work. The form is even nor submitted.
My Form is
<form name="form" method="post">
<div style="width:530px;">
<input style="display:none; height:25px;" id="downloadkey" name="downloadkey" type="text" />
<input style="display:none;" type="submit" id="submit" name="submit" value="<?php echo $variable['QUESTION_BUTTON']['value'] ?>"/>
</div>
<input type="hidden" id ="box_id" value="<?php echo $box_id ?>" />
</form>
JQuery is
$(document).ready(function() {
$('#submit').click(function(e) {
var key = $('#downloadkey').val();
var box_id = $('#box_id').val();
var dataString = {KEY:key, BID:box_id};
$.ajax({
url: "/home/validate_key",
type: 'POST',
data: dataString,
success: function(msg) {
if(msg=="false"){
alert("Your download key is either wrong or missing");
}
else{
$('#popupContact').hide();
$('#backgroundPopup').hide();
}
}
});
e.preventDefault();
});
});
In my controller the validate function is
function validate_key(){
$key = strtolower($this->input->post('KEY'));
$id = $this->input->post('BID');
$query = $this->db->get_where('mc_boxes', array('idmc_boxes' => $id));
$row = $query->row();
$download_key = strtolower($row->downloadkey);
if($download_key == $key){
$_SESSION['download_key'] = $key;
$_SESSION['timeout'] = time();
}
else{
echo 'false';
}
}
Do i need something special to make it working on ipad?
Thanks
jQuery.click() doesn't function properly on iOS.
Try using jQuery.on() or by binding other events like touchstart
.bind("click touch tap", function(){
// code
});
Is what I've seen used when dealing with iPad.
(It's not a CodeIgniter issue for sure.)

Send multiple checkbox data to PHP via jQuery ajax()

I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;

Categories