I want to delete a row from my html page
I am using this function
function delete_row(no)
{
var row=document.getElementById("frm"+no).value;
var data= {};
data.row = row;
$.ajax({
url: 'delete_formation.php',
type: 'POST',
data: data,
success: function(output){
//alert(output);
}
});
document.getElementById("row"+no+"").outerHTML="";
}
My delete_formation.php contains a php script to delete that row in my sql database :
<?php
/* Connexion à une base MySQL avec l'invocation de pilote */
$pdo = 'mysql:dbname=TDW;host=127.0.0.1';
$user = 'root';
$password = '00000000';
try {
$pdo = new PDO($pdo, $user, $password);
} catch (PDOException $e) {
echo 'Connexion échouée : ' . $e->getMessage();
}
$d=$_POST['row'];
try {
// sql to delete a record
$sql = 'DELETE FROM Types_formation WHERE type_id="'.$d.'"';
echo $sql ;
// use exec() because no results are returned
$pdo->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}?>
This is not working, and it seems that my js script is not getting that text where id="frm1" (for exemple)
Using var row=document.getElementById("frm"+no).innerText;
instead of var row=document.getElementById("frm"+no).value; will solve this problem
I think you are pass value in ajax data variable and you get data $_post['row'] but you need $_post['data']['row'].
If this is not work than I will give full example.
Related
How can I iterate through the object sent back from the php script below in my jquery/ajax call?
I tried result[0] whiche gave me back c. That means that I'm being returned a string.What code should I write to be returned company1 etc. ?
DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;
CREATE TABLE company(
name VARCHAR(255),
id INT PRIMARY KEY AUTO_INCREMENT
);
INSERT INTO company(name) VALUES( 'company1');
INSERT INTO company(name) VALUES( 'company2');
INSERT INTO company(name) VALUES( 'company2');
$.ajax({
type: "GET",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
//console.log(response[0]; -> log Company1
//console.log(response[1]; -> log Company2
}
});
<?php
//manager-get-company.php
$hostname = 'localhost';
$username = 'root';
$password = '';
$database_name = 'test';
$con = mysqli_connect($hostname,$username,$password,$database_name);
//Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
echo $row['name'];
}
In ajax add dataType : "json",
$.ajax({
type: "GET",
dataType : "json",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
if(!response.error){
console.log(response[0]);
}
}
});
In php
$result = [];
//Check connection
if (mysqli_connect_errno()) {
$result['error'] = "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
$result[] = $row['name'];
}
}
echo json_encode($result);
Edited : use $result['error'] not result['error']
I have a problem, clicking in a < tr > of a table I call a javascript function which in turn calls a function in php to get data in a database. The click on the table row works, sql works, and from the console.log command I know there is an answer in reponseText. but it does not work and I get the error back, I'll post the code. I hope you can help me.
file config.php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
file cards.php
<?php
class card
{
private $_db;
function __construct($db){
$this->_db = $db;
}
public function view_card_id($id)
{
$rows = array();
$statement = $this->_db->prepare('SELECT * FROM card_details WHERE card_id = :card_id');
$statement->execute(array(':card_id' => $id));
$numrows = $statement->fetch(PDO::FETCH_ASSOC);
if($numrows < 1) {
$this->error = "Error";
return false;
} else {
$statement->bindColumn("card_id", $cid);
$statement->bindColumn("a", $a);
$statement->bindColumn("b", $b);
$rows[] = array('card_id' => $numrows['card_id'], 'a' => $numrows['a'], 'b' => $numrows['b']);
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$row = array('card_id' => $cid, 'a' => $a, 'b' => $b);
$rows[] = $row;
}
return $rows;
}
}
file index.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
?>
html code ....
<script src="/js/Cards.js" type="text/javascript"></script>
file Cards.js
$('#table-cards tr').click(function() {
var id = $(this).find("a").text();
$.ajax({
type: 'POST',
url: '/classes/cardsFunc.php',
dataType:'text',
data: {functionname: "view_card", id: id },
success: function(response){
//Use response
alert("Server echo: "+response);
console.log(response);
},
error: function(msg){
console.log(msg);
alert("Error: "+msg);
}
});
});
In the Cards.js file, once the $ .ajax function is called, it does not return to success but to error, but in the console.log I see the array of the executed query under the responseText entry.
that is, in the error response, I see the result of the query, which in theory should be in the response of success.
I also tried to use
$.post('/classes/cardsFunc.php', { functionname: 'view_card', id: id }, function(data){
});
but nothing
file cardsFunc.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>
thank you for the time you have dedicated to me
I noticed that if I recreate the connection to the db in the file cardsFunc.php, everything works, but I do not understand why, since everything is in the config.php file.
Like this:
file cardsFunc.php
<?php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>
So I'm building a mobile (cordova) app using a mySQL server, PHP, javascript (jQuery) but I have encountered a rather annoying problem.
When sending a test string with AJAX the recieving end, a PHP script does not receive all the data:
function testJson() {
$.ajax({
type: 'POST',
data: {
text: "hello, this is a test to see if the string is send."
},
url: 'http://a.working.url/save.php',
success: function(data) {
alert('succes');
},
error: function(data) {
alert('There was an error adding your comment');
}
});
return false;
}
then at the serverside I have a small PHP script:
<?php
$server = "localhost:3307";
//changed port to 3307
$username = "user";
$password = "pass";
$database = "test";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$comment = $_POST['text'];
echo $comment;
$sql = "INSERT INTO data (comment) ";
$sql .= "VALUES ('$comment')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
but this PHP script did not recieve the full string, when I check using:
echo $_POST['text']
It only got: "hello, this is a test to see if the" (without quotes).
If anybody can help me it would be great cause I cannot continue working on the app unless the data transfer works.
Thanks in advance.
I have a question re. receiving data from php-function to ajax.
Ajax (in html-file):
function showUser(name) {
$.ajax({
type: 'POST',
url: '/api.php',
data: {
name : "\""+name+"\"",
func_id : "1"
},
dataType: 'json',
success: function(data)
{
if (data == null) {
console.log("Something went wrong..");
} else {
console.log(data);
Php (separate php-file):
<?php
error_reporting(E_ALL);
//MySQL Database connect start
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";
$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end
$func_id = $_POST['func_id'];
function showUser() {
global $con;
$name = $_POST['name'];
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
if ($func_id == "1") {
showUser();
}
?>
The question: Everything works if I don't have the showUser-function in the php, i.e. I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax.
Is there a fix for this?
Thanks!
The reason may be that the variables inside a function're visible only for function itself. Try this way:
$name = $_POST['name'];
function showUser($name) {
global $con;
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.
I have this PHP:
function getList() {
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array('result' => $result));
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
and this javascript:
$.ajax({
type: 'GET',
url: rootURL + '/' + myAPI,
dataType: "json",
success: function(list) {
var list = list.result;
console.log (list);
}
error: function( jqXHR, textStatus, errorThrown ) {
console.log (" errors: " );
console.log (jqXHR);
console.log (textStatus);
console.log (errorThrown);
}
});
now everything was working fine until I added some rows in the list table of my DB.
So now the js list result from AJAX is empty:
{"result": }
The error I receive from AJAX is:
Object { readyState=4, status=200, statusText="OK", more elements...}
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
so I tried to remove: dataType: "json", but result is still empty.
the only way to make it works is to limit the SQL query like this:
$sql = " SELECT * FROM list LIMIT 9 ";
and it works:
{"result":
[
{"ID":"1","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"2","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"3","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"4","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"5","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"6","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"7","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"8","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"9","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
]
}
I don't understand why there is such a limit. I also tried:
$sql = " SELECT * FROM list LIMIT 10 ";
and so on, but the result is still empty:
{"result": }
Can you help me please?
Thanks
Read the manual at http://php.net/json_encode. It says:
All string data must be UTF-8 encoded.
Make sure your data is in UTF-8 encoding in the database. If not you have to convert it first.
If it is working with LIMIT 9 and not working with LIMIT 10 so problem is in your records after 9th row so please check your 10th row It may have any 'special character', 'new line character' which is creating problem.
There are 2 points I'd like to point out in your code to have a look at. First of all, the construction of the error should be using the json_encode function, which will ensure valid format, so instead of doing echo '{"error":{"text":'. $e->getMessage() .'}}'; you should do
$response = new stdClass();
$response->error = new stdClass();
$response->error->text = $e->getMessage();
echo json_encode($response);
Note, that it looks overly complex, but I tried to retain the format you specified in your example.
The other thing is that Javascript will not like type: 'json' if the correct headers are not set. So what I suggest your PHP function should look like is this:
function getList() {
$response = new stdClass();
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$response->result = $result;
unset($db);
} catch(PDOException $e) {
$response->error = new stdClass();
$response->error->text = $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($response);
exit();
}
I hope this helps!