The information is not updated, or rather it refreshes, but it does not take out the new information. if I enter data.php, then if it takes out the new information, it's like it keeps the cache memory and doesn't get the new information added. After entering data.php, everything also appears in ajax.
data.php:
<?php
$conn = new mysqli('localhost', 'xxx', 'x', 'xx');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM `users`");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo
" <tr>
<td>".$row['username']."</td>
<td>Jackson</td>
<td>94</td>
</tr>";
}
}
?>
ajax:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
ajax_call = function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "data.php",
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").html(response);
}
});
};
var interval = 1000;
setInterval(ajax_call, interval);
});
</script>
Edit: you change the data in ajax only if you manually enter data.php and then change it automatically in ajax page.
Only change GEt from POST and is work fine.
Related
When form submission finishes, the page DISPLAYS the raw json data instead of logging it to the console. The php and html code are both on the same page so I wasn't expecting the page to change at all.
POST
jQuery(function($) {
$("#idSearch").submit(function(event) {
$.ajax({
url: "/index.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
sucess: function(data) {
console.log(data);
}
})
})
});
php form handling
<?php
if (isset($_POST['orderId'])){
header('Content-Type: application/json');
require 'private/database.php';
$sql = "SELECT * FROM form";
$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));
}
?><!DOCTYPE html>
I've implemented something similar on another webpage but it works as I intended.
POST
function loadInfo() {
jQuery(function($) {
$.ajax({
method: "POST",
url: "/admin.php",
data: {loadInfo: 1},
dataType: "json",
success: function(data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
setMarker(data, i, "red");
printInfo(data, i);
}
}
})
});
}
php form handling
<?php
if(isset($_POST['loadInfo'])){
header('Content-Type: application/json');
require 'private/database.php';
$sql = "SELECT * FROM form";
$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));
}
?><!DOCTYPE html>
Why do these two pages behave differently?
You should stop the default form event.
The browser continue the action and submit the form, so the page is reloaded using POST.
You could prevent using Event.preventDefault()
jQuery(function($) {
$("#idSearch").submit(function(event) {
event.preventDefault(); // << ADD
$.ajax({
url: "/index.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function(data) { // << Here 'success' not 'sucess'.
console.log(data);
}
})
})
});
solved:
<form action="index.php" method="POST" id="idSearch">
<input type="text" name="orderId" placeholder="訂單號瑪" required><br>
<input type="submit">
</form>
I didn't think I needed an action parameter for the form as it was being sent to the same .php? The code worked once I added a path. Weird.
I am trying some things regarding Ajax, Jquery and PHP.
My JavaScript code (the pop.php is located correctly)
<script type="text/javascript">
$('.nameclick').click(function()) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id=$(this).data("formid")}
success: function(result){
alert(result);
} else {
alert("test");
}
});
});
</script>
Part of my html/php code in the same page (this code works fine to print out the table I am looking for):
<table class="data-table">
<thead>
<tr>
<th>Servicenummer</th>
<th>Kund</th>
<th>Uppgift</th>
<th>Status</th>
<th>Inlämnad</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td><div id="clickMe">'.$row['service'].'</div></td>
<td>'.$row['name'].'</td>
<td>'.$row['Drakt1'].'<br>'.$row['Drakt2'].'<br>'.$row['Drakt3'].'<br>'.$row['Drakt4'].'<br>'.$row['Drakt5'].'<br>'.$row['Drakt6'].'<br>'.$row['reg1'].'<br>'.$row['flaska1'].'<br>'.$row['dator1'].'</td>
<td>'.$row['Service_Status'].'</td>
<td>'.$row['date'].'</td>
</tr>';
$no++;
}?>
</tbody>
</table>
And my pop.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$telephone = $conn->real_escape_string($_POST['telephone']);
$sql = 'SELECT name, email, telephone FROM Service_Form WHERE id = "10"';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<?php
while ($row = mysqli_fetch_array($query))
{
echo $row['name'];
echo $row['email'];
echo $row['telephone'];
}
?>
At the moment when I click my link in my normal page I don't get anything, no alerts at all, but my pop.php prints out the values correctly, I hope... I know I have to change my id="10" to something but i am not certain to what, could it be formid?
What am I doing wrong here?
What I want:
a table with the values below from a table in the database
when I click the name in the table it should show an alert (or something similar) that shows the name, email and telephone number (these are stored as well in the database table but not on the website table).
your ajax function is having some errors
so use this
<script type="text/javascript">
$('.nameclick').click(function(ev) {
ev.preventDefault();
var id = $(this).data("formid");
$.ajax({
type: "POST",
url: "pop.php",
data: {
"id":id
},
success: function(result){
alert(result);
},
error:function (error) {
alert(error);
}
});
});
</script>
I am editing your jquery part please try
<script type="text/javascript">
$('.nameclick').click(function(ev)) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id:$(this).attr("data-formid")}
success: function(result){
if(result){
alert(result);
} else {
alert("test");
}
}
});
});
</script>
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();
}
I am trying to let jQuery dynamically add html to my page. Unfortunately, I don't receive a response from my server. My JS code sends a GET request, which contains a parameter (bodypart). The server should return a response including the results from the database, but the response is empty.
What causes this problem?
JAVASCRIPT:
function getData() {
var sPanelHeading = '<div class="col-lg-3"><div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">Symptomen van ' + bodypart + '</h3></div>';
$( "#abc" ).append(sPanelHeading);
$.ajax({
url: 'controller.php',
data: 'bodypart=Autism',
dataType: 'json',
}).done(function(data) {
$( "#abc" ).append('<div class="panel-body" style="overflow-y: scroll;"><span class="list-group-item"><b>Vaak voorkomende symptomen</b></span></div><div class="list-group">');
for (var c in data) {
$("#abc").append('<span class="list-group-item">');
$("#abc").append(c);
$("#abc").append('</span">');
}
}).always(function(data) {
console.log(data);
});
}
PHP:
<?php
require_once( 'config.php' );
$bodypart = $_GET['bodypart'];
$sql = "SELECT c_name FROM condition WHERE c_name = '$bodypart'";
$result = $conn->query($sql);
$json_response = array();
if ($result->num_rows > 0) {
while($row = mysql_fetch_assoc($query)) {
$json_response[] = $row;
}
print json_encode($json_response);
}
$conn->close();
?>
1st : instead of
data: 'bodypart=Autism',
use
data: {'bodypart':'Autism'},
2nd
echo json_encode($json_response);
Basics of $.ajax
$.ajax({
url: 'controller.php',
type: 'GET',
data: {'bodypart':'Autism'},
dataType: 'json',
success : function(data){
alert(data);
}
});
in php
<?php
$bodypart = $_GET['bodypart'];
echo $bodypart;
?>
output should alert Autism .. if this Ok you can complete your stuff .. if something went wrong .. check your php file path
I was wondering what is the best to use in my php file in connecting to database include or include_once while my ajax script requesting it everytime.
ajax script
$(document).ready(function () {
var countTimer = setInterval(function () {
codeValue();
}, 500)
function codeValue() {
if ($('#emailCodeResult').val() !== '') {
clearInterval(countTimer);
}
$.ajax({
type: "POST",
url: 'codeTime.php',
dataType: "JSON",
cache: false,
success: function (result) {
$("#count").val(result.user_code);
}
});
return false;
}
});
codeTime.php
<?php
include_once('view/database.php');
$db = new Connection();
$db = $db->dbConnect();
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT user_code FROM tbl_user";
$query = $db->prepare($sql);
$query->execute();
$num_rows = $query->rowCount();
echo json_encode(array('user_code'=>$num_rows+1));
?>
include_once. If there are recursive imports, this function will make sure they are only imported once, but you really should have your connection as a global and not create a new connection every single time you refresh. Just create the connection to the database initially and when you refresh, just make a new mysqli_query($connection, $query) and when you are done use mysqli_free_result($query).