I am currently trying to simply get Ajax to 'activate' a php file on wampserver
Better to show the code that explain I think
The following is a function activated by a button, the HTML/JS all works fine
var jsonString = "";
function jsonconversion(){
jsonString = JSON.stringify(myArr);
return jsonString;
console.log(jsonString);
$.ajax({
type: "POST",
url: "http://xx.xx.xx.xx:80/xx/index2.php",
data: jsonString,
complete: function() {
console.log("Success");
},
error: function() {
console.log("Function: forward_to_server() error")
}
});
}
However, I can't seem to access the php file. For ease, I am not even using the jsonString in the php file, instead I am simply trying to post some integers into a database on wamp. The php file loaded by itself works fine
<?php
$servername = "localhost";
$username = "root";
$password = "xx";
$dbname = "xx";
//$myArray = $_REQUEST['jsonString'];
$myArray = array(100,1,19);
$con = mysqli_connect($servername,$username,$password ,$dbname) or die ("could not connect database");
echo $myArray;
$keys = array_keys($myArray); // get the value of keys
$rows = array(); // create a temporary storage for rows
foreach($keys as $key) { // loop through
$value = $myArray[$key]; // get corresponding value
$rows[] = "('" . $key . "', '" . $value . "')";
// add a row to the temporary storage
}
$values = implode(",", $rows); // 'glue' your rows into a query
$sql = "INSERT INTO php_test (temp, sound, light) VALUES (10,20,30)"; //. $values
$rs = mysqli_query($con,$sql) or die(mysqli_error($con));
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
?>
However when I call the function in phonegap, it doesn't seem to work, I have no errors either which is hurting the process :(
Wamp server is 'online' and I can access it from the internet.
Any guidance on this?
Thanks in advance
Related
Try to adopt JSON in database because i have data not fixed.
i can query well from terminal, and need to write same query to php script.
i have spent a lot of time before ask.
example:
sqlite> select json_extract(events.interni, '$') from events WHERE id='35';
output
[{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
where id = 35 will become a variable of $ _POST ['id']
what I tried:
$result2 = $db->query("select json_extract(events.interni, '$') from events WHERE id='35'");
var_dump($result2->fetchAll(PDO::FETCH_ASSOC));
return [] <- empty array
i want instead = [{"student_id":"21","student_name":"Rafael Royal"}]
where did I go wrong?
I followed this answer on SO https://stackoverflow.com/a/33433552/1273715
but i need to move the query in php for an ajax call
possibile another help.
Can the result fron $ajax call can be usable as key value or remain string?
in other hands i can convert string to object like students = new Object()?
eaxaple of what i need in js environment
- count objects in array
- and loop key value
var data = [{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
consolle.log(JSON.Stringify(data));
here I would like to avoid the backslash
consolle.log(JSON.Stringify(data.lenght));
in this phase the desired data is = 2
any possible help is largely appreciated
UPDATE
leave json_extract() function i have solved the second problem, so now i can work whit object property, and finally important to count objects in array:
<?php
try {
$db = new PDO('sqlite:eventi.sqlite3');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
echo $e->getMessage();
}
$risultato = $db->query("SELECT * FROM events WHERE id = '35'", PDO::FETCH_ASSOC);
$result = array();
foreach ($risultato as $row) {
$result[] = $row;
}
// echo "Results: ", json_encode($result), "\n"; this produced backslash
echo $result[0]['interni'];
?>
js part
var num='';
$.ajax({
url: "sqlitedb/test-con.php",
type: 'POST',
dataType: 'json',
success:function(result){
console.log(result[0].student_id+ " - "+ result[0].student_name); // output here is good: 12 - Lisa Ochoa
counter(Object.keys(result).length);
}});
function counter (numero){
console.log("num2: =" + numero);
}
//out put here: 2
perfect!
odd behaviour:
console.log(result[0].student_id+ " - "+ result[0].student_name);
12 - Lisa Ochoa
outup is right but
console.log(result.lenght);
output is null
You can try something like this. and since you said in the comment about approaching it with ajax. I have included that also.
I also include php mysql backend workability for clarity. so Yo have now two options
1.) PHP WITH MYSQL
2.) PHP WITH SQLITE as you requested
index.html
<script src="jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: 'get',
url: 'data.php',
dataType: 'JSON',
cache:false,
success: function(data){
var length = data.length;
for(var s=0; s<length; s++){
var student_id = data[s].student_id;
var student_name = data[s].student_name;
var res = "<div>" +
"<b>student_id:</b> " + student_id + "<br>" +
"<b>student_name:</b> " + student_name + "<br>" +
"</div><br>";
$("#Result").append(res);
}
}
});
});
</script>
<body>
<div id="Result" ></div>
</body>
In mysql database you can do it this way.
<?php
$host = "localhost";
$user = "ryour username";
$password = "your password";
$dbname = "your bd name";
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
echo "cannot connect to db";
}
$return_arr = array();
$query = "SELECT id, student_id, student_name FROM events where id='35'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
?>
So with sqlitedb something like this will work for you
$return_arr = array();
$result2 = $db->query("SELECT id, student_id, student_name FROM events where id='35'");
$result2->execute(array());
//$result2 = $db->query("SELECT * FROM events where id='35'");
//$result =$result2->fetchAll(PDO::FETCH_ASSOC));
while($row = $result2->fetch()){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
You are surrounding you query with double quotes but inside the query there is an unescaped $.
Try escaping it:
$result2 = $db->query("SELECT json_extract(events.interni, '\$') FROM events WHERE id='35'");
var_export($result2->fetchAll(PDO::FETCH_ASSOC));
I am having a problem trying to get around a "parsererror" that is returned from my ajax request, despite a response in devtools which is an array of strings. I have a click event that makes an ajax request to pull in information from a database. The result in dev tools is:
1["1","admin","admin#admin.com","test","2017-01-11 00:00:00"]
I was expecting it to be a json object { }.
The code I wrote for the click event is:
$('#viewProfile').on('click', function() {
$.ajax({
type: 'GET',
url: 'api.php',
data: "",
cache: false,
dataType: 'json',
success: function(data) {
var id = data[0];
var name = data[1];
$('#userDetails').html("<p>ID: " + id + " Name: " + name + "</p>");
},
error: function(request, error) {
$('#userDetails').html("<p>There was a problem: " + error + "</p>");
}
});
});
The php I wrote for api.php
session_start();
echo $_SESSION['user_session'];
//DECLARE VARS FOR DB
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
$db_tablename = "tbl_users";
//CONNECT TO DB
include 'dbconfig.php';
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
$dbs = mysqli_select_db($db_con, $db_name);
//QUERY DB FOR DATA
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
$array = mysqli_fetch_row($result);
//RETURN RESULT
echo json_encode($array);
I have tried in api.php to use json_encode($array, JSON_FORCE_OBJECT) along with changing the datatype to HTML, which obviously did not work. In short, my goal was to be able to fire the click event, send an ajax request to retrieve information from the database, based on the user id then return that to the #userDetails id on the page. I am stuck trying to get around the array of strings that seems to be the roadblock for me.
Remove this line:
echo $_SESSION['user_session'];
and change this:
$array = mysqli_fetch_row($result);
to this:
$array = mysqli_fetch_assoc($result);
EDIT: you should also be checking for success/failure of your various db-related statements:
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("there was a problem connecting to the db");
$dbs = mysqli_select_db($db_con, $db_name) or die("Could not select db");
and also
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
if (!$result) {
die("query failed");
}
This needs to be removed echo $_SESSION['user_session'] it is getting returned to ajax call and because it is on json the return is incorrect.
I have a variable in php file reg.php. I want to send that variable into .js file in different place (app.reg.js). I tried a lot of solutions but they didn't work. I have to admit that I'm a new programmist, and this is my first own project in angularjs.
How my app exactly works :
In index.html i use routing to get to register.html (this working well).
register.html has a form app.reg.js sending it into reg.php
App.reg.js :
http://www.chopapp.com/#kpwad4zs (i'm getting ALL THE TIME "your post is not properly formatted as code -.-).
reg.php (it works fine! Just need variable $loginExist from it :
http://www.chopapp.com/#yvqivk5m
I would like to send variable from reg.php to the app.reg.js file. How to do this? I think i tried all of the solutions from here but non of them worked...
php file
session_start();
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$login = $request->login;
$password = $request->password;
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connect = new mysqli($host,$db_user,$db_password,$db_name);
if($connect->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
} else {
//Does login exist?
$result = $connect->query("SELECT id FROM `users` WHERE login = '" . mysql_real_escape_string($login) . "'");
$login_count = $result->num_rows;
if($login_count>0) {
$loginExist = true;
}
else {
$loginExist = false;
$password = $login . $password;
$password = password_hash($password, PASSWORD_DEFAULT);
//$sql = "INSERT INTO users (login, password) VALUES ('$login','$password')";
$sql = "INSERT INTO users (login, password)VALUES('" . mysql_real_escape_string($login) . "', '" . mysql_real_escape_string($password) . "')";
if($connect->query($sql) === TRUE) {
echo "ok!";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
$connect->close();
}
} catch(Exception $e) {
echo 'Server error!';
}
echo json_encode(['res' => $loginExist]);
?>
js file
app.controller('regCtrl', function ($scope, $window, $http) {
$scope.send = function () {
var form = {
password: scopeToPasswordImput,
login: scopteToLoginImput
};
$http({
url:'reg1.php',
method: "POST",
data: form
}).then(function (response) {
if (response) {
//I Want to use php variable in this section
//$window.alert("");
console.log(response.data.res);
} else {
console.log("Network response was not ok.");
window.location.href = '/';
}
})
};
});
I have created a table with popup unabled editing with xeditable plugin and trying submit my data with ajax call to the database. The following is my table row code:
echo "<td>" . $row['loan_status'] . "</td>";
I have tried debugging and in the Network tab of firefox I could see the data being posted as follows :
Form Data:
name : "loan_amount"
value: "2000"
pk: "1"
but the response from the post.php is this field is required . Here is my post.php code
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
/*
Check submitted value
*/
if(!empty($value)) {
$result = mysql_query('update k_loans set '.mysql_escape_string($name).'="'.mysql_escape_string($value).'" where loan_id ="'.mysql_escape_string($pk).'"');
print_r($_POST);
} else {
echo "This field is required!";
}
My jquery code for th xeditable plugin is as follows:
$(document).ready(function() {
//toggle `popup` / `inline` mode
$.fn.editable.defaults.mode = 'popup';
$('#loan a').editable({
type: 'text',
name: 'loan_amount',
url: '../payments/post.php',
title: 'Enter amount',
ajaxOptions: {
type: 'put'
}
});
});
But i am unable to understand the issue as the query seems perfectly fine to me , still the database is not getting updated .
Anyone who can guide me in the right direction . Thanks
The first issue with the script provided by the xeditable on their github uses mysql which is not safe to use these days . So I have shifted all of them to use mysqli. Here is the working code for anyones reference :
<?php
$server = "localhost";
$username = "user";
$password = "pass";
$database = "db";
$con = new mysqli($server,$username,$password,$database);
if (!$con){
die('Could not connect: ' . mysqli_connect_error($con));
echo "Cudnt cnnect";}
else{
echo "connected";
}
var_dump($_POST);
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
/*
Check submitted value
*/
if(!empty($value)) {
if ($result = mysqli_query($con,'update k_loans set '.mysqli_real_escape_string($con,$name).'="'.mysqli_real_escape_string($con,$value).'" where loan_id ="'.mysqli_real_escape_string($con,$pk).'"'));
{
echo "Update successful";
}
mysqli_close($con);
print_r($_POST);
} else {
echo "This field is required!";
}
?>
I have a MYSQL table that has a column defined as TEXT, when i reading the contents into PHP the result is that the data is not being pulled through.
my php code
SELECT establishments.name AS estName,
establishments.address AS estAddr,
establishments.telephone_num AS estTel,
establishments.description AS estDesc,
establishments.Logo AS estLogo,
establishments.title AS estTitle
FROM bucurestideals1.establishments
WHERE establishments.establishment_id ="'.$est_id.'"';
The table row has data so this is not an issue, i am reading the data using php as below:
$.ajax({
type: 'GET',
url: pass_url,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
// Assign the returned data to the page
$.each(data, function(i,item)
{
alert(item.estDesc);
});
},
Update: PHP Code
<?php
header('Content-type: application/json');
$est_id = $_GET['id'];
$server = "*";
$username = "*";
$password = "*";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$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) . ');';
?>
You can probably remove the quotes from your where statement. If that is not the issue, can you post the php code that you use to execute the sql?