Upload and download variables using AJAX/PHP - javascript

I have a jQuery script file on a page which requires data to be uploaded. Depending on if the data uploaded has a value or not, the PHP page will either return the current time (if value uploaded !isset()), or some sql data. However, when the variable I upload actually has a value, it still returns the !isset() method. Am I doing something incorrectly?
AJAX
$.ajax({
url: 'download.php',
type: 'REQUEST',
datatype: 'json',
data: ({
last_downloaded: latestTimestamp,
username: username
}),
success: function (data) {
parsedData = $.parseJSON(data);
if (!latestTimestamp) {
latestTimestamp = parsedData.most_recent;
}
}
});
}
if latestTimestamp is null, (it should be the first time this method is run), then the most recent time is run. However when it runs the second time, latestTimestamp has a value when I console.log.
PHP
<?php
// Get variables sent
$last_chat_time = $_REQUEST['last_downloaded'];
$username = $_REQUEST['username'];
// Start echoing JSON
if (!isset($last_chat_time)) {
// User did not send last chat time they have, assume they just joined
// Get the most recent chat date
$SQL = 'SELECT current_timestamp() as "most_recent" from dual';
$results = mysql_fetch_assoc(mysql_query($SQL));
$last_chat_time = $results;
echo '{"most_recent":"' . $results['most_recent'] . '"}';
}
else{
$SQL = 'return some tasty data'
$result = mysql_query($SQL);
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = Array(
'chat' => $row['chat'],
'time' => $row['time_sent'],
'username' => $row['username']
);
}
echo json_encode($messages);
}
On the php, it ALWAYS returns the first if. However, if I visit the url directly for the php page and append ?last_downloaded=somedate, it returns the correct information. Am I doing the AJAX incorrectly?

To me this has to be updated to type : 'post or get' because php's $_REQUEST handles both, so you can change your type to this:
$.ajax({
url: 'download.php',
type: 'post',
or this:
$.ajax({
url: 'download.php',
type: 'get',

Related

Sending data from front-end to back-end to front-end

Hi i'm a beginner in using JavaScript i have this html page with JavaScript codes that receives data from the server and display it on this current page, what i'm trying to do is use that data and sending it to another PHP page for my SQL query to get back results.
<script>
var json = sessionStorage.xhr;
var object = JSON.parse(json);
var hard = object["red-fruits"];
var string = JSON.stringify (hard);
var stringData = encodeURIComponent(string);
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
cache: false,
success: function(){
console.log("OK");
}
});
var user = sessionStorage.getItem('impData');
console.log(user);
</script>
This is my PHP page codes, what i'm doing here is getting the data "dataA" from that html page and sending it to this PHP page for the SQL query and getting the results which is the "$haha" array and using JavaScript session function to send it back to the HTML page. But my console only shows "null" can anyone tell me if i'm doing anything wrong or have any suggestion would be really appreciated.
<?php
$connection = mysqli_connect("localhost","root","","") or
die("Error " . mysqli_error($connection));
if (isset($_POST['dataA'])) {
echo $name = $_POST['dataA'];
}
else {
echo "Error";
}
$string = str_replace("]", "", str_replace("[", "", str_replace('"','',$falcon)));
$array = explode(',', $string);
$array2= implode("', '",$array);
$sql = // "SQL query"
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .
mysqli_error($connection));
while($row = mysqli_fetch_array($result)) {
$haha[] = $row['row_name'];
}
?>
<script type="text/javascript">
var tills = <?php echo '["' . implode('", "', $haha) . '"]' ?>;
console.log (tills);
sessionStorage.setItem('impData', tills);
</script>
You are now mixing ajax and session data on a strange way. The session data used by your javascript will not be updated by the php-script till you refresh your page. The correct way to handle data is in the "success" function:
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
dataType : "json",
cache: false,
success: function(data){
console.log(data);
}
});
and in you PHP output the data you want to send to the browser as a json string:
echo json_encode($your_object);

Successful AJAX call on working PHP script returns nothing

I'm running a script which is supposed to send a user ID number to a database. The database grabs a bunch of image IDs from whichever row has the matching user ID, then goes to a different table and grabs the image URLs which match the image IDs. Then it returns the URLs.
The PHP script runs fine on its own, it returns the correct URL in either straight text or JSON, as requested.
As for the jQuery, the AJAX call does indeed get to the success function, because I can ask it to document.write something there and it will do it. When I ask it to print out the data, however, the AJAX call runs forever (I think it is repeatedly calling the success function? Based on the browser telling me that it is either waiting or transferring data repeatedly). Regardless, nothing is printed to the screen despite the repeating script.
Oh, also, no errors are returned to the console.
I am not sure why it is doing this and so here I am. I've browsed through the other posts here and randomly on the internet, with no luck. Any help is appreciated!
Here is the PHP:
<?php
header('Content-type: text/plain; charset=utf-8');
// define variables and set to empty values
$servername = "localhost";
$username = "root";
$password = "Wolf*6262";
$dbname = "Game";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$id = $_GET["id"];
}
$query1 = mysqli_query($conn, "SELECT imageids FROM users WHERE id = $id");
// Start user session
if ($imageIds = mysqli_fetch_array($query1)) {
fetchUrls($imageIds, $conn);
} else {
echo "Fail";
}
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = '1'");
$array = mysqli_fetch_assoc($query2);
$url = $array["url"];
exit($url);
}
$conn->close();
The jQuery:
function getUrls (userId) {
$.ajax({
type: 'GET',
data: {id:userId},
URL: 'fetchChar.php',
async: false,
dataType: 'text',
success: function (data) {
document.write(data);
document.write(userId);
}
});
}
Aaand here's where I define userId and call getUrls, it's in a separate HTML file:
var userId = <?php echo $_SESSION["id"]; ?>;
$(document).ready(getUrls(userId));
Can you please modify your script: as standard way what prefer from jQuery:
1. Change URL to url
2. Please avoid async defining
Like this
$.ajax({
type: 'GET',
data:{ id: userId },
url: 'fetchChar.php',
// async: false,
dataType: 'text',
success: function (data) {
console.log(data);
//document.write(data);
//document.write(userId);
}
});
I added console log to show the return data, so that you can make sure that your data is returning correctly from fetchChar.php file using console log.
Ended up doing the following, question solved:
Javascript file:
$.ajax({
type: "POST",
dataType: "json",
url: "fetchChar.php",
data: {id:userId},
success: function(data) {
document.write(JSON.stringify(data));
}
});
PHP file, near the end:
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = 1");
$array = mysqli_fetch_assoc($query2);
$url = $array['url'];
$url = json_encode($url);
echo $url;
exit();
}

Post data from javascript to php file using ajax doesn't work

When I tried to used ajax to post data from javascript file to php file, there was nothing displayed on php file after using
$_POST['userinput']
Here is the javascript file:
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
userinput = places[0].name.toString(); // Get user input from search box
// Pass data to userinput.php via ajax
$.ajax({
url: 'userinput.php',
data: {userinput : userinput},
type: "POST",
success: function (result) {
alert(JSON.stringify(result));
}
});
});
php file:
if (isset($_POST)) {
$servername = "localhost";
$username = "XXXXXXX";
$password = "XXXXXXXXX";
$dbname = "CALIFORNIA";
$city = $_POST['userinput']; // Nothing is posted here
// Create connection
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);
$sql = $conn->prepare("SELECT State FROM CITY as C WHERE C.City_name=$city");
$sql->execute();
$result = $sql->fetchAll();
$json = json_encode($result);
echo $json;
}
I was able to connect to the mysql database. However, there was no data posted from javascript file to php. I'm not sure what to do from this point. the value $city print out nothing. On the client side it printed out an empty object.
in your ajax function try setting dataType property
$.ajax({
url: 'userinput.php',
data: {'userinput' : 'userinput'},
type: "POST",
dataType: "text", // add this property
success: function (result) {
alert(JSON.stringify(result));
}
});

Using two Ajax calls to post then retrieve data

I am currently trying to firstly post the name of the user that I am trying to retrieve from the database to my php code using ajax. Then in the success part of the call I am trying to make a function to retrieve data from a database which matches the name of the user the I previously sent to the page, however no data is coming back to the javascript code.
Here is the function with my ajax calls.
function checkPatientAnswers(event) {
window.open("../src/clinicreview.php", "_self");
var patientname = event.data.patientname;
var dataToSend = 'patientname=' + patientname;
var clinicquestions = getQuestionsForClinic();
var answers = [];
$.ajax({
type: "POST",
url: "../src/getselectedpatient.php",
data: dataToSend,
cache: false,
success: function(result) {
$.ajax({
url: "../src/getselectedpatient.php",
data: "",
dataType: "json",
success: function(row) {
answers = row;
console.log(row);
}
})
}
})
console.log(answers);
for (i in clinicquestions) {
$('#patientanswers').append("<h2>" + clinicquestions[i] + " = " + answers[i]);
}
$('#patientanswers').append("Patient Status = " + answers[answers.length - 1]);
}
And here is my PHP code:
<?php
session_start();
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$patientname = $_POST['patientname'];
$_SESSION['patient'] = $POST['patientname'];
$data = array();
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '$patientname'");
$data = mysql_fetch_row($query);
echo json_encode($data);
mysql_close($con);
?>
jQuery
var dataToSend = {'patientname':patientname};
$.ajax({
type : "POST",
url : "../src/getselectedpatient.php",
data : dataToSend,
dataType : "json",
cache : false,
success: function(result) {
console.log(result);
}
})
PHP
<?php
session_start();
$_SESSION['patient'] = $POST['patientname'];
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '".$_POST['patientname']."'");
$data = mysql_fetch_row($query);
mysql_close($con);
echo json_encode($data);
?>
For the record, I do not condone the use of your mysql_* shenanigans. It has been completely REMOVED in PHP 7 and don't try telling me that you will ride PHP 5 till death do you part.
Secondly, you are 8000% open to SQL injection.
I understand that you are most likely just a student at a school in the UK but if your teacher/professor is OK with your code then you are not getting your money's worth.
You probably forgot to set data on the second call:
$.ajax({
url : "../src/getselectedpatient.php",
data : result,
or result.idor whatever.

Get array as response from Ajax request

I use the following Ajax request to pass data:
var query = {
"username" : $('#username').val(),
"email" : $('#email').val(),
}
$.ajax({
type : "POST",
url : "system/process_registration.php",
data : query,
cache : false,
success : function(html) {
// output
}
});
My php-file (process-registration.php), in which the query is being processed, looks like this:
require_once 'db.php';
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
// Include new user into database
$db -> query("INSERT INTO users (username, email) VALUES ('$username', '$email');");
//Identify user id of this new user (maybe there is a faster way???)
$results = $db -> query("SELECT * FROM users WHERE username='$username'");
while ($result = $results->fetch_assoc()) {
$user_id = $result['id'];
}
// My output?
Now comes my question: How can I tell the Ajax command / the PHP script to return as a result two elements:
a HTML message: <p>You have registered successfully</p>
the $user_id that I have identified via the loop above
I need the user_id, because in the frontend I want to include it as a GET parameter into the href of the button "Go to admin area" that will appear AFTER the Ajax request will be completed.
Try this:
$response = array('user_id'=>$user_id,'message'=>'Success - user created');
echo json_encode($response);
This will give return a json object that you can access in JS.
$.ajax({
type : "POST",
url : "system/process_registration.php",
data : query,
cache : false,
dataType: 'json',
success : function(html) {
// output - do something with the response
console.log(html.user_id);
console.log(html.message);
}
});
I think it would be better to change the array in string by putting a special character(I use % or #)between different values. In your case just echo 'You have registered successfully%'.$user_id ;. Now explode the response string and use both.

Categories

Resources