now i have a text-input and a php variables.
$price = 200;
<input type="text" name="promotion_code">
after users type in value of 'promotion_code' , without submit button , or any links.
it's can match 'promotion_code' between javascript on that pages.
lets say the javascript :
var str="123203";
so i want match the 'promotion_code' with 'var str' .
if match then $price = $price - 10;
if not match then $price value doesn't change ..
any could helps or any methods to solve this ?
note :!! to be told. this form did not have a submit button .. the compare process should be works in time when the user input the promotion_code
You should not do that with JavaScript, it is no secure enough.
Anyone can view your JavaScript code by looking at the source of your page.
Try to make it with an ajax request.
jQuery.ajax({
type : "post",
url : "request.php",
data : "code=" +jQuery("input[name=promotion_code]").val(),
success : function(ret){
jQuery("#price").text(ret);
}
});
Here you call the page request.php with the value code
Here what can be request.php :
$price = 200;
$code = $_POST["code"];
if( $code == "123203" ){
$price -= 10;
}
return $price;
Then you update the price field with the data returned by the request.php page.
You have to adapt that code of course.
I hope this can help.
Make sure to do that on the server since anyone can see the code in the source of the page. Also $price is on the server and the client value is not available to the server until you send a request back to the server using for example AJAX
So something like
<form action="purchase.php" id="form1">
Promotion code: <input type="text" name="promotion_code" id="prCode" />
<input type="button" id="prCodeBut" value="Apply" />
Price: <input type="text" readonly="readonly"
name="finalprice" id="fPrice" value="<?PHP echo $price; ?>" />
</form>
JavaScript
DEMO 1 - using click
var orgPrice = <?PHP echo $price; ?>;
window.onload=function() {
document.getElementById("prCodeBut").onclick=function(){
// hardcoding the promocode is NOT recommended
if (document.getElementById("prCode").value == "<?php echo $promocode; ?>") {
document.getElementById("fPrice").value=orgPrice-10;
}
}
}
DEMO 2 using onkeyup
var orgPrice = <?PHP echo $price; ?>;
window.onload=function() {
document.getElementById("prCode").onkeyup=function(){
// hardcoding the promocode is NOT recommended
if (document.getElementById("prCode").value == "<?php echo $promocode; ?>") {
document.getElementById("fPrice").value=orgPrice-10;
}
}
}
DEMO 3 using onblur
var orgPrice = <?PHP echo $price; ?>;
window.onload=function() {
document.getElementById("prCode").onblur=function(){
// hardcoding the promocode is NOT recommended
if (document.getElementById("prCode").value == "<?php echo $promocode; ?>") {
document.getElementById("fPrice").value=orgPrice-10;
}
}
}
Ajax to hide the promocode
// delay from http://stackoverflow.com/a/1909508/295783
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(function() {
$("#prCodeBut").on("keyup",function() {
delay(function() {
$.get("checkPromo.php",{promotion: $("#prCode").val()},function(data) {
$("#fPrice").val(data);
});
},300);
});
});
Related
So I'm trying to pass a value from my AJAX code to my PHP code which connects to an API to get the weather. It works when just using PHP, but I want ajax to return the results to some div on the same page. My code looks correct when I compare it to other examples but it just doesn't work.
Code may not be written with security in mind, standard practice etc, I'm just trying to play around with API's and get the basics of AJAX.
api.php:
$city = $_POST['city'];
function getCityLat($x) {
$latUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $x .'APIKEY';
$latResponse = file_get_contents($latUrl);
$latArray = json_decode($latResponse, true);
$lat = $latArray['results'][0]['geometry']['location']['lat'];
echo $lat;
return $lat;
}
function getCityLng($y) {
$lngUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $y .'APIKEY';
$lngResponse = file_get_contents($lngUrl);
$lngArray = json_decode($lngResponse, true);
$lng = $lngArray['results'][0]['geometry']['location']['lng'];
echo $lng;
return $lng;
}
function getWeather($x, $y) {
$weatherUrl = 'https://api.darksky.net/forecast/APIKEY/' . $x . ',' . $y;
$weatherResponse = file_get_contents($weatherUrl);
$weatherArray = json_decode($weatherResponse, true);
$timeZone = $weatherArray['timezone'];
$locWeather = $weatherArray['currently']['temperature'];
$locFeelsLike = $weatherArray['currently']['apparentTemperature'];
$windSpeed = $weatherArray['currently']['windSpeed'];
$weatherSummary = $weatherArray['currently']['summary'];
$time = $weatherArray['currently']['time'];
$outputweather = '<p>Temp: '.$locWeather.'</p>';
echo $outputweather;
}
getWeather(getCityLat($city), getCityLng($city));
?>
index.php(html):
<h3 align="center">Weather</h3>
<form align="center" method="POST">
<input type="text" id="city" name="city" placeholder="Enter City">
<button class="btn btn-xs btn-success" name="city_go" id="city_go">Go</button>
</form>
<div id="weather"></div>
JQuery:
function getWeather(city) {
$.ajax({
url: "api.php",
method: "POST",
data: {city:city},
dataType: "text",
success: function(data) {
$('#weather').html(data);
}
});
}
$(document).on('click', '#city_go', function() {
var city = $('#city').val();
getWeather(city);
});
The problem is that you are submitting a form, which forces a page refresh. Everything else is working correctly, just the page is being refreshed. To fix that you need to update your click event to something like
$(document).on('click', '#city_go', function(e) {
e.preventDefault();
var city = $('#city').val();
getWeather(city);
});
the preventDefault() call will cancel the default action of the form (the page refresh) and allow the AJAX call to follow through and display the data.
I'm working on a PHP application i want to submit form without refresh page. Actually, i want my php code to be written on the same page as the one containing html and jquery code.
In order to submit form using jquery i've written this code
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
$.post("php-opt.php", //Required URL of the page on server
{ // Data Sending With Request To Server
selectrefuser:vname,
},
function(response,status){ // Required Callback Function
//alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
});
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
//return false;
//e.preventDefault();
//$("#monbutton:hidden").trigger('click');
});
});
and my php code is :
<?php
$resclient_alt = 1;
$resclient_long = 1;
if(isset($_POST['selectrefuser'])){
$client = $_POST['selectrefuser'];
echo $client;
$client_valide = mysql_real_escape_string($client);
$dbprotect = mysql_connect("localhost", "root", "") ;
$query_alt= "SELECT altitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1_alt=mysql_query($query_alt, $dbprotect);
$row_ss_alt = mysql_fetch_row($query_resclient1_alt);
$resclient_alt = $row_ss_alt[0];
//echo $resclient_alt;
$query_gps= "SELECT longitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1=mysql_query($query_gps, $dbprotect);
$row_ss_ad = mysql_fetch_row($query_resclient1);
$resclient_long = $row_ss_ad[0];
}
?>
My form is as below
<form id="form1" name="form1" method="post" >
<label>
<select name="selectrefuser" id="selectrefuser">
<?php
$array1_refuser = array();
while (list($key,$value) = each($array_facture_client_refuser)) {
$array1_refuser[$key] = $value;
?>
<option value="0" selected="selected"></option>
<option value="<?php echo $value["client"];?>"> <?php echo $value["client"];?></option>
<?php
}
?>
</select>
</label>
<button id="btn">Send Data</button>
</form>
My code does these actions:
select client get its GPS coordinates
recuperates them in php variable
use them as jquery variable
display marquer on map
So since i do this steps for many clients i don't want my page to refresh.
When i add return false or e.preventDefault the marquer is not displayed, when i remove it the page refresh i can get my marquer but i'll lost it when selecting another client.
is there a way to do this ?
EDIT
I've tried using this code, php_query.php is my current page , but the page still refresh.
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Edit
When adding e.preventDfault , this code doesn't seem to work
$( "#monbutton" ).click(function() {
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
$('#myResults').html("je suis "+php_long);
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
});
This code recuperate this value var vname = $("#selectrefuser").val(); get result from sql query and return it to jquery .
It will refresh since you have not prvent default action of <button> in script
$("#btn").click(function(e){ //pass event
e.preventDefault(); //this will prevent from refresh
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Updated
Actually, i want my php code to be written on the same page as the one containing html and jquery code
You can detect the ajax call on php using below snippet
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special code here */
}
I am working on the PHP cart timer script using PHP and jQuery/JavaScript.
I am iterating the set-interval function every seconds to get the PHP's current time-stamp.
When the first product is added to the cart, the timer begins before getting timer-stops it prompts the user, whether the user want to continue or cancel.
My code is follows
$(document).ready(function(){
var orderedtime = "echo $_SESSION['ordertime'];";
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}
else{
init();
}
});
var currenttime;
var alerttime;
var extratime;
function cd(){
alerttime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (1 * 60))); ?>"
extratime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (2 * 60))); ?>";
redo();
}
function redo(){
currenttime = "<?php echo date('h:i:s', time()); ?>";
if(alerttime == currenttime) {
//doing something
}
else if(currenttime == extratime){
//doing something
}
else{
cd = setTimeout("redo()",1000);
}
}
function init(){
cd();
}
The currenttime variable only storing the 1st iteration value is not getting updating.
How to solve this issue?
Please kindly help me to solve it.
Thanks in advance.
You're not actually requesting a time from the server in your setTimeout loop.
This line
currenttime = "<?php echo date('h:i:s', time()); ?>";
is set when the page is first generated and not changed again. If you want the time updated you need to send a request to the server. This probably isn't the best way to do it though.
Further to MikeW's excellent but incomplete answer, you need a way to request the time from the server and receive it back in the DOM.
There is only one way to do that: AJAX.
As Mike pointed out, the PHP code that you typed above only runs once: when the page is first generated. After the page has been generated and the document is "ready", you must use AJAX.
Below is a fully-working, copy/pastable example to demonstrate one way this could work.
Note that I had to over-ride the orderedtime variable because I don't know how/when you set that.
HTML/javascript side: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
//var orderedtime = "<?php echo $_SESSION['ordertime']; ?>";
var orderedtime = '';
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}else{
doAjax();
}
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
PHP side: get_the_time.php
<?php
if (isset($_POST['ordertime']) != true) {
$d = date("h:i:s");
}else{
$ot = $_POST['ordertime'];
$d = date('h:i:s', (strtotime($ot) + (1 * 60)));
}
echo $d;
IMPORTANT NOTE:
When using AJAX, the response sent from the server is received inside the success: function, and no where else.
If you later wish to use that data, assigning it into a variable inside the success function will not work. The best way I have found is to stick the received data into an element of some kind (a hidden input field works great for this), and then retrieve it from there when needed.
For example:
<input type="hidden" id="myHiddenField" />
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
$('#myHiddenField').val(myData);
}
});
Then, inside some other javascript function, you can grab that data and assign it to some variable, thus:
var someVar = $('#myHiddenField').val();
Hope this helps, late as it is.
This stackoverflow post has further information/explanation regarding AJAX. Check out the simplified AJAX examples at the bottom.
I have been looking all over for a way to do this.
I use a PHP while loop to get some variables from a database:
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<script type="text/javascript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
//-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
<? } //end while
?>
Sometimes i get 10 results, and i make 10 Go! bottoms. But when i come to the delete page, the $is variable is off cause the same as the last result, no matter witch of the bottoms i press..
Any ideas on how to get around that, so i get the confirm box, and still keep the right id to be deleted?
You're creating a global function called "go_there" for each entry, so only the last one will remain. Instead of that, create just one function, and fetch the "id" value from an attribute on the button.
function go_there(button)
{
var id= button.getAttribute("data-id");
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
}
Then:
<INPUT TYPE="button" value="Go!" onClick="go_there(this)" data-id="<?php echo $id ?>">
It seems to me like you're creating your javascript function in your loop as well so it only fires one of them (you're creating multiple functions with the same name. How is it supposed to know which one to use). You should create 1 javascript function and pass the id into it as a a parameter
<script type="text/javascript">
function go_there(id)
{
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
</SCRIPT>
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
echo '<td><form><INPUT TYPE="button" value="Go!" onClick="go_there(<?php echo $id; ?>)"></form></td></tr>'
} //end while
?>
Overall this is a poor way to do this. You should avoid wrtiting handlers inline unless you have a specific case where it is the only way. Much better if you attach a handler to the elements in questions (working fiddle - for firefox anyhow...):
<!-- output our inputs with the id value in an attribute data-id-value -->
<?php while ($row = mysql_fetch_array($query)): $id = $row["ID"]; ?>
<td><form><INPUT class="go-button" TYPE="button" value="Go!" data-id-value="<?php echo $id ?>"></form></td></tr>
<?php endwhile; ?>
<script type="text/javascript">
var goButtons = document.querySelectorAll('input.go-button'), // select all out buttons
// define our handler function
goThere = function (event) {
// get the id the we encoded from php from our data attr
var id = event.target.getAttribute('data-id-value');
if(confirm('Are you sure you want to delete?')) {
// if confirm is true then redirect to the delete url
window.location = "index.php?p=delete&id=" + id;
}
};
// loop over the buttons and attach the handler
for (var i = 0; i < goButtons.length; i++) {
goButtons[i].addEventListener('click', goThere);
}
</script>
The issue here is that that isnt necessarily cross browser. Thats typically one of the reasons people use libraries like jQuery or similar so that they don't have to normalize dom querying and listener attachment.
Here is a corrected script.
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<SCRIPT language="JavaScript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to == true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
Your button will not work because you have added the comment markers <!-- and --> to the function. If you want help with that then please comment.
Also, can you clarify you're issue in the comments? We can help you better then.
My goal is to have input field that will take value of whats was typed and echoed through. The js function will grab the value of the input box two seconds after user stops typing and post it. The issue seems to be with the php not echoing the value of the input box. When I take out the js function and use a button that forces refresh then
it works fine. How come php is not taking the value posted by js function?
Example SITE
JS
<script type="text/javascript">
$(document).ready(function() {
var timer;
$('#video-input1').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#ytVideo").submit()
//alert('submitted:' + value);
}, 2000);
});
//then include your submit definition. What you want to do once submit is executed
$('#ytVideo').submit(function(e){
e.preventDefault(); //prevent page refresh
var form = $('#ytVideo').serialize();
//submit.php is the page where you submit your form
$.post('index.php', form, function(data){
});
return false;
});
});
</script>
PHP
<?php
if($_POST)
{
$url = $_POST['yurl'];
function getYoutubeVideoID($url) {
$formatted_url = preg_replace('~https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/| youtube\.com\S*[^\w\-\s])([\w\-]{11})
(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>| </a>))[?=&+%\w-]*~ix','http://www.youtube.com/watch?v=$1',$url);
return $formatted_url;
}
$formatted_url = getYoutubeVideoID($url);
$parsed_url = parse_url($formatted_url);
parse_str($parsed_url['query'], $parsed_query_string);
$v = $parsed_query_string['v'];
$hth = 300; //$_POST['yheight'];
$wdth = 500; //$_POST['ywidth'];
$is_auto = 0;
//Iframe code with optional autoplay
echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.$v.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');
}
?>
form
<html>
<form method="post" id="ytVideo" action="">
Youtube URL: <input id="video-input1" type="text" value="<?php $url ?>" name="yurl">
<input type="submit" value="Generate Embed Code" name="ysubmit">
</form>
</html>
It's because you are not returning your php result anywhere. It's simply lost...
$.post('index.php', form, function(data){
var x = $(data);
$("body").html(x);
});