Here is my problem, I have a AJAX function which is working on my local server but don't return anything when I put it on my online server.
Here is my code :
Here the page where I call the function showEspece() :
echo "<div class='tableau'>";
echo "<table class='tableAnimal'>\n";
echo "<thead>\n";
echo "<td class='tdAnimal'><b> Nom </b></td>\n";
echo "<td class='tdAnimal'><b> Nombre </b></td>\n";
echo "</thead>\n";
while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr class='trAnimal'>\n";
foreach ($row as $item) {
echo " <td class='tdAnimal'>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "</td>\n";
} ?>
<td class='tdAnimal' onclick="showEspece(<?php echo "'";echo $row['ESPECE'];echo "'";?>, <?php echo "'";echo $categorie;echo "'";?>,this);" ><a class='lightbox'><img src='images/loupe.png'/></a></td> <?php
echo "</tr>\n";
}
echo "</table>\n\n";
echo '</div>';
Here is the Ajax function :
function showEspece(espece, categorie, object)
{
$.ajax({
type : 'POST',
url: 'getespece.php',
data: {espece: espece, categorie: categorie },
dataType: 'json',
success: function(data)
{
alert('ok');
var tableau = data;
$('#output').html(tableau);
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
}
Here is the page call by the Ajax function :
<?php
include("/includes/connexionBD.php");
include("includes/entetepage.php");
$requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");
oci_execute($requete);
$table = "<table>\n";
$table .= "<thead>\n";
$table .= "<td><b> Nom </b></td>\n";
$table .= "<td><b> Sexe </b></td>\n";
$table .= "<td><b> Date naissance </b></td>\n";
$table .= "</thead>\n";
while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
$table .= "<tr>\n";
foreach ($row as $item) {
$table .= " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "</td>\n";
}
$table .= "</tr>\n";
}
$table .= "</table>\n\n";
echo json_encode($table);
?>
And that is what error I get on the consol :
VM1130:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.error (ajax.js:16)
at i (jQuery.js:2)
at Object.fireWith [as rejectWith] (jQuery.js:2)
at A (jQuery.js:4)
at XMLHttpRequest.<anonymous> (jQuery.js:4)
Does someone know where the problem can come from and can help me ?
Sorry fo my bad english :/
The issue here is that your JSON response is malformed, you could try getting the output JSON and put it through a linter to find where the problem actually is:
https://jsonlint.com/
I would recommend not building the HTML (your table) in PHP but building it using Javascript and injecting the data from the Ajax request into the table.
Change php response code with the following,
<?php
include("/includes/connexionBD.php");
include("includes/entetepage.php");
$requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");
oci_execute($requete);
$table = "<table>\n";
$table .= "<thead>\n";
$table .= "<td><b> Nom </b></td>\n";
$table .= "<td><b> Sexe </b></td>\n";
$table .= "<td><b> Date naissance </b></td>\n";
$table .= "</thead>\n";
while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
$table .= "<tr>\n";
foreach ($row as $item) {
$table .= " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "</td>\n";
}
$table .= "</tr>\n";
}
$table .= "</table>\n\n";
echo json_encode(array("table"=>$table, JSON_UNESCAPED_SLASHES));
?>
change ajax code with the following
function showEspece(espece, categorie, object)
{
$.ajax({
type : 'POST',
url: 'getespece.php',
data: {espece: espece, categorie: categorie },
dataType: 'json',
success: function(data)
{
alert('ok');
var tbl = $.parseJSON(data);
var tableau = tbl.table;
console.log(tableau);
$('#output').html(tableau);
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
}
Related
I possible to insert update.php?id=" . $row["id"] . " into AJAX url?
I'm trying to make async sql row updating via form. I don't have specific id, because id is called on click.
JS
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
$.ajax({
type: "POST",
url: 'update.php?id=" . $row["id"] . "',
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
PHP where update.php call is located
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
$potnik = $row["potnik"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form id='form' action='update.php?id=" . $row["id"] . "' method='POST'><input id='id' name='potnik' value='".$row["id"]."' type='hidden' /> <input id='cas' class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input id='submit' type='submit' value='Posodobi'> <label id=\"info\"></label></form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
First, you will want to fix a lot of your HTML. You have many repeating ID attributes for various HTML elements. This will cause many JavaScript issues and is incorrect syntax for HTML.
$html = ""
$id = $row['id'];
if ($row["naslov"] !== null) {
$html .= "<div class='col-6 flex-vcenter-items fs-1'>\r\n";
$html .= "\tNastavi uro\r\n";
$html .= "\t<form id='form-$id' action='update.php?id=$id' method='POST' data-id='$id'>\r\n";
$html .= "\t\t<input id='cas-$id' class='form-control fancy-border' type='text' name='posodobljeni_cas' />\r\n";
$html .= "\t\t<input id='submit-$id' type='submit' value='Posodobi'> <label id='info-$id'></label>\r\n";
$html .= "\t</form>\r\n</div>\r\n";
$html .= "</div>";
echo $html;
} else {
echo " </div>";
}
You can see a lot being done here. First we create a $html and $id variable to just make things easier. Now when we enter String data into the $html variable, if we're using " (double quote) for wrapping, we can just use $id directly in the string. We will also use ' (single quote) for wrapping all the HTML Element attributes.
Try this for your jQuery:
$(function(){
$("form[id|='form']").on('submit', function(e) {
e.preventDefault();
var form = $(this);
var id = form.data("id");
var cas = $("inptu[id|='cas']", form);
var info = $("input[id|='info']", form);
if(validate()) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
});
More Info on the selector: https://api.jquery.com/attribute-contains-prefix-selector/
Unable to test this as you have not provided a testing area. Hope it helps.
You can assign the PHP $row['id']; variable to a local JS variable and append it to the URL as shown below -
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
var id=<?=$row['id'];?>;
$.ajax({
type: "POST",
url: 'update.php?id='+id,
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
I have this script which is triggered when a button with the class .press_me is pressed.The buttons are on a column from a php generated mysql table:
$result = mysqli_query($con,"SELECT * FROM tbname");
echo "<table id='main'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='right-middle user'>" . $row['ID'] . "</td>";
echo "<td class='right-middle user'>" . $row['Nume'] . "</td>";
echo "<td class='right-middle done'>" . $row['Teme_facute'] . "</td>";
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me'>" ."</td>";
echo "<td class='right-middle undone'>" . $row['Teme_nefacute'] . "</td>";
echo "<td class='right-middle uncheck'>" . "<img src='img/uncheck.png'>" . "</td>";
echo "<td class='side-table resetDone'>" . "<img src='img/resetDone.png'>" . "</td>";
echo "<td class='side-table resetUndone'>" . "<img src='img/resetUndone.png'>" . "</td>";
echo "</tr>";
}
echo "</table>";
And the script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
And counter.php:
<?php
echo $_POST["id"];
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
I'm having trouble updating only the value on the same row as the button pressed.When i run the page in this configuration counter.php returns no id passed and i think the problem is with the passing of the row id. Can anyone help me update only the value on the row with the pressed button?
I'm aware of sql injection but it's not the main problem now
Your id is empty
try this
echo "<td class='right-middle check'>" . "<img data-id='{$row['ID']}' src='img/check.png' class='press_me'>" ."</td>";
And in the script use this
var id=$(this).data("id");
change you javascript, looks like you are not sending data at all
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php",
// add this line
data: { id: id}
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
Replace below script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo $row[ID]; ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
NOTE: I assume that you are working with single record. If not then it
will going wrong.
If this is working wrong then replace .press_me line with below:
$id = $row['ID'];
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me' id='<?php print($id);?>' >" ."</td>";
And script is like:
var id = $(this).attr("id");
Hope this help you well!
I'm sending request by $.ajax method from test.php to ajax.php page. The console shows "200 ok" that means the request is ok. But return nothing, although the console doesn't show any error.
My used pages are as following:
test.php
<div id="return-data">
<ul class="return-lists">
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$('.submit-form').click(function() {
var name = "tanvir";
var address = "Dhaka";
var cData = "name=" + encodeURIComponent(name) + "&address=" + encodeURIComponent(address);
$.ajax({
url: "ajax.php",
type: "POST",
data: cData,
success: function(data)
{
alert(data);
$('#return-data .return-lists').append(data);
}
});
});
</script>
And ajax.php
<?php
if( isset($_POST['name']) ) {
$name = $_POST['name'];
$address = $_POST['address'];
$lists = '';
$lists .= '<li>' . $name . '</li>';
$lists .= '<li>' . $address . '</li>';
return $lists;
exit;
}
I also have tried by removing if( isset($_POST['name']) ) {} and by using echo instead of return in ajax.php
Try this one. Change return $list for echo $list and no need to use exit at the end of ajax.php
<?php
if( isset($_POST['name']) ) {
$name = $_POST['name'];
$address = $_POST['address'];
$lists = '';
$lists .= '<li>' . $name . '</li>';
$lists .= '<li>' . $address . '</li>';
echo $lists;
}
Yeah, I have solved the problem by normally putting "echo" instead of "return". Because the "return" return an string and echo print an string. Thanks to all.
So, what im doing is searching for records stored in a database using AJAX, but when it prints the callback data, the first record is duplicated:
My code:
$gUser = $_GET['q'];
$connect = mysql_connect("localhost", "root", "") or die("Could not connect to the server");
mysql_select_db("socialj") or die("Could not connect to the database");
$result = mysql_query("SELECT fullname, email FROM users WHERE fullname LIKE '%$gUser%' ");
while($array[] = mysql_fetch_array ($result))
{
foreach($array as $r)
{
echo $r['fullname'].' | '.$r['email'].'<br>';
}
}
?>
JavaScript Code:
$(document).ready(function (){
$('#searchh').on('submit', function (e){
e.preventDefault();
var sVal = $('#search').val();
$.ajax({
type: 'get',
url: 'profile.php',
data: {q : sVal},
success: function (data) {
alert(data);
}
});
});
});
Could you guys help me? I don't know whats happening... Thanks.
Replace this
while($array[] = mysql_fetch_array($result)) {
foreach($array as $r) {
echo $r['fullname'] . ' | ' . $r['email'] . '<br>';
}
}
with this
while($row = mysql_fetch_array($result)) {
echo $row['fullname'] . ' | ' . $row['email'] . '<br>';
}
I dont know how to use ajax in my problem:
I have a function in php (assign) that update a temporary table in database, I want to when user user click on a button (feedback function that is defined in javascript) this function (assign) run, what should I do?
<script>
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign(1);
}
else{
assign(0);
}
}
}
</script>
<?php
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
$result = mysql_query("select * from words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
function assign($checkparm){
//mysql_query("update words set checking=$checkparm ");
mysql_query("create TEMPORARY TABLE words1user1 as (SELECT * FROM words) ");
mysql_query("update words1user1 set checking=$checkparm ");
}
mysql_close($con);
?>
<button onclick="ShowMeanings()">ShowMeanings</button>
<button onclick="feedback()">sendfeedback</button>
There is only one way to call a php function after the page is loaded:
1.ajax:
function callPHP() {
$.ajax ({
url: "yourPageName.php",
data: { action : assign }, //optional
success: function( result ) {
//do something after you receive the result
}
}
in your PHP, write
if ($_POST["action"] == "assign")
{
assign(your parameters); //You need to put the parameters you want to pass in
//the data field of the ajax call, and use $_POST[]
//to get them
}
There are many great guides on the internet. I will however suggest you get too know JQuery. It will help you on your learning curve.
function ajaxCall(){
$.ajax({
type: "GET",
url: "scripts/on/serverside.php"
});
};