Variable not posted on keyup - javascript

The input's value should go to PHP for validation dynamically on every keystroke. JS:
$("#coupon-code").on('keyup', function () {
var coupon = $("#coupon-code").val();
$.ajax({
url:"C:/xampp/htdocs/lessdoing/lessdoinglive.com/checkout/page-2/full-pay/coupons/coupons.php",
type: "POST",
data: {coupon: coupon}
}).done(function (data) {
if (data === "success") {
$('#coupon-code').css("background-color", "green");
}
else {
$('#coupon-code').css("background-color", "red");
}
})
});
PHP:
$coupons = array("foobar", "coupon");
foreach($coupons as $coupon) {
if ($_POST["coupon"] === $coupon) {
echo "success";
} else {
echo 'invalid';
}
}
I don't see the script echoing out anything in the console. The variable insn't posted.

1. The URL
url:"C:/xampp/htdocs/lessdoing/lessdoinglive.com/checkout/page-2/full-pay/coupons/coupons.php"
its not really an URL that is processed by your web server. File is opened from filesystem by your browser and does nothing, as its not pushed via php preprocessor. It must be an proper URI, let say, if you can visit you site with http://127.0.0.1/lessdoing/checkout/page-2/full-pay/coupons/coupons.php, your URL should be /lessdoing/checkout/page-2/full-pay/coupons/coupons.php. Full representation should work too, but is not necessary.
2. There will be no echo in console
as of PHP part of script is running on server-side, there will be no echo in browser console. To echo anything in your browser you will have to implement that in your .done() callback in your JS, eg:
.done(function (data) {
console.log(data);
if (data === "success") {
$('#coupon-code').css("background-color", "green");
}
else {
$('#coupon-code').css("background-color", "red");
}
})
3. Posting POST
Your JS script is not currently sending form format that PHP recognises and pust to $_POST array. This fix is quick, you need dataType: 'html'.
$.ajax({
url:"/lessdoing/lessdoinglive.com/checkout/page-2/full-pay/coupons/coupons.php",
type: "POST",
dataType: 'html',
data: {coupon: coupon}
})
4. PHP upgrade
if(in_array($_POST["coupon"], $coupons)) echo "success";
else echo "invalid";
As in other answer, hardly, but MAY be a situation, when you put coupon twice in your $coupons array and produce "successsuccess" instead of "success".

url:"C:/xampp/htdocs/lessdoing/lessdoinglive.com/checkout/page-2/full-pay/coupons/coupons.php",
This line must be url. You wrote server file path.
.done(function (data) {
alert(data);
if (data === "success") {
$('#coupon-code').css("background-color", "green");
}
else {
$('#coupon-code').css("background-color", "red");
}
})
If you add alert function, you can see data variable value.
$coupons = array("foobar", "coupon");
foreach($coupons as $coupon) {
if ($_POST["coupon"] === $coupon) {
echo "success";
break;
} else {
echo 'invalid';
}
}
And
If you add break in success area, performance upgraded. Or you can use in_array function.
$coupons = array("foobar", "coupon");
if (in_array($_POST["coupon"], $coupons)) {
echo "success";
} else {
echo "invalid";
}

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Getting 500 error on simple form POST via AJAX -- not sure what's wrong?

I don't understand why I'm getting a 500 error on this simple AJAX-based form POST to PHP.... Mind taking a look? It's probably something simple I'm just not catching but I'm scratching my head right now.
JS:
$form.submit(function(e) {
e.preventDefault();
var formData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: formData
}).done(function(res) {
console.dir(res);
alert('success!'); // update status text
$form[0].reset(); // reset the form
$form.find('input[type="submit"]').attr('disabled', 'disabled');
}).fail(function(data) {
alert('error');
});
});
PHP:
if($_SERVER["REQUEST_METHOD"] == "POST") {
if( !empty($_POST['captcha']) ) {
processForm( $_POST['formName'] );
} else {
http_response_code(401);
echo "Unauthorized.";
}
} else {
// not valid. ignore
http_response_code(400);
echo "Bad Request.";
}
PHP: processForm():
function processForm(string $type) {
if ($type == 'contact') {
http_response_code(200);
echo "contact form";
}
if ($type == 'appointmentRequest') {
http_response_code(200);
echo "appointment form";
}
// send the email
// return confirmation / failure
// die
}
I'm just getting a 500 error. I am sure the request is pointing to the right location.
Sorry but as you can read in PHP 5 documentation:
Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.
Since string is not a class, you can't "type-hint" it in your function therefore getting the error.
You can check if it's a string using other methods like filter_input

Submit textarea using javascript

In fact im working on a small php script ! I have recently added some feature anyway i still have an issue which is :
In html file i have put textarea and an submit input I want that when the user click on it the infos of textarea will be sent to a php file without refreshing the page !
Thank you.
Then you should have a look at ajax:
http://api.jquery.com/jquery.ajax/
$("#mysubmitbutton").click(function() {
$.ajax({
url: "mywebsite.com/save-comment.php",
type: "post",
data: {commentText: $("#comment").val()},
success: function(text) {
if(text == "true") {
alert("It worked! Your data were saved hurrayyy!");
}
},
error: function() {
alert("Print some error here!");
}
});
});
On serverside accept your data:
$myText = $_POST["commentText"];
$query = "UPDATE comment SET text = '" . mysql_real_escape_string($myText) . "'";
if(mysql_query($query) == true) {
echo "true";
} else {
echo "false";
}
die();

PHP/ Ajax/ jQuery - Equivalent for my code

I have the following code and would like to use jquery to make it simpler:
var auctionBidAjax;
function auctionBid(auction_id) {
auctionBidAjax=GetXmlHttpObject();
if (auctionBidAjax==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="/cms/ajax/auctionBid.php?auction_id="+auction_id;
auctionBidAjax.onreadystatechange=function() { auctionBidReady(auction_id); };
auctionBidAjax.open("GET",url,true);
auctionBidAjax.send(null);
}
And...
function auctionBidReady(auction_id) {
if (auctionBidAjax.readyState==4) {
if (auctionBidAjax.responseText == "Bid Placed") {
document.getElementById('auctionBid' + auction_id).innerHTML=
"Place Bid";
userBids();
} else if (auctionBidAjax.responseText == "Not Logged In") {
popupCentre('popupLogin');
popupLoad('popupLogin');
} else if (auctionBidAjax.responseText == "No Bids"){
popupCentre('popupNoBids');
popupLoad('popupNoBids');
}
}
}
My PHP script adds a bid etc and echos the responseText.
You've tagged this question as jquery so you can use $.ajax():
function auctionBid(auction_id) {
$.ajax({
url: "/cms/ajax/auctionBid.php",
type: "GET",
data: {
auction_id: auction_id
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// act appropriately
},
success: function(data, textStatus) {
// do whatever
}
});
}
If you didn't need an error handler you could use the simpler form of $.get() instead:
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.get(url, { auction_id: auction_id }, function(data, textStatus) {
// do whatever
});
}
I actually prefer not to use error handlers. It's a little uglier than it needs to be. Use that for actual errors. Things like "not logged in" could be handled by the success handler. Just pass back a JSON object that contains the required information to tell the user what happened.
For this you could use the $.getJSON() shorthand version.
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.getJSON(url, { auction_id: auction_id }, function(data) {
if (data.notLoggedIn) {
alert("Not logged in");
}
...
});
}
To return some information as JSON from PHP use json_encode() and set the MIME type appropriately:
<?php
session_start();
header('Content-Type: application/json');
echo json_encode(array(
'highBid' => get_new_high_bid(),
'loggedIn' => $_SESSION['loggedIn'],
));
exit;
?>
I'm making assumptions about your login system so the above is a gross simplification.
Return that to a $.getJSON() callback and you should be able to do:
alert(data.highBid);
alert(data.loggedIn);
JQuery.get is what you need
http://docs.jquery.com/Ajax/jQuery.get

Categories

Resources