reference a php string in jquery? - php

I am using the following code to generate a random string in php, and then am storing this in my database like so:
<?php $allowance_promo = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8); ?>
I am then using my query to store this value into the database:
$query = sprintf("UPDATE internal_users SET allowance_promo = '$allowance_promo' WHERE user_id ='{$_SESSION['id']}'");
$result = mysql_query($query);
I then use another query to retrieve the value:
$query2 = sprintf("SELECT * FROM internal_users WHERE user_id ='{$_SESSION['id']}'");
$result2 = mysql_query($query2);
while ($row = mysql_fetch_array($result2)) {
$check = $row['allowance_promo'];
Then i am trying to use jquery to check if the value entered into my input field matches the one in the database like so:
<script>
$(document).ready(function() {
$('.promo_check').click(function() {
var discountCode = "<?php echo $check; ?>";
var codeEntered = $("input[name='promo']").val();
if (discountCode == codeEntered) {
$('#submit').removeAttr("disabled");
}
});
});
</script>
However i am having some difficulty getting it to work using a php string. If i use normal text like var discountCode = '123'; then it works, but when i try and use var discountCode = "<?php echo $check; ?>"; it wont work. Can someone please show me what i am doing wrong. Thanks,

Replace your script by the script below. Put discountCode outside the click event handler and remove $(document).ready();
<script type="text/javascript">
var discountCode = "<?php echo $allowance_promo; ?>";
$('.promo_check').click(function() {
var codeEntered = $("input[name='promo']").val();
if (discountCode == codeEntered) {
$('#submit').removeAttr("disabled");
}
});
</script>

Related

jQuery function doesn't update data when it is updated in the database

I would like to update the data in the frontend when it is changed in the database. The code I'm using is given below:
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<div id="test">
<?php
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = 1;";
if(mysqli_fetch_assoc(mysqli_query($conn, $query))["name"] == "MyName")
echo 'Hi <b>MyName!</b>';
else
echo 'You are not <b>MyName</b>.';
?>
</div>
<script>
setInterval(function(){
$.get("/test.php", function(data){
let $data = $(data);
$("#test").append($data.find("#test > *"));
});
}, 1000);
</script>
However, when the data is updated, it does not get updated in the frontend unless refreshed. When I use jQuery's load() function, it works perfectly. Why does this not work?
As I suggested in the comment, if you create a stand alone PHP Script, it might be like:
getUserName.php
<?php
$id = (int)$_GET['id'];
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = $id;";
$myName = "";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$myName = $row;
}
}
mysqli_free_result($result);
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($myName);
?>
This is a very basic example and I would strongly advise you switch to using prepared statements to avoid the risk of SQL Injection.
In your HTML you can now do:
<script>
setInterval(function(){
$.getJSON("/getUserName.php", { id: 1 }, function(data){
$("#test").append(data.name);
});
}, 1000);
</script>
This will ping the script every second and you will have a list of names appearing.

retrieve multiple data from various queries with ajax php mysql

I'm new in Ajax and JSON notation, so I'm trying to get data from differents tables of a Database, data like country names, state names, departament name, job position etc. and I've seen examples how through JSON can get data but just from a single table, can you give me a little help how can I do it with more than one table and keep it in an array.
<?php
$host = "localhost";
$user = "usuer";
$pass = "password";
$databaseName = "jsonExample";
$tableName = "variables";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}
echo json_encode($array);
?>
Html file:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
If you want to have the results from multiple queries in one array you can add each result to a key. F.i. if you querying table table1 to tablen ...
// define the array that will contain all result sets
$array = [];
// create an array for the result set coming from table 1
$array['table1']= [];
$result = mysql_query("SELECT * FROM table1");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table1'][] = $obj;
}
}
// create an array for the result set coming from table 2
$array['table2']= [];
$result = mysql_query("SELECT * FROM table2");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table2'][] = $obj;
}
}
::
::
// create an array for the result set coming from table n
$array['tablen']= [];
$result = mysql_query("SELECT * FROM tablen");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['tablen'][] = $obj;
}
}
// return the results formatted as json
return json_encode($array);
In javascript you can access the results for table1 with data->table1.
Tip
Use mysqli instead of mysql. It is the improved version of mysql. Check the answers for this question for some background.

Get url parameter and query mysql data with ajax

I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];

get input values from other input

im having a little problem, i have a form, with three fields, my problem is this one:
on the 2 and 3 input i get via javascript values for countries and cities, what i want to do is to make the city input throw the values from the country i have selected in the country input, heres the javascript
<script>
var availableTags = [
<?php
$sql = "select * from citys ";
$rsd = mysql_query($sql);
while($row = mysql_fetch_array($rsd))
{
$pid=$row['cid'];
$city=$row['city'];
$state=$row['state'];
?>
"<?php echo $city; ?>,<?php echo $state; ?>",
<?php } ?>
];
$( "#inputsearch21" ).autocomplete({
source: function( request, response ) {
var matches = $.map( availableTags, function(tag) {
if ( tag.toUpperCase().indexOf(request.term.toUpperCase()) === 0 ) {
return tag;
}
});
response(matches);
}
});
</script>
and the country script is the same, changing the php for country database.
i know i have to get the country id from the first form and in the second query i should be "select * from citys where countryid="$countryid"
any idea how to do this?
Probably the best thing to do is to work with an cobmination ajax and json. Then It should be something like this.
getCities.php
<?php
/* your connection ofc. */
$con = database_connection();
/* example unsecure please use PDO */
$sql = "SELECT ID, Name FROM City WHERE Country = '" . $_GET['country'] . "'";
$rsd = mysql_query($sql);
$res = mysql_fetch_array($rsd);
/* Return output in json format */
echo json_encode($res);
?>
Javascript
$.ajax({
type: "GET",
url: "getCities.php",
data: { country: "Germany" }
}).done(function( output ) {
/* Example for select inputs */
var cities = eval('(' + output + ')');
var length = cities.length;
for(var i = 0; i < length; i++)
{
var newOption = $('<option/>');
newOption.attr('text', cities[i].Text);
newOption.attr('value', cities[i].Value);
$('#ID-OF-SELECTBOX').append(newOption);
}
});

JQuery AJAX update a textbox on another textbox textchanged

I would like to update my input text type (id="textbox2") when i typed something at another input text type (id="textbox1").
Here's my initial code:
$("#textbox1").keyup(function(){
$.ajax({
type: "POST",
url: "idgetter.php",
data: 'id='+$("#textbox1").val(),
success: function(n) {
$('#textbox2').val(n);
},
error: function(n) {
$('#textbox2').val(n);
}
});
});
And my idgetter.php :
include("inc/conn.php");
$q = mysql_query("SELECT name FROM jurnalis WHERE userid = '".$_POST['id']."'")or trigger_error("SQL", E_USER_ERROR);
if(mysql_num_rows($q)<=0) return "none";
else{
$r = mysql_fetch_array($q);
return $r["name"];
Long story short, this did not work, any idea why?
In idgetter.php, Instead of returning using return give
echo "none";
and
echo $r["name"];
You should try echo instead of return:
your code would be like this:
include("inc/conn.php");
$q = mysql_query("SELECT name FROM jurnalis WHERE userid = '".$_POST['id']."'")or trigger_error("SQL", E_USER_ERROR);
if(mysql_num_rows($q)<=0) echo "none";
else{
$r = mysql_fetch_array($q);
echo $r["name"];
Think there are a few amends needed in your php:
change return to echo (like stated in the other answers)
change your if statement to
if(mysql_num_rows($q)==0){
echo 'none';
}else{
$r = mysql_fetch_assoc($q);
echo $r['name'];
}
That should do it hopefully. Also as an FYI its worth trying to avoid adding $_POST[''] items to SQL statements directly, as its prone to SQL injection breaches.

Categories