PHP AJAX Postback with JQUERY - php

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;

Related

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>

why i cannot pass json data to another PHP file?

i have two php files home.php and ajax.php. i have two buttons on home.php. when they are clicked the according php functions in ajax.php should get called.
home.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
</html>
ajax.php
<?php
echo 'this was called';
echo $_POST['action']; //THROWS AN ERROR undefined index 'action'
if ( isset( $_POST['action'] ) ) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
the problem is the json data i assign to data property in jquery code will not get passed to the ajax.php. Is there any reason why it doesn't not pass it?
here is my youtube video on the error video
There are two possibilities, depending of what you want to achieve afterwards.
Eighter you stick on doing a backgroud ajax-call to ajax.php and then do with the response whatever you want (that's what I'd suggest):
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).id(); // changed to id here!
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
console.log(response); // log what the response is
alert("action performed successfully and the resonse is: \n"+response);
// do with that data whatever you need
});
});
});
</script>
</head>
<body>
<!-- changed to buttons, removed the form -->
<button class="button" id="insert">insert</button>
<button class="button" id="select">select</button>
</body>
</html>
or you submit the form and output on screen the response from ajax.php:
<html>
<head>
<!--script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script-->
<script type='text/javascript'>
// no need for any javascript then
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
and in ajax.php:
<?php
echo 'this was called';
if ( isset( $_POST['insert'] ) ) {
insert();
}
if ( isset( $_POST['select'] ) ) {
select();
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
try
$.post(ajaxurl, data)
.done(function( r ) {
alert("action performed successfully");
});
I like to use the jQuery on() and to be sure post has worked, I moved in your variables as such. Also you can try to do console.log(clickBtnValue) after the click to be sure you are able to see the value itself. After confirming, the post() should send that value into action post param.
<script type='text/javascript'>
$(document).ready(function(){
$('.button').on('click',function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
$.post(ajaxurl, {action:clickBtnValue}, function (response) {
alert("action performed successfully");
});
});
});
</script>
If you need to do a ajax call, remove the following part from the home.php
<form action='ajax.php' method="POST">
</form>
I think you are messed up with Ajax technology and the form post mechanism.

use jQuery to send javascript array to php

I'm trying to pass javascript array to php using ajax and jQuery.
I have simple page that contains a series of numbers that I've made selectable via jQuery UI (see below) When I select a group of numbers, I use array.push to add those numbers to an array called "shift". Here's the question: What's the simplest way to send this array to PHP? Will it remain an array after it comes over? I'm new to coding and would appreciate any help I can get. After a lot of research, here's what I've tried. Oh, I've managed to figure out how to submit the form to PHP, it's the jQuery UI array that i'm stuck on.
here's my main.php
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class = "container">
<form action="post.php" method="post" id="add">
<input type="text" class="leader" name="name" placeholder="Leader">
<input type="text" class="date" name="date" placeholder="date">
<input type="text" class="time" name="time" placeholder="time">
<input type="text" class="score" name="score" placeholder="score">
<input type="submit" id="btn" value="send" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.4.custom.js"></script>
<script src="globe.js"></script>
<ul id ="hours_zoned">
<li class="nine">9</li>
<li class="ten">10</li>
<li class="eleven">11</li>
<li class="twelve">12</li>
<li class="one">1</li>
<li class="two">2</li>
<li class="three">3</li>
<li class="four">4</li>
<li class="five">5</li>
<li class="six">6</li>
<li class="seven">7</li>
<li class="eight">8</li>
<li class="nine">9</li>
</ul>
</div>
</body>
</html>
here's my post.php
<html>
<body>
/* I'm using all of these echoes to verify that the data is coming
over. Only "shift" fails to come over */
NAME <?php echo $_POST["name"]; ?><br>
DATE <?php echo $_POST["date"]; ?><br>
TIME <?php echo $_POST["time"]; ?><br>
SCORE: <?php echo $_POST["score"]; ?><br>
SHIFT: <?php echo $_POST["shift"]; ?>
<?php
include("db.php");
$name = $_POST["name"];
$date = $_POST["date"];
$time = $_POST["time"];
$query = "INSERT INTO leaders (name, shift_date, shift_time) VALUES ('$name', '$date', '$time')";
$result = $db->query($query);
?>
</body>
</html>
here is my globe.js
var shift = []; //create array to store zoned hours
$(function() {
$( "#hours_zoned" ).selectable();
$( "#hours_zoned" ).on('click', 'li', function() {
$(this).addClass("clicked ui-selected");
$( this ).css( "background-color", "#e74c3c" );
$( this ).selectable({ disabled: true });
var floorTime = $(this).text(); // get the value of the hour that was clicked
shift.push(floorTime); // add that hour to the floorTime
});
/*$('#add').on('submit', function() {
var name = $('.leader').val(); */
$('#btn').on('submit', function() {
$.ajax({
type: 'POST',
url: 'post.php',
data: shift,
success: function(msg) {
alert(msg);
}
});
});
return false;
});
You are only sending the key
data: shift,
according to the docs - Object must be Key/Value pairs. (https://api.jquery.com/jQuery.ajax/)
try
data: {shift: shift},
so it is now
$('#btn').on('submit', function() {
$.ajax({
type: 'POST',
url: 'post.php',
data: {shift: shift},
success: function(msg) {
alert(msg);
}
});
return false;
});
EDIT: Your ajax function was a bit jacked up. Fixed that for you also. See new code.
Your ajax submit isn't running. Add return false; to prevent the main form from submitting. I'm thinking the easiest way to add the array would be to insert it into a hidden input immediately after being pushed in your jQuery function. Then you would just serialize the form data and send it all in your ajax function. See below:
New form:
<form action="post.php" method="post" id="add">
<input type="text" class="leader" name="name" placeholder="Leader">
<input type="text" class="date" name="date" placeholder="date">
<input type="text" class="time" name="time" placeholder="time">
<input type="text" class="score" name="score" placeholder="score">
<input type="hidden" class="shift" name="shift">
<input type="submit" id="btn" value="send" />
</form>
New function:
var shift = []; //create array to store zoned hours
$(function() {
$( "#hours_zoned" ).selectable();
$( "#hours_zoned" ).on('click', 'li', function() {
$(this).addClass("clicked ui-selected");
$( this ).css( "background-color", "#e74c3c" );
$( this ).selectable({ disabled: true });
var floorTime = $(this).text(); // get the value of the hour that was clicked
shift.push(floorTime); // add that hour to the floorTime
$("#add .shift").val(shift); // add shift array to hidden input in form
});
/*$('#add').on('submit', function() {
var name = $('.leader').val(); */
$('#add').submit(function() {
$.ajax({
type: 'POST',
url: 'post.php',
data: $("#add").serialize(),
success: function(msg) {
alert(msg);
}
});
return false; // you need this to prevent the other form submission
});
return false;
});
Untested, but that should get you going in the right direction.
Just wanna add to the answers given here..
You also need to check if the items selected are in array already (prevent duplicate).. so to do that you can do it like this
*code is taken from Matt answer
if($.inArray(floorTime, shift) === -1) {
shift.push(floorTime);
$("#add .shift").val(shift);
}
Try parse_str().
$array = parse_str( $_POST['data'] );

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>

Submit form (jquery) and show results in colorbox

I have a form that I wish to submit which is posting to a php script to deal with the form data.
What I need to do is after hitting submit have a colorbox popup with the php results in it.
Can this be done?
This is what i've been trying:
$("#buildForm").click(function () { // #buildForm is button ID
var data = $('#test-buildForm'); // #test-buildForm is form ID
$("#buildForm").colorbox({
href:"build_action.php",
iframe:true,
innerWidth:640,
innerHeight:360,
data: data
});
return false;
});
UPDATE: This would need to be returned in an iframe as the
build_action.php has specific included css and js for those results.
This is simple, untested code but it'll give you a good jumping off point so you can elaborate however much you please:
<form action="/path/to/script.php" id="formID" method="post">
<!-- form stuff goes here -->
<input type="submit" name="do" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({html:data});
},
'html');
return false;
});
});
</script>
this article will help you with the problem
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
You will need to see the exact way to use your colorbox jQuery plugin. But here is a basic (untested) code example that I've just written to hopefully get you on your way.
If you wish to submit a form using jQuery, assuming you have the following form and div to hold dialog data:
<form id="myForm">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit" name="formSubmit" />
</form>
<div style="display: hidden" id="dialogData"></div>
You can have a PHP code (doAddition.php), which might do the addition of the two numbers
<?php
// Do the addition
$addition = $_POST['num1'] + $_POST['num2'];
$result = array("result" => $addition);
// Output as json
echo json_encode($result);
?>
You can use jQuery to detect the submitting of the code, then send the data to the PHP page and get the result back as JSON:
$('form#myForm').submit( function() {
// Form has been submitted, send data from form and get result
// Get data from form
var formData = $('form#myForm').serialize();
$.getJSON( 'doAddition.php', formData, function(resultJSON) {
// Put the result inside the dialog case
$("#dialogData").html(resultJSON.result);
// Show the dialog
$("#dialogData").dialog();
});
});
This is how I ended up getting it to work:
<div id="formwrapper">
<form method="post" action="http://wherever" target="response">
# form stuff
</form>
<iframe id="response" name="response" style="display: none;"></iframe>
</div>
<script>
function hideresponseiframe() {
$('#formwrapper #response').hide();
}
$('form').submit(
function (event) {
$('#formwrapper #response').show();
$.colorbox(
{
inline: true,
href: "#response",
open: true,
onComplete: function() {
hideresponseiframe()
},
onClosed: function() {
hideresponseiframe()
}
}
);
return true;
}
);
</script>

Categories