Is this the right way to retrieve data from mysql using jquery? The php side is working fine ($data gets printed onto the page) but jquery doesn't seem to be receiving the variable at all.
Besides that, is there a way to get the jquery function to run after the page AND after the google maps initMap() function has finished loading? Is it possible to include jquery code inside a standard javascript function?
admin.php
<?php
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
echo json_encode($data);
?><!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
What I've tried
js/admin.js
$(document).ready(function() {
$.ajax({
url: '../admin.php',
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
})
});
I received a "404 Not found" error in the console
The 404-Error indicates that you are using a wrong URL in your jQuery code to get the data. Try to enter not just the filename but the whole URL like https://example.com/admin.php for the url parameter.
Besides your problem getting the data via jQuery, what happens when you open admin.php directly in your browser? Are you getting the $data AND your HTML Code? If thats the case I would recommend you to wrap the whole PHP-Code inside an if-statement:
if($_SERVER['REQUEST_METHOD'] === 'POST'){
header('Content-Type: application/json');
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
die(json_encode($data));
}
else{ ?>
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
<? } ?>
Now, if its a POST-Request like from your js, the PHP will return the data as JSON. Also the right header will be set. If its not a POST-Request the PHP will return your HTML.
To your other question: Yes, it is possible to use jQuery in a normal JavaScript function.
This question already has answers here:
Download CSV file using "AJAX"
(6 answers)
Closed 3 years ago.
I have the following problem:
I'm upgrading a working system, so I have to create code that fits in.
I want to create a csv file on a php page and a mysql database. I'm also using Ajax to stay on the same page while running other php-Files. Here are the Code snippets:
PHP/HTML-Page with Button
<div class="btn" id="export">Export</div>
Javascript Ajax
$("#export").click(function() {exportInfos();});
function exportInfos() {
$.ajax({
type: "POST",
url: "functions/exportInfos.php",
data: { searchterm: $("#search").val(), filterbycat: $("#filterbycat").val(), filterbytype: $("#filterbytype").val()},
success: function(response){
console.log("success_export");
},
});
}
PHP-File to create csv(exportInfos.php):
<?php
include ('../../config.php');
$searchterm = $_POST["searchterm"];
$filterbycat = $_POST["filterbycat"];
$filterbytype = $_POST["filterbytype"];
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=export.csv');
$output = fopen("php://output", "w");
$query = "SELECT * FROM database";
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
?>
I'm not sure where the Problem is but in the console I only see that the php script is called and the success_export text from the log, but no file is opened or downloadable. I think the problem could be with the AJAX part because thats the part Im not sure about the most.
The data values in the Ajax part are there to edit the query as soon as i get some output File.
$mysqli is the connection defined in the config file.
I think you need the change download methodology. Maybe it can be as follows.
Static Page :
<!doctype html>
<html lang="en">
<body>
<div class="btn" id="export">Export</div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('#export').click(function() {exportInfos();});
function exportInfos() {
$.ajax({
type: 'POST',
url: 'functions/createCSV.php',
data: {
searchterm: $('#search').val(),
filterbycat: $('#filterbycat').val(),
filterbytype: $('#filterbytype').val(),
},
success: function(response) {
if (response.filename != undefined && response.filename.length > 0) {
window.open('functions/downloadCSV.php?filename='+response.filename);
}
},
});
}
</script>
</html>
createCSV :
<?php
include('../../config.php');
$searchterm = $_POST["searchterm"];
$filterbycat = $_POST["filterbycat"];
$filterbytype = $_POST["filterbytype"];
//header('Content-Type: text/csv');
//header('Content-Disposition: attachment; filename=export.csv');
$outputPath = '/path/to/save/outputFile.csv';
$output = fopen($outputPath, "w");
$query = "SELECT * FROM database";
$result = mysqli_query($mysqli, $query);
while ($row = mysqli_fetch_assoc($result)) {
fputcsv($output, $row);
}
fclose($output);
header('Content-Type: application/json');
echo json_encode(
[
"filename" => basename($outputPath),
]
);
downloadCSV :
<?php
if (!empty($_GET['filename'])) {
http_send_status(404);
}
$filepath = "/path/to/save/" . $_GET['filename'];
if (!is_file($filepath) || !is_readable($filepath)) {
http_send_status(404);
}
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=" . $_GET['filename']);
echo file_get_contents($filepath);
I have a php file which has svg embedded in php variable. Using an onclick event on the svg elements displayed (lines with ID's) I want to change the colour of the SVG element and then send a parameter to a mysql table to return the x and y coords etc of other lines which join my selected line.
This part unto sending the parameter to mysql table works fine using ajax in my javascript function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/json" />
<title>Enter Exercises</title>
</head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script>
<script type="text/javascript">
function GetPathways(elt)
{
document.getElementById(elt.id).style.stroke = "blue";
var test=elt.id;
var test = document.getElementById(elt.id);
test.setAttribute("x2", "550");
test.setAttribute("y2", "450");
document.getElementById(elt.id).style.visibility = "visible";
var exid = parseInt(elt.id);
$.ajax(
{
type: "POST",
url: 'GetPathways.php',
data: {id: exid},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(message)
{
alert (message);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert("Error code is....:"+xhr.status);
}
});
};
</script>
Ajax calls php file which executes the sql required to return the table rows (multiple). I have tested the query in my phpAdmin and it works fine retrieving some appropriate rows of data.
Ajax script however only executes error function and not the success function.
The success function will eventually use the ID of the returned svg element to be displayed ie update the webpage based on the onclick event. Seems like a good use of ajax to refresh page without reloading.
GetPathways.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/json" />
<title>Get Pathways</title>
</head>
<body>
<?php
//echo "Hello from processing file GetPathways.php"."<br>";
header("Content-Type: application/json");
$dbname = 'TTexercises';
$dbuser = 'dummy entry';
$dbpass = 'dummy entry';
$dbhost = 'localhost:3036';
# set the database connection to be used using php function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to
Connect to '$dbhost'");
# select the database to be used using php function
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$id = $_POST['id'];
$query = "SELECT * FROM `PathwayTable` WHERE `EndPathwayID`= $id";
mysql_query($query);
mysql_close($conn);
?>
</body>
</html>
Error code is 200
You have to echo the data inorder to get response from ajax call and also you did not execute the query. change the GetPathways.php as follows
<?
header("Content-Type: application/json");
$dbname = 'TTexercises';
$dbuser = 'dummy entry';
$dbpass = 'dummy entry';
$dbhost = 'localhost:3036';
# set the database connection to be used using php function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to
Connect to '$dbhost'");
# select the database to be used using php function
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$id = $_POST['id'];
$query = "SELECT * FROM `PathwayTable` WHERE `EndPathwayID`= $id LIMIT 1";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
mysql_close($conn);
print_r($value);
?>
i have a task which is about ajax post data and also ask the script to show data...I have 3 files.. HTML file perform an ajax to the php script, passwrapper.php and then include the another script to show all data in the json format on the console.log in the html file.. I implemented some ajax post values such as 'Abdullahlahlahlah' and 'Muslim' so that the passwrapper.php will receive those data and echo on the console separatley from the whole data... Developer said ajax cannot echo 2 times...... Is it totally impossible???? If there is no way, please tell me other options...
Requirement: Please do not modify the student.php as i want the that php script to echo all the data in json..
Modify the paswrapper.php and html file..
When i run the html file, the error states
Status Code: 200
ErrorThrown: SyntaxError: Unexpected token < in JSON at position 1634
jqXHR.responseText:
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]
Also there is the posted values on the console.log which states LastRowname = Abdullahlahlahlah LastRowReligion = Muslim
HTML File
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="results"</div>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: 'Abdullahlahlahlah',
lastReligion: 'Muslim',
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
passwrapper.php
<?php
include 'student.php';
executePass();
receivePost();
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
echo '<script>console.log("LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'");</script>';
}
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
?>
in my network tab
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]<script>console.log("LastRowname = Abdullahlahlahlah LastRowReligion = Muslim");</script>
my requirement:
i want to echo all the data(except the posted values) on the html file.
i want to show the posted values on the console.log. it can either be in the passwrapper.php or html file..... Please help me....
ajax cannot echo 2 times;
1.student.php
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
//echo json_encode($json_array);
return $json_array;
2.passwrapper.php
<?php
include 'student.php';
$data['student_arr']=executePass();
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>
3.html file
success: function(data){
console.log(data.post_str);
$('#results').text(JSON.stringify(data.student_arr));
},
passwapper.php
<?php
include 'student.php';
ob_start();
executePass();
$string = ob_get_contents();
ob_end_clean();
$data['student_arr']=json_decode($string);
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>
I have troubles with JQuery and Ajax forms. I'm new in Ajax and Jquery. I'm creating a webapp with a search form. The data I'm fetching from MYSQL Database. So I have a request page with a form, then the mysql processing file, a javascript to return the requested data and a html file, where the results are displayed. So, my problem is, that I can't display the results under index.html. Therefore I tried to action directly to landmarks.php and there I can see the reuslts in array like this
([{"id":"1","name":"Big Ben","latitude":"51.500600000000","longitude":"-0.124610000000"}]);
The request.html file
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<form method="post" action="landmarks.php">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<label for="l_name"><b>Name</b></label>
<input type="text" name="l_name" id="l_name" value="" />
<input class="submit" type="submit" value="Submit" />
</fieldset>
</div>
</form>
</body>
Then this file for mysql
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "test";
$password = "test132";
$database = "landmarks";
$l_name = $_POST["l_name"];
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude FROM landmarks WHERE l_name like '".$l_name."' ORDER BY l_name";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
my json callback looks like this
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'landmarks.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.latitude+'<br>'
+ item.longitude+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.')
}
});
});
and finally my final page, where the results should be displayed
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/load-json.js"></script>
</head>
<body>
<div id="output"></div>
</body>
</html>