so I currently have this PHP script to get the Youtube IDS set in a mySQL database. This PHP script lists all the Youtube ID's in the database.
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "songrequests";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "song: " . $row["link"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Ok, and after that, I found this script that pushes Youtube IDs to a playlist, this is found here on jsFiddle (Full demo here)
So basically, what I am trying to achieve is to push the IDs from my database to the list. I created a json which lists all of the IDs here
With this ajax I'm trying to push the ID's from the json to the list, but it does not seem to work.
JS
$.ajax({
url: 'http://dj.aotikbot.tv/songlist.php',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data.songs.length);
if (data.songs.length != 0) {
for (var x = 0; x < data.songs.length; x++) {
ytplayer_playlist.push("'" + data.songs[x].link + "'");
}
}
},
error: function() { console.log('Uh Oh!'); },
});
If you need more info on what I'm trying to do, let me know. Thanks in advance.
So, based on our chat, JSONP is what you went after. The code below should work. Take a look.
var playlist = [];
$.ajax({
url: 'http://dj.aotikbot.tv/songlist.php?callback=?',
type: 'GET',
async: false, //evil, but you needed this!
dataType: 'json',
success: function(data) {
if (data.songs.length > 0) {
$.each(data.songs, function() {
playlist.push(this.link);
});
}
console.log("Here is your playlist");
console.log(playlist);
},
error: function() { console.log('Uh Oh!'); }
});
Related
I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct
Hello I want to pass this variable: ID_person to view and then send it to php script to get requested data from database.
Controller:
public function view($id){
$data = array();
if(!empty($id)){
$data['zakaznici'] = $this->Zakaznici_model->getRows($id); //$data['temperatures'] = $this->Temperatures_model->getRows($id);
$data['title'] = 'Údaje o zákazníkovi';
$data['ID_person'] = $id;
$this->load->view('zakazniciview', $data);
}else{
redirect('/zakaznici');
}
}
So far I'm using this request in my view:
<script type="text/javascript">
$(function() {
$.ajax({
url: "http://localhost/skolaa/chart_vypozicky.php",
type: "GET",
success: function(data) {
chartData = data;
var chartProperties = {
caption: "Celková suma za prenájmy počas jednotlivých rokov",
xAxisName: "Rok",
yAxisName: "Suma ",
rotatevalues: "0",
useDataPlotColorForLabels: "1",
theme: "fusion"
};
apiChart = new FusionCharts({
type: "column2d",
renderAt: "chart-container",
width: "550",
height: "350",
dataFormat: "json",
dataSource: {
chart: chartProperties,
data: chartData
}
});
apiChart.render();
}
});
});
</script>
It is working but I need to get somehow that ID_person variable from controller and sent it to chart_vypozicky.php script and then retrieve it in query in this script.
Php script:
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "root";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "";
//name of the db under which the table is created
$dbName = "prenajom_sportovisk";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$query = "SELECT SUM(cena) as price, YEAR(DATUM) as rok FROM sportoviska_zakaznici where ID= "; //I need to retrieve that id variable here
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['rok'];
$jsonArrayItem['value'] = $row['price'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
Is it somehow possible to get this done? I will be really thankful for all suggestions.
In your view pass ID_person and then Use $_GET['ID_person'] in chart_vypozicky.php page
<script type="text/javascript">
$(function() {
$.ajax({
url: "http://localhost/skolaa/chart_vypozicky.php",
type: "GET",
data:{ID_person:'<?php echo $ID_person; ?>'},
success: function(data) {
chartData = data;
var chartProperties = {
caption: "Celková suma za prenájmy počas jednotlivých rokov",
xAxisName: "Rok",
yAxisName: "Suma ",
rotatevalues: "0",
useDataPlotColorForLabels: "1",
theme: "fusion"
};
apiChart = new FusionCharts({
type: "column2d",
renderAt: "chart-container",
width: "550",
height: "350",
dataFormat: "json",
dataSource: {
chart: chartProperties,
data: chartData
}
});
apiChart.render();
}
});
});
</script>
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "root";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "";
//name of the db under which the table is created
$dbName = "prenajom_sportovisk";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$person_ID=$_GET['ID_person']
$query = "SELECT SUM(cena) as price, YEAR(DATUM) as rok FROM sportoviska_zakaznici where ID='".$person_ID."'"; //I need to retrieve that id variable here
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['rok'];
$jsonArrayItem['value'] = $row['price'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
Use this updated code
I'm aiming to display dots with javascript by their coordinates. Each person click on an image, (X,Y) will be stored in the database. On the same image will be displayed all dots, when a person is visualing the image with dots and another person will submit new dot, this last will appears because array_x and array_y tabs will be refreshed every 1s.
The question is : is it the best way in terms of using server ressources of doing that ? suppose i've 1000 persons that will participate to this study, that signify that for one person there is at least one request every 1s. Suppose that one person will spend 30s, that will be a huge amount of requests.
I am afraid to have a server breakdown due to multiple requests. Is it a way more guaranteed than this one ?
My js :
window.setInterval(loadNewPosts, 1000); //load simultaneous choice in 1 second
function loadNewPosts(){
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "latest.php",
data: "current_id=" + current_id +"&nextType=" + nextType,
success: function(data) {
for (var i = 0; i < data['array_x'].length; i++) {
array_x.push(data['array_x'][i]);
array_y.push(data['array_y'][i]);
}
}
});
}
my php latest.php :
$servername = "";
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$current_id = intval($_GET['current_id']);
$Type = (string)$_GET['nextType'];
$sql = "SELECT * FROM `table` WHERE id > $current_id and Type='".$Type."'";
$result = mysqli_query($conn, $sql);
$array_x= [];
$array_y= [];
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
array_push($array_x,$row["X"]);
array_push($array_y,$row["Y"]);
}
} else {
echo "";
}
mysqli_close($conn);
// return the posts as a JSON object
header('Content-Type: application/json');
$data=array(
'array_x' => $array_x,
'array_y' => $array_y
);
echo json_encode($data);
I have written a script i JQuery and PHP,
After the success return from PHP, AJAX function should catch a success response but I am not getting that.
Below is the code:
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
//if(data=="ok"){
if(data=="YES"){
alert("EMAIL");
}else{
alert(data);
}
//}
//if(data=="ok"){
//alert("Expenses Id already exists!");
//}else{
//alert(data);
//}
}
});
and here is the php code
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
//echo "helloooo";
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
//echo "Proceed";
}
}else{
echo "Not Okay";
}
}else{
}
}
I can see the echo value on browser and alert value also. But if condition is not working for success function???
Try set correct data type for returned data.
$.ajax({
url: 'script_admin-add-category.php',
method: 'POST',
data: {lExpensesId: lcl_ExpensesId},
dataType: 'text',
success: function (data) {
if (data === 'YES') {
alert('EMAIL')
} else {
alert(data)
}
}
})
#J Salaria as i understood your question you are having problem with jquery AJAX and PHP code as you are not getting you desired result. There are different ways to send the data through jquery ajax which i will be explain in detail.
$_POST["lExpensesId"] are you getting this ID from a HTML <form> ?.Because here i'll be showing you 3 different practiced ways to send data through ajax..
NOTE: YOUR CODE IS VULNERABLE TO SQL INJECION. I'LL BE ALSO SHOWING YOU THE METHODS TO OVERCOME.IF YOU WANT TO LEARN MORE ABOUT SQL INJECTION CLICK ON THIS LINK SQL INJECTION LINK
HTML FORM CODE :
<form action="" id="send_lExpensesId_form" method="post">
<input type="text" name="lExpensesId" id="lExpensesId" >
<input type="submit" name="submit" >
</form>
FIRST WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = $(this).serialize();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
SECOND WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = new FormData($(this)[0]);
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
contentType: false,
processData: false,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
THIRD WAY FOR SENDING DATA THIS IS USED WHEN A LINK CLICKED OR TO DELETED THROUGH ID OR CLASS
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var lcl_ExpensesId = $("#lExpensesId").val();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
HERE IT THE PHP CODE WITH mysqli_real_escape_string(); AGAINST SQL INJECTION
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "demo";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST["lExpensesId"])){
$lExpensesId = mysqli_real_escape_string($conn, $_POST["lExpensesId"]);
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
echo "Proceed";
}
}else{
echo "Error".mysqli_connect_error();
}
}
?>
HERE IT THE OTHER PHP CODE WITH MYSQLI->PREPARED WHICH IS BETTER AGAINST SQL INJECTION
<?php
// WITH MYSQLI PREPARED STATEMENT AGAINST SQL INJECTION
$sql = $conn->stmt_init();
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId =?";
if($sql->prepare($Lquery)){
$sql->bind_param('i',$lExpensesId);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0){
echo 'YES';
}else{
echo "Proceed";
}
}
else
{
echo "Error".mysqli_connect_error();
}
?>
I HOPE YOU GOT ANSWERE FOR YOU QUESTION IF YOU HAVE OTHER DOUBTS FEEL FREE AND COMMENT BELOW
All methods are known and many thanks for assistance. My question is that Why I am not able to get proper return from PHP. Below is my code:
var lcl_ExpensesId = $("#IExpensesId").val();
//alert(lcl_ExpensesId);
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data=="ok"){
alert("Inserted");
}else{
alert(data);
}
}
});
ob_start();
/------------------FUNCTION TO READ ACCOUNTS DROPDOWN EXPENSES LIST -----------------------/
require_once 'db_config.php';
$newlist = fxn_CONFIGURATION();
$HOST = $newlist[0];
$DBNAME = $newlist[1];
$UNAME = $newlist[2];
$PSWD = $newlist[3];
$conn = mysqli_connect($HOST, $UNAME, $PSWD, $DBNAME);
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
$query_result = mysqli_query($conn, $Lquery);
if(mysqli_num_rows($query_result) > 0){
echo "ok";
}else{
echo "Proceed";
}
}
}
mysqli_close($conn);
ob_flush();
As, i am using this AJAX in my one of input keyup method so whatever I will type, each and everytime, it will execute PHP script. I am having a item as FOOD in databse. When i type "F", I got Proceed, "O" - Proceed, "O" - Proceed, "D" - ok....
When I type D, i should get "Inserted" instead of Ok....
This is my doubt that why i m getting this????
The above problem is resolved by using exit() statement in PHP as I am getting five ↵↵↵↵↵ after my values and it means I am having 5 lines of html without closing ?>. So the best way to resolve the issue is to use exit() in PHP as per need
At the lessons i learn how to pass result from a sql request to js via JSON/AJAX. I need the value of the row from this request in my js but it doesnt work. Via console i have an error: Uncaught SyntaxError: Unexpected token <
part of PHP:
<?php
//get all the course from db and reply using json structure
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_hyp");
$id = $_POST['id'];
if (mysqli_connect_errno()) { //verify connection
exit(); //do nothing else
}
else {
# extract results mysqli_result::fetch_array
$query = " SELECT * FROM course WHERE course_category='$id'";
//query execution
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
$myArray = array();//create an array
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = array_map('utf8_encode', $row);
}
$response = array();
$response['rows'] = $row;
$response['query'] = $myArray;
echo json_encode($response);
}
//free result
$a=num_rows;
$result,$a->close();
//close connection
$mysqli->close();
}
?>
first part of Script:
$.ajax({
method: "POST",
//dataType: "json", //type of data
crossDomain: true, //localhost purposes
url: "./query/cate_has_courses.php", //Relative or absolute path to file.php file
data: {id: i},
success: function(response) {
console.log(JSON.parse(response));
var course=JSON.parse(response.query);
var row=JSON.parse(response.rows);
Seem you use JSON.parse in wrong way.
The JSON.parse must be done one time only. The result of JSON.parse is store in course the the access to the data is due by response.query or respons.row .. and so on and not by JSON.parse(respose.query)