I'm unable to retrieve the q parameter sent from the PHP.
When I run my code, null values get inserted in my database.
Here are the concerning parts of my code:
My JavaScript function:
function load_now(str){
//alert(str);
var id = str.split("+")[0];
var r = confirm("Start load process for scooter " + str + "?");
if (r == true) {
var xmlhttp = new XMLHttpRequest();
//console.log(str);
xmlhttp.open("GET", "load_scooter_action.php?q=" + str, true);
xmlhttp.send();
}
}
and my load_scooter_action.php file:
<?php
require "checkUserModel.php";
require "databaseController.php";
$databaseController = new DatabaseController();
$databaseController->startConnexionToDatabase();
$conn = $databaseController->getConn();
$dateObject = new DateTime();
$startTime = $dateObject->format('Y-m-d H:i:s');
$user = $_SESSION['user-id'];
// get the q parameter from URL
$q = $_REQUEST["q"];
//forme:(scooter, lat, lng, chg);
$val = explode("+",$q);
$scooter = val[0];
$lat = val[1];
$lng = val[2];
$chg = val[3];
echo "<script type='text/javascript'> console.log(".$q.")</script>";
$sql = "UPDATE `scooters` SET `disponible` = '0' WHERE `scooters`.`numero` = '$scooter';";
if ($conn->query($sql) === TRUE) {
$add = "\nScooter Taken";
} else {
$add = "Error Taking scooter" . $conn->error;
}
$sql = "
INSERT
INTO Reloads(scooter, user, initialLoad, finalLoad, sourceX, sourceY,destinationX, destinationY, startTime,endTime)
VALUES ('$scooter','$user','$chg',null,'$lat','$lng',null ,null, '$startTime', null)";
if ($conn->query($sql) === TRUE) {
//echo "\nNew record created successfully";
//echo '<script>window.location.href = "../php/scooterMapIndex.php";</script>';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Could you help me have a clear understanding of my mistake?
Thanks in advance.
EDIT
str is has the following form 599+50.8037+4.32782+4
Two mistakes:
The first one is a quick fix. Replace val with $val
The second one is that, although str is of the form 599+50.8037+4.32782+4 in the .js file, $q gets retrieved without the + characters in the .php file. Therefore it has to be split appropriately.
Can you show me that what is passed in str or which value is passed in str load_now function. Do you get value when you alert(str)?
If yes then try below function
$.ajax({
type: 'GET',
url: 'follow_user.php?user_id='.urlencode($user_id),
success: function(data) {
alert('done');
}
});
Thanks
Related
I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.
i am using contenteditable property in p tag .. the code is
<p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'A.'.'  '.$question1['Option1'];?></p>
<p contenteditable="true" id="Option2_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'B.'.'  '.$question1['Option2'];?></P>
and jquery to make a request to make request
document).ready(function(){
$("p[contenteditable=true]").blur(function(){
var msg = $(".alert");
var newvalue = $(this).text();
var field = $(this).attr("id");
$.post("ajax.php",field+"="+newvalue,function(d){
var data = JSON.parse(d);
msg.removeClass("hide");
if(data.status == '200'){
msg.addClass("alert-success").removeClass("alert-danger");
}else{
msg.addClass("alert-danger").removeClass("alert-success");
}
msg.text(data.response);
setTimeout(function(){msg.addClass("hide");},3000);//It will add hide class after 3 seconds
});
});
});
and then php to update my mysql database on receiving the request
<?php
$response = NULL;
$status = http_response_code(406);
if(!empty($_POST)){
session_start();
$mock_test_name=$_SESSION['mock_test_name'];
$num_of_sections = $_SESSION['num_of_sections'];
$school_name = $_SESSION['school_name'];
$class_name = $_SESSION['class_name'];
$section_name = $_SESSION['section_name'];
$con = mysqli_connect("localhost","root","","onlinetest");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$table_space = "$school_name $class_name $section_name $mock_test_name";
$table = str_replace(" ", "_", $table_space);
$table_space1 = "$school_name $class_name $section_name";
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = "$table1 $table";
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);
foreach($_POST as $key=>$value){
$key = strip_tags(trim($key));
$value = strip_tags(trim($value));
$explode = explode("_",$key);
$user_id = $explode[1];
$field_name = $explode[0];
if(isset($user_id)){
$update = false;
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'"); //Selecting data from MySql
$result = mysqli_fetch_assoc($selectData); //Fetching Data
if($result[$field_name]!==$value){ //Checking if the Value is modified
$update = mysqli_query($con,"UPDATE" + $table2+ "SET" + $field_name+"="+$value+ "WHERE question_id='"+$user_id+"'"); //Updating MySQL if value is Modifie
}
//Update the users Table
if($update){
$response = "User Details Updated";
http_response_code(200); //Setting HTTP Code to 200 i.e OK
}else{
$response = "Not Modified";
http_response_code(304); //Setting HTTP Code to 304 i.e Not Modified
}
}else{
$response = "Not Acceptable";
}
}
}
echo json_encode(array(
"status"=>$status,
"response"=>$response
));
?>
But i think the request is not made properly as the database is not getting updated.. Please tell me how to check if a request has been made... or am i making error somewhere in writing code ??
Your mysqli_query function is formed incorrectly. You have to escape out of the parentheses in order to drop in variables.
You need to do something like
mysqli_connect($con, "SELECT " + var1 + " FROM " + var2);
or you'll end up making a query for
EDIT:
For a more apt example, the line
$selectData = mysqli_query($con,"SELECT $field_name FROM $table2 WHERE question_id='$user_id'");
should be
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'");
You'll notice the main difference, especially in coloring between the two, signifying that in the first one, the variables $field_name, $table2, and $user_id are all being interpreted as part of the query. You don't want the NAME of the variable, you want the VALUE of it instead, so you need to concatenate the strings together.
This is just one of the multiple similar fixes you'll need to do for your multiple queries. Every place the editor is marking the thing you're trying to use as a variable as part of the string, take the same steps to concat the strings.
You need to change your code like this,
ajax code
$.ajax({
type:"post",
url:"ajax.php",
data: "your data",
success:function(d){
console.log(d);
}
});
php code:
$table_space = $school_name." ".$class_name." ".$section_name." ".$mock_test_name;
$table = str_replace(" ", "_", $table_space);
$table_space1 = $school_name." ".$class_name." ".$section_name;
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = $table1." ".$table;
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);
So I'm trying to make a basic mockup shoe store for one of my classes, but I've been looking for a way to take a variable in the url and send it to my PHP...
This is my php:
<?php
// This block allows our program to access the MySQL database.
// Stores your login information in PHP variables
require_once 'studentdb.php';
// Accesses the login information to connect to the MySQL server using your credentials and database
$db_server = mysql_connect($host, $username, $password);
// This provides the error message that will appear if your credentials or database are invalid
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($dbname)
or die("Unable to select database: " . mysql_error());
if(isset($_GET['model_id']) && is_generic($_GET['model_id'])) {
$model_id = $_GET['model_id'];
$result = mysql_query('CALL shoes(`'.$model_id.'`);');
$row=mysql_fetch_array($result);
echo $row['size'];
}
?>
and I was trying to get it to work with JavaScript/jQuery/ajax, but I couldn't find a method to get model_id (which is in the form of a setup) and pass it back to the PHP.
<script>
$("a").click(function(e) {
e.preventDefault;
var shoePrice = $(this).attr('href');
history.pushState({}, '', $(this).attr("href"));
$("a").attr('data-title', shoePrice);
return false;
});
</script>
Example of my tag:
<a href="?model_id=1" data-largesrc="images/shoe1.jpg" data-title="Test" data-description="Shoe description here" data-price="Price here"><img src="images/thumbs/shoe1.jpg" alt="img01"/>
PS: This is all in the same file..
EDIT:
Old PHP loop -
$model_id = isset($_GET['model_id']) ? $_GET['model_id'] : 0;
if($_GET["model_id"] === "") echo "model_id is an empty string \n";
if($_GET["model_id"] === false) echo "model_id is false \n";
if($_GET["model_id"] === null) echo "model_id is null \n";
if(isset($_GET["model_id"])) echo "model_id is set \n";
if(!empty($_GET["model_id"])) echo "model_id is not empty \n";
if(isset($model_id)) {
$query = 'SELECT size, price, style FROM shoes WHERE model_id='.$model_id;
$search1 = 'SELECT * FROM shoes WHERE model_id='.$model_id;
$abc = mysql_query($search1);
$result = mysql_query($query);
// The mysql_num_rows function returns an integer representation of number of rows for the table passed as an argument
$number_of_requests = mysql_num_rows($result);
if(! $result) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "Shoe ID: {$row['model_id']} <br>".
"Shoes Size: {$row['size']}<br>".
"Shoe Price: {$row['price']}<br>".
"Shoes Style: {$row['style']}<br>";
}
while($row = mysql_fetch_assoc($abc)) {
$size = $row['size'];
}
}
Assuming you are sending request to same page as the href shows all you need is a $.get in the click handler
$("a").click(function(e) {
e.preventDefault;
var shoePrice = $(this).attr('href');
history.pushState({}, '', $(this).attr("href"));
$("a").attr('data-title', shoePrice);
$.get(shoePrice , function(serverResponse){
// do something here with response
})
});
$,get is a shorthand method for $.ajax.
If you are receiving json can replace $.get with $.getJSON
Here is what I've actually come up with, this is the final version that works... Thank you for your help, but I had to dig deeper to figure it out.
<script>
function parseData(html) {
var json = {};
$.each(document.getElementsByTagName("div"), function(index, value) {
json[value.id] = value.innerHTML;
});
return json;
};
$("a").click(function(e) {
e.preventDefault();
var href = $(this).attr("href");
history.pushState({}, '', $(this).attr("href"));
$.get("/~huntcki3/test.php"+$(this).attr("href"), function(data) {
var info = JSON.parse(data);
console.log(info);
console.log(href);
$("div.og-details h3")[0].innerHTML = info.name;
$("div.og-details p")[0].innerHTML = info.style+'<br>' + 'Size: ' + info.size+'<br>' + '$' + info.price+' USD';
});
});
</script>
public function login($username,$password) {
$linkingcon = $this->getConnection();
$sqlquery = "SELECT ac.userID,ac.name,us.usertype FROM users us JOIN accounts ac ON us.userID = ac.userID WHERE us.username='$username' AND us.password='$password';";
$result = mysql_query($sqlquery , $linkingcon);
$this->throwMySQLExceptionOnError($linkingcon);
$row = mysql_fetch_array($result);
$survey = new stdClass();
if($row) {
$res->userID = (int)$row['userID'];
$res->name = $row['name'];
$res->usertype = (int)$row['usertype'];
$string = rand() . 'SurveyLand' . rand() . $username. $password;
$_SESSION['SURVEYLAND_KEY'] = md5($string);
} else {
$res = false;
}
return $res;
}
Hi everyone,
im in a spot of bother regarding a conversion, I need to get a Javascript response from the above php function by calling that php function from another script(HTML)...
P.S
i saw an example in the internet like the below, cant i use method like below get the call
client.sendRequest('hello', null, { 'async': false }, function(rtn) {
if (rtn.isError())
document.write('<li>Request hello error: ' + rtn.getErrorMessage() + "</li>");
else
document.write('<li>Request hello result: ' + rtn.getResult() + "</li>");
});
If you are using ajax return response in json format
return json_encode($res);
Or just print response in script tag
<script>
var res = <?php echo json_encode(login('username','password')); ?>
</script>
I am using AJAX in order to access data from a php file.
I have problem with the format of retrieved data from database, please help.
So, this is my ajax function splice. It retrieves data from find_account.php
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
form_prof.prof_id.value = req.responseText;
form_prof.prof_name.value = req.responseText;
form_prof.prof_username.value = req.responseText;
form_prof.prof_password.value = req.responseText;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
find_account.php
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
echo 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$id = $arr['profs_number'];
$name = $arr['profs_name'];
$username = $arr['profs_username'];
$password = $arr['profs_password'];
}
header("Content-type: text/plain");
echo $id;
echo $name;
echo $username;
echo $password;
?>
and I have 4 input boxes in my HTML from where the req.responseText puts the value
and everytime I search the name in the input field for example:
Search: [ Dorothy Perkins ]
The output goes like [id,name,username,password]:
[20111Dorothy Perkinsdperkins#mail.com123456] [same with 1st field] [same] [same]
Wherein I want it to be like...
[20111] [Dorothy Pekins] [dperkins#mail.com] [123456]
Where [ ] are input fields.
Please help me arrange my format, I am so confused. I am new to this.
You can encode return values in json before sending back.
In PHP
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
$returnValues = 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$returnValues = json_encode($arr);
}
echo $returnValues;
?>
In Javascript
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
req = JSON.parse(reg);
form_prof.prof_id.value = req.id;
form_prof.prof_name.value = req.name;
form_prof.prof_username.value = req.username;
form_prof.prof_password.value = req.password;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
You have to write the data in some format from your PHP code (XML, json, or simply separate the values with a comma), and parse it from your javascript.
For example, in PHP:
echo $id . "," . $name . "," . $username . "," . $password;
And then in the javascript:
values = req.responseText.split(",");
form_prof.prof_id.value = values[0]
form_prof.prof_name.value = values[1];
form_prof.prof_username.value = values[2];
form_prof.prof_password.value = values[3];
Of course you may have to do something more complicated if the values may contain a comma.
You can try this
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query, MYSQLI_STORE_RESULT);
while($arr = $result->fetch_array(MYSQLI_ASSOC)) {
$returnValues = json_encode($arr);
break;
}
echo $returnValues;
Note that column names are used as associative index for $arr
Hope it works.