I am building a website for a school-project. I have been programming in PHP for about a year now, and javascript shouldn't be that much of a problem either.
However, I ran into a problem a couple of days ago. I have a "warning/notification" bar under my navbar. There is two buttons, one where you close the notification and one where you get redirected to read more about it.
If you click the close button, I want to make an AJAX call to the same file, where I have PHP code that will detect the call and then change a SESSION variable, so the notification doesn't show up again regardless of which file you are on.
This however, does not seem to work no matter how many approaches I have tried. I've had enough of this struggle and would greatly appreciate any help from this wonderful community.
This by the way is all in the same file.
Here's the AJAX code:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
type:"POST",
url:"navbar.php",
data: info
});
});
And here's the PHP code (that prints out the HTML):
<?php
require "includes/database.php";
$sql = "SELECT * FROM posts WHERE (post_sort = 'homepage' OR post_sort = 'everywhere') AND post_type = 'warning'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($_SESSION["closed_notification"] == 'no') {
if($resultCheck >= 1) {
while($row = mysqli_fetch_assoc($result)) {
$post_header = $row["header"];
$post_content = $row["post_content"];
$post_index = $row["post_index"];
echo '<div class="nav_bottom_holder_warning">
<div class="navbar_lower_container">
<p>'.$post_header.'</p>
<button class="btn" id="close_warning">Stäng</button>
<button class="btn" id="show_warning">Visa inlägg</button>
</div>
</div>';
}
}
}
?>
Last but not least, the code that is responsible for changing the actual SESSION:
<?php
$_SESSION["closed_notification"] = "no";
if(isset($_POST["info"])) {
$_SESSION["closed_notification"] = "yes";
}
?>
I have tried numerous approaches to this problem, this is just one of them. At this point I am just clueless of how to solve it, thank you.
EDIT: I have already included this file in another file that contains a "session_start()" command. So using that in this file would be no help.
First of all there is no session_start(); on the first line so it will give you an error for the Session Variable.
Secondly update your ajax code to this:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
url: 'navbar.php',
type: 'post',
data: {info:info}
});
});
It basically means that data:{name1:variable2}
Here you are giving the data from js variable(variable2) 'info' to php as info(name ==> that we generally set the input attribute) so in php you can access it as $_POST['info'];.
And lastly you gave the js variable value 'close' and you just checked whether the variable is set while changing the session variable.
Change it to actually checking the value which is better and clear when others read your code.
Summary:
Change data: info to data:{info:info}
Just use Javascript local storage or session storage. I guess it is not important for the server to know if a user has closed the notification yet or not.
$("#close_warning").click(function(){
// close the notification
$("#notification").hide();
// set 'closed' flag in local storage
storage.setItem('closed', 1);
});
Have javascript hide the notification, if the 'closed' flag is set.
if (storage.getItem('closed')) {
$("#notification").hide();
}
Related
Okay so, I'm a bit stuck... Here's my problem. So, what I'm trying to achieve is I have a JS calendar and what I want it to do is when I click on a date, it fetches the times available for that day and displays it and then changes depending on what day you click on WITHOUT refreshing the page. Now, looking around, the only way I can seem to do this is with AJAX (suggestions welcome) although I have never touched AJAX before so have no idea what I'm doing here.
So I've currently got my .HTACCESS files setup on my webserver to use dynamic subdomains.
It's sort of like a multi-step form, and I'm collecting data in the SESSION as I go. Now what I'm guessing the way to do is here, to send a AJAX query with a JS variable with the date and then that runs an SQL query and gets the times and displays them. Here's what I have so far.
Update Session
<div class="output"><?PHP echo $_SESSION["outputTimes"]; ?></div>
<script>
$("#clickme").click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'data.php',
data: { date: '2020-07-04'},
success:function(response){
alert(response);
}
});
});
</script>
data.php
<?php
//Start Session
session_start();
//Include Database Config
include ("config.php");
//POST
$requestDate = $_POST["date"];
//Define SQL Query
$app_get_sql = "SELECT * FROM cc_av WHERE date=$requestDate";
//Run Query
if($result = mysqli_query($db_connect, $app_get_sql)){
while($row = mysqli_fetch_assoc($result)){
$_SESSION["outputTimes"] = '<li>'.$row["time"].'</li>';
}
}
?>
Currently, when I run this, I get the response in the alert() as the current code of the page I'm on. Hence why I noted about my HTACCESS although I can include() it just fine using the same root. Also, from the results of the data.php, how would I output the code sort of update what would be there at the moment.
Here's what I'm trying to create...
https://drive.google.com/file/d/1bgxSUxN6j2IOZcQBuAOo-PeCsuRgdmZ-/view?usp=sharing
Thanks in advance.
So, I've managed to work out what was going wrong. Because my HTACCESS file is creating SubDomains, it was also redirecting the Paths so in the AJAX code I used a URL to the code instead and then added a header to my PHP code on the file that needed to be requested.
header("Access-Control-Allow-Origin: (URL NEEDING TO BE REQUESTED)");
Final AJAX Code
var scriptString = 'THISISMYSTRING';
$('#clickMe').click(function(){
$.ajax({
method: 'get',
url: '(URL)/data.php',
data: {
'myString': scriptString,
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
I am trying to get the sub total updated, when adding the items to the database from java-script. But, currently it displays the first amount and not updates when adding items. (But when runs the query from phpMyAdmin it works correctly)
java-script code
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
HTML code
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" / >
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
The problem is, that when you declare the function with PHP, the function cannot be refreshed by using PHP again... because everything that PHP does, happens before the page is loaded, therefore, let's say as an example:
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
this 'value' from $rowT[0] = 10 from the first query, it will always be 10, because that is what PHP read from the database when it checked upon page load. You will have to use something like jquery or ajax to read the contents of another php file that contains the value (the mysqli_fetch_row).
PHP is literally named hypertext preprocessor, meaning everything that is processed before the html is printed to the user. (before the page has finished loading)
try experimenting with this: https://api.jquery.com/jquery.get/
ShowSubTotal() will bring only the value when the page loads. Dynamic actions will not make any changes, because php needs an server request to operate.
You should bring the subtotal through a dynamic request (ajax) call.
Or:
Use javascript to sum the values and set the value in your txtSubTotal field. If you go for this option, remember to not rely on this value on your server side processing, as it may be adulterated by users.
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
try this code
$("#btnSave").click(function(){
$.ajax({
url : file_url.php,
type : 'post',
data : {
get_subtotal:"subtotal",
},
success : function( response ) {
alert(response);
$("#txtSubTotal").val(response );
},
error: function(response) {
console.log(response);
}
});
});
file_url.php
if(isset($_POST['get_subtotal'])){
$resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
echo $rowT[0];
}
Update: The first part of this question has been solved and has been updated below with the working code.
~
I’m working on a Javascript application and I’m having difficultly getting an AJAX call to work.
I’m able to successfully insert data into my database using AJAX POST & PHP but I can’t seem to pull data from the database.
I have a Javascript application which uses an image, currently it gets this image from a location in the root folder like this:
img.src = 'picture1.jpg';
Instead of doing this, I want to select a random image from a table in the database every time the Javascript application loads.
I’ve created a table with a single column, and populated this with the addresses/locations of images contained in a folder in my root directory.
For example:
/images/00001.jpg
/images/00002.jpg
/images/00003.jpg
This is the PHP file (located at /scripts/imagerandomizer.php) I’m using to call a random image address:
<?php
session_start();
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabase";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlrandomize = mysqli_query($conn,"SELECT images FROM `images` ORDER BY RAND( ) LIMIT 0 , 1");
$row = mysqli_fetch_row($sqlrandomize);
header('Content-Type: application/json');
echo json_encode($row);
mysqli_close($conn);
?>
And the AJAX which initiates the PHP & listens for the echo:
function getRandomImage() {
$.ajax({
url: 'scripts/imagerandomizer.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
I’m trying to use alert(data); to have the randomly chosen image location/address appear in an alert box (just to see if it’s working). But it’s not working for me, I’m pretty sure I've made a mistake somewhere, and I’m not sure if json is the right data type to use here?
I would like to have the returned address replace the current img.src = 'image.jpg'; , so that when the Javascript application starts, it will receive a random image from the img.src = section of code.
Thanks for any help on this!
UPDATE:
The Javascript can now correctly display a random address (using either “alert” or “console.log”) every time it’s loaded. The last part of my question concerns how to have a .js file read this string, and use it as the location of an image that it then fetches.
This is how my game is set up:
I have a file named “game.js”, it contains the code needed for the game to operate, right now, part of that code is this: img.src = 'images/image00001.jpg'; Right now that image is permanently defined and doesn’t change. I’m trying to replace this static definition with the randomized one. Basically I’m trying to get the randomized address to appear after img.src = whenever game.js loads.
I also need to make sure that this event happens before the rest of the game.js code initiates, as I need the randomly chosen image file to be in place before the rest of the game loads.
I’ve tried defining img.src by including img.src=(response) in the AJAX call at the top of the game.js file but it’s failing to load any image into the game. I’m thinking that maybe this is the wrong way to do this?
2nd UPDATE
Hi #PHPGlue
I’ve been trying to get this to work for days now but I’m still missing something.
This is my function to grab the randomized image, and I’ve tried to place the code to run the game in the success function if (img.src) {//code to run the game here}:
Function getRandomImage() {
$.ajax({
url: 'scripts/imagerandomizer.php',
data: "",
dataType: 'json',
success: function(response){
$('#imageId').attr('src', data.image);
img.src = $('#imageId');
if (img.src) {
//code to run the game here
}
}});
};
I’m definitely missing something here, I think I’m not understanding what you mean correctly. I’d really appreciate any advice on this and thank you again for taking the time to look at my question!
3rd Update
Hi, my current code is:
function getRandomImg(gameFunc){
$.post('scripts/imagerandomizer.php', {randImg:1}, function(data){
var im = $('#imageId');
im.attr('src', data.image);
im.load(function(){
gameFunc(img.src=im);
}
}, 'json');
}
getRandomImg(function(){
javascriptgame();
});
function javascriptgame(){
//in this area I’ve placed all the code to make the game work
}
When you said /* pass args to gameFunc here */ I entered img.src=im. (I’m not sure I understand you correctly but I think I’m supposed to define the img.src= for the game to call in this line?
When you said // game code here - could also pass function name instead of Anonymous function, I created a new function called javascriptgame, inside which I placed the game’s code, and then called this function at this line. I’m not sure if that’s what you meant for me to do?
Unfortunately right now there’s still no image loading into the game, I want to thank you again for taking the time to help me with this and if you could offer any more advice that would be awesome! Thanks so much.
The problem is with your mysqli_query()
It should be like
mysqli_query(connection,query,resultmode)
Where connection and query are required and resultmode is optional.
Example:
mysqli_query($conn,"SELECT images FROM images ORDER BY RAND( ) LIMIT 0 , 1");
For more details please check out
mysqli_query
First you should make a separate secure PHP connection page
// connection.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
You're problem is that you don't actually get any results by just making a query. You still have to get the query results and use them in your code:
<?php
include 'connection.php'; $db = db(); $r = array();
if(isset($_POST['randImg'])){
if(+$_POST['randImg'] === 1){
if($iq = $db->query('SELECT images image FROM images ORDER BY RAND() LIMIT 1')){
if($iq->num_rows > 0){
$fi = $iq->fetch_object(); $r['image'] = $fi->image;
}
else{
// no results were found
}
$iq->free();
}
else{
// connection failure
}
}
else{
// randImg hack
}
}
echo json_encode($r);
$db->close();
?>
Get that in JavaScript as data.image inside your success function.
function getRandomImg(gameFunc){
$.post('scripts/imagerandomizer.php', {randImg:1}, function(data){
var im = $('#imageId');
im.attr('src', data.image);
im.load(function(){
gameFunc(/* pass args to gameFunc here */);
}
}, 'json');
}
getRandomImg(function(){
// game code here - could also pass function name instead of Anonymous function
});
I am needing a little help with updating a mysql table from data in an jquery array using ajax. I have tried searching for similar issues but could not find anything, or maybe I do not know the correct terms to search... I'm still fairly new to web dev/coding.
I'll try explain what I am trying to do as clearly as I can. I have a page with seats which users select by clicking on them, upon clicking the seat ID is added in its own span tag in a kind of shopping cart area on the left of the page. This works fine.
Upon checkout my js file is able to pick up these seat ID's in an array, but from here I am unsure of how to properly send this array to the php file, and then for the php file to read the seat ID's from the array and update the relevant seat rows to change the availability from 1 to 0 (this is using ajax).
Here is my code:
checkout.js
$(document).ready(function(){
$('#checkout').click(function(){
var status = sessionStorage.getItem("username");
if(sessionStorage.getItem("username")){
var tickets = [];
$("#myTickets").find("span").each(function(){ tickets.push(this.id); });
var type = "POST",
url = "scripts/sendSeatDetails.php";
console.log(tickets);
$.ajax ({
url:url,
type:type,
data:tickets,
success: function(response){
if(response == 5){
alert("Seat update query failed");
} else {
alert("success");
}
}
});
} else {
alert("Before purchasing please log in. If you do not have an account please register.");
}
});
});
In the console log this shows: ["A2", "A3", "A4"] (if I have selected seats with ID A2, A3, A4 etc).
sendSeatDetails.php
<?php
include("dbconnect.php");
$myseats=$_POST['tickets'];
$query="update seats set status='0' where seatnum=";
for($i=0;$i<count($myseats);$i++){
$query.="'$myseats[$i]'";
if($i<count($myseats)-1){
$query.=" || seatnum=";
}
}
$link = mysql_query($query);
if (!$link) {
echo 5;
}
?>
This returns the alert showing success, but this is not true as the tables are not being updated. Can anyone help me with this or point me in the right direction?
I appreciate your help, and hopefully will be able to contribute to this site when I am at a better skill level in the future.
Many Thanks.
To send an array in jQuery you have to serialize it then parse it in the PHP file:
data: tickets.serialize(),
...
parse_str($_POST['data'], $data);
And then you treat it as an ordinary array.
Run update query one by one.
$myseats=$_POST['tickets'];
$flag=0;// Total successful updates
$myseats=explode(',',$myseats);
for($i=0;$i<count($myseats);$i++){
$query="update seats set status=0 where seatnum='".$myseats[$i]."'";
$link = mysql_query($query);
if (!$link) {
$flag=$flag+1;
}
}
echo $flag;die;
Check response. it will be number of updated rows.
I need to get a value which is from jQuery to PHP so I can do a search function for my site.
I currently have tried:
<script>
$(document).ready(function () {
$('#search_button').click(function(e){
e.preventDefault();
e.stopPropagation();
carSearch();
});
});
function carSearch()
{
$.ajax({
type: "POST",
url: 'cars.php',
data:
{
mpg : $('.mpg').val()
},
success: function(data)
{
alert("success! "+$('.mpg').val()+"mpg");
}
});
}
</script>
This ajax is running when the button is pressed and js value is there as it is displayed in the alert.
However
if(isset($_POST['mpg']))
{
$query = "SELECT * FROM cars WHERE mpg =< ".($_POST['mpg'])."";
echo "<div class='test'></div>";
}
else
{
$query = "SELECT * FROM cars";
}
The isset doesn't trigger, the div is just a big blue box for testing purposes. The ajax is posting to cars.php which is also where the ajax is, so posting to its own file. Which I've not read about being done, but I've posted within the same file before just not with ajax.
I have also tried posting the value from the ajax to another file:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('cdb', $conn);
if(isset($_POST['mpg']))
{
$r = mysql_query ("INSERT INTO test VALUES ".($_POST['mpg'])."", $conn);}
}
?>
Just to test if it is doing anything and it isn't.
So
data:
{
mpg : $('.mpg').val()
},
Appears to be wrong, though I got this from looking at the many many other questions on here to do with passing js to php. I've tried all the variations for it I've seen on here, and only the above code results in the success function alert triggering.
I see a mistake here
$r = mysql_query ("INSERT INTO test VALUES ".($_POST['mpg'])."", $conn);}
The "}" at the end of the line probably throw an error. Is there error in your .php file when the ajax is running ?
To check if there is errors or see what the .php file is returning follow these steps:
Using Chrome right click on your page and choose "Inspect Element"
Click on "Network" in the menu
If not active click on the filter icon (depending on your chrome version)
Click on XHR element of submenu
Refresh your page and your .php file should appear
Click on it and see what the file is returning
(It could also be done in Firefox but not exactly the same titles)
Tell us what you got here.
Also, you should go with the extern file way. Because ajax data returning correspond to the .php file content. If your .php file contains anything else than what you need to return, there is a problem. Example: Any HTML on your .php file will be returning in the ajax data and this is probably far from what you want.