Update PHP Variable after Ajax call - php

I am making an Ajax call to a PHP file that checks a condition and runs a query a MySQL query if the conditions are met.
The query updates a table in my DB with a new value. This all works great. I would like to know how to show the new value in the current page without having to manually reload. Code is Below.
The variable I am updating is $trialExpiry
HTML/PHP
<h4 class="sbText mt-10">Trial End Date: <?php echo date("d/m/Y",
strtotime($trialExpiry)); ?></h4>
<form id='promocode'>
<input type='text' class='sbInput' placeholder='Promo Code' name='promocode'>
<input type='hidden' name='userid' value='<?php echo $userID; ?>'>
<button class='btn sbSubmit'>Submit</button>
</form>
JQUERY
<script>
$(function () {
$('#promocode').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '../model/process-promo-code.php',
data: $('#promocode').serialize(),
success: function () {
$("button.btn").css({
'transition-duration': '1000ms',
'opacity': '0.5'
});
}
});
});
});
</script>
Thanks so much.

You don't want to do the live updating with PHP variables, since those are only refreshed when the page is reloaded. Instead, you want to update an element's value via AJAX. As far as I can tell, you want to update the expiration date. If you don't, just let me know and I can change the code to whatever it's supposed to do.
Here's the "control flow" of this functionality:
(Entry point) User clicks 'Submit', jQuery event handler fires
jQuery AJAX function is called and sends the promo code to a PHP script
In the PHP script, the database is updated with the promo code.
The PHP script returns the new expiry date (I'll assume that it's in the d/m/Y format you wanted)
The callback in the jQuery AJAX function receives the data from the script.
The callback's function body updates the "Expiry" element on the page with the value from the PHP call.
Here's how to put that into HTML / JavaScript:
<h4 class="sbText mt-10" id="expiry_label">
Trial End Date: <?php echo date("d/m/Y",
strtotime($trialExpiry)); // The initial value can be displayed as normal. ?>
</h4>
<form id='promocode'>
<input type='text' class='sbInput' placeholder='Promo Code' name='promocode'>
<input type='hidden' name='userid' value='<?php echo $userID; ?>'>
<button class='btn sbSubmit'>Submit</button>
</form>
<script>
$(function () {
$('#promocode').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '../model/process-promo-code.php',
data: $('#promocode').serialize(),
success: function (result) {
$("button.btn").css({
'transition-duration': '1000ms',
'opacity': '0.5'
});
document.getElementById("expiry_label").innerHTML = "Trial End Date: " + result;
}
});
});
});
</script>
As you can see, I only added an "id" attribute to the element, a parameter to the "success" property of the AJAX call, and a line of code to update the element.
Hope I helped!

You need to add a callback -- IE
<script>
$(function () {
$('#promocode').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '../model/process-promo-code.php',
data: $('#promocode').serialize(),
success: function (data) { //<---- CALLBACK
alert(data); // data contains the return from the ajax call
$("button.btn").css({
'transition-duration': '1000ms',
'opacity': '0.5'
});
}
});
});
});
</script>

Only change the success function like below
success: function (data) { //<---- CALLBACK
$('input["name='userid' "]').val(data); // data contains the return from the ajax call
$("button.btn").css({
'transition-duration': '1000ms',
'opacity': '0.5'

Related

Onclick in a XHR response with jquery

I have a form loaded from AJAX. On this form there is a input type button which i would like to manage like it
$("#button_id").on("click",function(){..});
but it's does not work...
My question is how to do this work?
Javascript/Jquery load form code
function openForm('commandForm')
{
$.ajax({
type: "POST",
url: "./forms/commandForm.php",
data: $('#'+frm).
dataType: "html",
beforeSend: function(msg){
$('#ResponseDiv').html('Loding....');
},
success: function(back_data){
$('#ResponseDiv').html(back_data);
}
});
}
commandForm.php
<form id="commandForm" action="postCommand.php" method="post" >
.....
....
<button type="Button" id="postButton" />
</form>
Jquery on postButton onclick
$(document).ready(function () {
$('#postButton').on("click", function (e) {
/*....*/
}); //This don't work
}
PS: I don't want submit the form directly! Just make my own checkform running in my javascript function...out of here. So i want only that the button react on the Onclick ...so to do an alert for example or any javacript function else
Solved my problem with jquery event delagation
More infos here.
Event binding on dynamically created elements?
Now i understood.
This will help you-
$(document).ready(function () {
$("#id").click(function (e) {
//.........
}); //This will work
}

AJAX / PHP error handling and global variable

this is my first time writing an ajax below is my structure
submitted.php
<?php $a = $_POST['a']; // an input submitted from index.php ?>
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php
<?php echo $a; // will this work? ?>
ajax return blank... no error, my error_reporting is on.
No, there are a few things wrong with this:
You are posting a key - value pair where the key is key, so you would need $_POST['key'] in your php script;
You should use .preventDefault() if you need to prevent an event like a form submit that is caused by your button. If that is the case, you need to get the event variable from your event handler: $('button').on('click', function(event) {.If there is no event to prevent, you can simply remove that line;
If you do have a form (it seems so from your comment), you can easily send all key - value pairs using: data: $('form').serialize().
form.php
<button>bind to jquery ajax</button> <!-- ajax trigger -->
<span></span> <!-- return ajax result here -->
<script>
// NOTE: added event into function argument
$('button').on('click', function(event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function(msg) {
$('span').html(msg);
});
});
</script>
process.php
<?php
echo (isset($_POST['key'])) ? $_POST['key'] : 'No data provided.';
?>
This is the way to do it:
ubmitted.php
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
// no need to prevent default here (there's no default)
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php
<?php
if (isset($_POST['key'])
echo $_POST['key'];
else echo 'no data was sent.';
?>

javascript wont read .post php submit input (in php)

Javascript part...
It stops at the $("#deletar").click...
$(document).ready(function() {
$("#deletar").click(function() { // it fails here !!
var sendu = $("#ids").val();
$.ajax({
type : "POST",
url : "deletar.php",
data : "ids=" + sendu,
success : function(msg, string, jqXHR) {
$("#result").html(msg);
}
});
});
});
This is the php file... is a echo to other ajax post, and retrieves a list of a mysql db
.$row2['amigos']."
</td>
<td><inp ``ut type='submit' name='deletar' id='deletar' value='deletar'
OnClick='return confirm(\"Tem certeza que quer deletar esta linha?\");'>
<input type='hidden' name='ids' id='ids' value='".$row2['id']."'>
</td>
</tr>
";
enter code here
Your ajax is being called from a submit button click. You haven't done anything to prevent the default behaviour of the submit button, therefore after your ajax call, the browser will submit the form using a traditional request.
In your click event, you can return false to prevent the form submitting:
$("#deletar").click(function(){ //it fails here !!
var sendu = $("#ids").val();
$.ajax({
type:"POST",
url:"deletar.php",
data: "ids="+sendu,
success: function(msg,string,jqXHR){
$("#result").html(msg);
}
});
return false; // <--- stop the form submitting
});
You can also use e.preventDefault to achieve the same result.
I think you need to stop the form submitting after the submit button has been clicked:
$(document).ready(function () {
$("#deletar").click(function (event) {//it fails here !!
event.preventDefault(); // one of these
event.stopPropagation(); // lines should do the trick
var sendu = $("#ids").val();
$.ajax({
type : "POST",
url : "deletar.php",
data : "ids=" + sendu,
success : function (msg, string, jqXHR) {
$("#result").html(msg);
}
});
});
});

Submitting form with jQuery

Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.

AJAX form submission and results

Just started using AJAX today via JQuery and I am getting nowhere. As an example I have set up a job for it to do. Submit a form and then display the results. Obviously I haven't got it right.
The HTML.
<form id="PST_DT" name="PST_DT" method="post">
<input name="product_title_1682" id="product_title_1682" type="hidden" value="PADI Open Water">
<input name="product_title_1683" id="product_title_1683" type="hidden" value="PADI Advanced Open Water">
<input type="submit" name="submit" id="submit" value="Continue" onclick="product_analysis_global(); test();"/>
</form>
<span id="results"></span>
There are actually many more fields all loaded in dynamically. I plan to use ajax to submit to PHP for some simple maths and then return the results but we can worry about that later.
The JQuery
function test() {
//Get the data from all the fields
var alpha = $('#product_title_1682').val();
JQuery.ajax({
type: 'POST',
url: 'http://www.divethegap.com/update/functions/totals.php',
data: 'text=' + alpha,
beforeSend: function () {
$('#results').html('processing');
},
error: function () {
$('#results').html('failure');
},
timeout: 3000,
});
};
and the PHP
<?php
$alpha = $_POST['alpha'];
echo 'Marvellous',$alpha;
?>
That's my attempt and nothing happens. Any ideas?
Marvellous.
First of all, you're passing the $_POST variable as 'text' while your script is looking for $_POST['alpha']. If you update your PHP to $_POST['text'], you should see the proper text.
Also, if your form is going to have lots of inputs and you want to be sure to pass all of them to your AJAX Request, I'd recommend using jQuery's serialize() method.
data: $('#PST_DT').serialize(), // this will build query string based off the <form>
// eg: product_title_1682=PADI+Open+Water&product_title_1683=PADI+Advanced+Open+Water
In your PHP script you'd then need to use $_POST['product_title_1682'] and $_POST['product_title_1683'].
UPDATE Add a success callback to your $.ajax call.
function test() {
// serialize form data
var data= $('#PST_DT').serialize();
// ajax request
$.ajax({
type : 'POST',
url : 'http://www.divethegap.com/update/functions/totals.php',
data : data,
beforeSend : function() {
$('#results').html('processing');
},
error : function() {
$('#results').html('failure');
},
// success callback
success : function (response) {
$('#results').html(response);
},
timeout : 3000,
});
};
In your PHP script you can debug the information sent using:
var_dump($_POST);
In your AJAX request, you are sending the parameter foo.php?text=..., but in the PHP file, you're calling $_POST['alpha'], which looks for foo.php?alpha=....
Change $_POST['alpha'] to $_POST['text'] and see if that works.
There is a simpler method:
$("#PST_DT").submit(function(e){
e.preventDefault();
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'http://www.divethegap.com/update/functions/totals.php',
success: function(){
....do stuff.
}
});
return false;
});
This will allow you to process the variables like normal.

Categories