I am trying to check the result from a function and determine where on my page it should go by using the Session Variable "alernativeRD". It goes to the correct element on the first try, but after that it keeps going only to the first element regardless of whether its right or not. After some testing I've found that "alernativeRD" does get changed every time in the PHP function, but it doesn't change in the Javascript part.
PHP PART
function firstSignInDefault(){
global $con;
$clubUsername= $_SESSION['clubUsername'];
$_SESSION['alternativeRD']='false'; //sets it back to false to avoid having alternativeRD be true for next user
$lastName= mysqli_real_escape_string($con, $_POST['lastNameF']);
$firstName= mysqli_real_escape_string($con, $_POST['firstNameF']);
$memberID= mysqli_real_escape_string($con, $_POST['idNumberF']);
if(!(is_numeric($memberID))){
die("<h3> Student ID must be a number </h3>");
}
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
if(mysqli_num_rows($getMemberRow)==0){
$sql="INSERT INTO memberstable (MemberMadeID,FirstName,LastName,Club)
VALUES ('$memberID','$firstName','$lastName', '$clubUsername')";
$test=false; //checks to make sure sql statement runs fine
if(mysqli_query($con,$sql))
$test=true;
else {
echo "<h3> Error running sql </h3>";
}
$date=date("Y-m-d h:i:sa");
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
$memberRowArray=mysqli_fetch_array($getMemberRow);
$memberPanID=$memberRowArray['UniquePanDBID'];
$sql2="INSERT INTO signinstable (TimeOfSignIn, UniquePanDBID, ClubUsername, FirstName, LastName) VALUES ('$date','$memberPanID','$clubUsername', '$firstName', '$lastName')";
//THE FOCUS OF THIS QUESTION IS BELOW THIS COMMENT
if(mysqli_query($con, $sql2) && $test==true){
$_SESSION['alternativeRD']='true';
echo " <h2 id='signedInPeople' >".$date. " ".$firstName ." ". $lastName ."</h2>";
}
}
else {
echo "<h3> ID Number already in use</h3>";
}
}
JAVASCRIPT/AJAX PART
function processFSIF(){
var xmlHttp= makeXMLHTTP();
// Create some variables we need to send to our PHP file
var url = "signInDataPlace.php";
var idNumberF = document.getElementById("idNumberF").value;
var lastNameF = document.getElementById("lastNameF").value;
var firstNameF = document.getElementById("firstNameF").value;
var typeSignIn="first";
var vars = "idNumberF="+idNumberF +"&lastNameF="+lastNameF +"&firstNameF="+firstNameF +"&typeSignIn=" +typeSignIn;
xmlHttp.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var return_data = xmlHttp.responseText;
//AREA OF PROBLEM BELOW
<?php
if($_SESSION['alternativeRD']=='true'){ ///YOU ARE HERE, alternativeRD is acting stupid
?>
document.getElementById("serverInputList").innerHTML = return_data;
<?php
}else{
?>
document.getElementById("serverInputFSIF").innerHTML = return_data;
<?php
}
?>
}
}
// Send the data to PHP now... and wait for response to update the status div
xmlHttp.send(vars); // Actually executes the request
document.getElementById("serverInputFSIF").innerHTML = "processing...";
}
Your Javascript was printed only once, before you use AJAX. You can return the session value together with response, or you can set the cookie in PHP, than use it in javascript.
Related
I have a button in my PHP file, and when I click on that button, I want another PHP file to run and save some data in a MySQL table. For that I am using AJAX call as suggested at this link (How to call a PHP function on the click of a button) which is an answer from StackOverflow itself.
Here is my show_schedule file from which I am trying to execute code of another PHP file:
$('.edit').click(function() {
var place_type = $(this).attr("id");
console.log(place_type);
$.ajax({
type: "POST",
url: "foursquare_api_call.php",
data: { place_type: place_type }
}).done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
});
});
here 'edit' is the class of the button and that button's id is being printed in the console correctly.
here is my foursquare_api_call.php file (which should be run when the button is clicked):
<?php
session_start();
include('connection.php');
if(isset($_POST['place_type'])){
$city = $_SESSION['city'];
$s_id = $_SESSION['sid'];
$query = $_POST['place_type'];
echo "<script>console.log('inside if, before url')</script>";
$url = "https://api.foursquare.com/v2/venues/search?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&v=20180323&limit=10&near=$city&query=$query";
$json = file_get_contents($url);
echo "<script>console.log('inside if, after url')</script>";
$obj = json_decode($json,true);
for($i=0;$i<sizeof($obj['response']['venues']);$i++){
$name = $obj['response']['venues'][$i]['name'];
$latitude = $obj['response']['venues'][$i]['location']['lat'];
$longitude = $obj['response']['venues'][$i]['location']['lng'];
$address = $obj['response']['venues'][$i]['location']['address'];
if(isset($address)){
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude, address) VALUES ($name, $latitude, $longitude, $address)");
$result = $statement->execute();
}
else{
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude) VALUES ($name, $latitude, $longitude)");
$result = $statement->execute();
}
}
}
?>
none of the console.log is logged in the console and also the 'temp' table is not updated. Can anyone tell me where I am making mistake? Or is it even possible to execute the code of a PHP file like this?
Your JavaScript is making an HTTP request to the URL that executes you PHP program.
When it gets a response, you do this:
.done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
}
So you:
Alert something
Show a model
At no point do you do anything with data, which is where the response has been put.
Just sending some HTML containing a script element to the browser doesn't cause it to turn that HTML into a DOM and execute all the script elements.
You'd need to do that explicitly.
That said, sending chunks of HTML with embedded JS back through Ajax is messy at best.
This is why most web services return data formatted as JSON and leave it up to the client-side JS to process that data.
to return the contents of php code you can do something like this
you can use any call to this function
function check_foursquare_api_call(place_type) {
var place_type= encodeURIComponent(place_type);
var xhttp;
//last moment to check if the value exists and is of the correct type
if (place_type== "") {
document.getElementById("example_box").innerHTML = "missing or wrong place_type";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("example_box").innerHTML = xhttp.responseText;
$('#userModal_2').modal('show');
}
};
xhttp.open("GET", "foursquare_api_call.php?place_type="+place_type, true);
xhttp.send();
}
this will allow you to send and execute the code of the foursquare_api_call file and return any elements to example_box, you can return the entire modal if you want,
you can use any POST / GET method, monitor the progress, see more here
XMLHttpRequest
I have a HTML page JavaScript which send a GET request data to PHP file to return all datas saved in the database . PHP replies with a HTML-table - that works fine!
But: When if i click a button (which calls the same JavaScript function) to update my table in order to display the new data, i get the same result (and i have definitely new data on table).
If I call the PHP manually via the browser it'll show me the new results immediately and at this moment it is also working with JavaScript (but only once).
Here is a part of my code.
HTML/JS:
<button onclick="GetData()"></button>
<div id="test"></div>
<script>
function GetData(){
var xhttp = new XMLHttpRequest();
document.getElementById("test").innerHTML = "";
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4 && xhttp.status == 200){
document.getElementById("test").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "../GetData.php", true);
xhttp.send();
}
</script>
PHP:
//DB details
$dbHost = 'localhost';
$dbUsername = 'lalalala';
$dbPassword = 'lalalalal';
$dbName = 'lalalala';
//Create connection and select DB
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName) or die ("UUUUPS");
$sql = "select name, beschreibung, image, video from data";
$result = $db->query($sql);
if ($result->num_rows > 0) {
$return = '<table class ="table table-hover"><thead><tr><th scope="col">Name</th><th scope="col">Beschreibung</th><th scope="col">Bilddatei</th><th scope="col">Video-Url</th></tr></thead><tbody>';
// output data of each row
while($row = $result->fetch_assoc()) {
$return .= "<tr><td>".$row["name"]."</td><td>".$row["beschreibung"]."</td><td><img src=data:image/png;base64,".base64_encode($row["image"])."/></td><td>".$row["video"]."</tr>";
}
$return .= "</tbody></table>";
$db->close();
echo $return;
} else {
echo "0 results";
}
Thank you for your help!
It seems your browser is caching your result, that's why you see data.
You can test it like this:
var random = Math.floor(Math.random() * 100);
xhttp.open("GET", "../GetData.php?"+random, true);
If this helps, look into expire headers in your PHP script. Also, the way you're doing queries in quite outdated. It's a very PHP4 way. Have a look here: http://php.net/manual/en/book.mysqli.php
I guess you probably know this, but just in case. Have you had a look in your browsers inspector, when testing you html page? especially the network tab within that inspector. There you can see the actual response from the server and you can see if it is served from cache or fetched (you can even disable cache there), maybe this helps.
Kind regard,
Mark
So basically I want to have a Javascript function that posts data to a table in my database. i know that I need to call a php page to do this. But the code I have written doesn't work. The js fucntion is triggered by a button press in html. I need to do this in js ajax and not jquery ajax
The Javascript
function comment_sub(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
}
};
xhttp.open("POST", "static/setcomments.php", true);
xhttp.send(encodeURIComponent(document.getElementById('comment-textbox').value));
}
The PHP
<?php
echo "Hello";
$mydb = mysqli_connect("localhost", "root","", "website");
if (!$mydb){
die("Connection failed".mysqli_connect_error());
}
$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_GET['comment-textbox']}')";
$query = mysqli_query($mydb, $sql);
if (!$query)
{
die('Error: ' . mysql_error());
}
echo "1 record added"
?>
Checked the network and console log. The JS function is being called fine but the network logs gives me a 404 error for the post request
You are only sending the value itself, not the name comment-textbox.
Try this:
xhttp.send(JSON.stringify({
'comment-textbox': document.getElementById('comment-textbox').value
}));
On the PHP page, you are doing a HTTP POST and not a HTTP GET. So rewrite it as this:
$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_POST['comment-textbox']}')";
I am trying to get the below AJAX script to pass a dropdown ID to PHP to run a query on, however it doesnt appear that the variable is actually being passed. When I hardcode the PHP file the query runs correctly, but when I try to do it dynamically the query returns "undefined" or nothing at all.
AJAX code
function ajax_post(){
var request = new XMLHttpRequest();
var id = document.getElementById("editorginfo").value;
alert (id);
request.open("POST", "parse.php", true);
request.setRequestHeader("Content-Type", "x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
document.getElementById("orgeditname").value = return_data;
document.getElementById("orgeditphone").value = return_data;
}
}
request.send("id="+id);
}
PHP Parse Code
<?php
include_once('../php_includes/db_connect.php');
$searchid = $_POST['id'];
//$searchid = 1;
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
$user_query = mysqli_query($db_connect, $sql) or die("Error: ".mysqli_error($db_connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$orgid = $row["id"];
$orgname = $row["orgname"];
$orgphone = $row["orgphone"];
echo $orgname, $orgphone;
}
?>
Not really sure where the information is getting lost. When I alert the id out it is capturing the right information, so I assume the issue is in my send portion, but I can't figure out what I'm doing wrong. Any help would be appreciated.
Thanks in advance.
Your request header is wrong. Change this line -
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
^^^^^^^^^^^^
Page1 has an input form. I validate the input field with a JavaScript:
<input type="text" name="frmBrand" size="50" onkeyup="BrandCheck();" maxlength="100" id="frmBrand" />
<span id="frmBrand_Status">Enter existing or new brand</span>
In the JavaScript I then call a PHP script:
function BrandCheck()
{
var jsBrandName = document.forms["AddPolish"]["frmBrand"].value;
if (jsBrandName !==null || jsBrandName !== "")
{
document.getElementById("frmBrand_Status").textContent = jsBrandName
// alert(jsBrandName);
var xmlhttp = new XMLHttpRequest();
var url = "CheckBrand.php";
var vars = "jsBrandName="+jsBrandName;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var return_data = xmlhttp.responseText;
document.getElementById("frmBrand_Status").innerHTML = return_data;
}
}
xmlhttp.send(vars);
document.getElementById("frmBrand_Status").innerHTML = "processing.....";
}
}
So far so good. I do get results from the CheckBrand.php because it changes the frmBrand_Status. But I can't get any database results from the PHP page.
<?php
if(mysqli_connect_errno()) { //if connection database fails
echo("Connection not established ");
}
//by now we have connection to the database
else
{
if(isset($_POST['jsBrandName']))
{ //if we get the name succesfully
$jsBrandName = $_POST['jsBrandName'];
$dbBrandName = mysql_real_escape_string($jsBrandName);
if (!empty($dbBrandName))
{
$dbBrandName = $dbBrandName . "%";
$sqlQuery = "SELECT `BrandName` FROM `Brand` WHERE `BrandName` like '$dbBrandName' ORDER BY `BrandName`";
$result = mysqli_query($con, $sqlQuery);
$NumRows = mysqli_num_rows($result);
// $BrandName_result = mysql_fetch_row($BrandName_query);
echo "Result " . $dbBrandName . " ----- ". $jsBrandName . "Number rows " .$NumRows. " BrandName = " .$result. " SQL " .$sqlQuery;
if( $BrandName_result = mysql_fetch_row($BrandName_query))
{
While ($BrandName_result = mysql_fetch_row($BrandName_query))
{
echo "Brand = " .$BrandName_result[0];
}
}
}
else
{
echo "dbBrandName = empty" . $dbBrandName;
}
}
}
?>
When doing this, the html page shows the constant change of the normal variables. For example when the input field holds "Clu" I get the following output the span ID frmBrand_Status:
Result Clu% ----- CluNumber rows BrandName = SQL SELECT `BrandName` FROM `Brand` WHERE `BrandName` like 'Clu%' ORDER BY `BrandName`
Which looks good as the brandname gets the % appended, but the Number of rows is not shown (empty field?), the SQL Query is shown and looks good, but I don't get any results.
And the if( $BrandName_result = mysql_fetch_row($BrandName_query)) section will not be reached, so there definitely is something going wrong in calling the query.
When I run that same query through PHPMyAdmin, i do get the result I expect, which is 1 row with a brandname.
I'm using firebug to try and troubleshoot the SQL Query, but I can't find where I can check this and I probably can't since PHP is serverside. correct? But how should I then trouble shoot this?
Found what was wrong.
The $con string I was using to open the database was no longer available. On other pages in the site, the $con is available, I load the database using an include script on my index page. But it seems that the variable gets lost when it is called through the XMLHttpRequest(). Which is logical now I think of it, since this can also be a call to a remote server. So my CheckBrand.php page was just missing the $con var to connect to the database.