Inserting a javascript code into php - php

I am searching for possibility to include a javascript function into a php code.
The code should get the results from the search php file and then print them out in form of a Javascript Playlist.
This is the javascript code:
<script type="text/javascript">
$(document).ready(function(){
var description = '';
var myPlaylist = [ {
mp3:'./../sounds/mysql-upload',
title:'mysql-title',
artist:'mysql-artist',
subcategory:'mysql-subcategory',
date:'mysql-date',
rating:'mysql-rating',
},
/* var myPlaylist has to repeat */
];
$('#main').ttwMusicPlayer(myPlaylist, {
autoPlay:false,
description:description, }
);
});
</script>
And here is the php code:
<?php
if (!empty($_POST['search'])) {
/* Connect to database */
$hostname = '';
$database = '';
$username = '';
$password = '';
if (!($mysql_link = mysql_connect($hostname, $username, $password))) {
die('Could not connect');
}
/* Select databse */
if (!($db_selected = mysql_select_db($database, $mysql_link))) {
die('Could not find database');
}
/* Send mysql command */
$sql_cmd = "SELECT * FROM sounds WHERE `keywords` LIKE '"
. $_POST['search']."%'";
if (!($res = mysql_query($sql_cmd))) {
die('Invalid MySQL query');
}
/* Show results */
while ($dsatz = mysql_fetch_assoc($res)) {
$upload = $dsatz["upload"];
$title = $dsatz["title"];
$artist = $dsatz["artist"];
$subcategory = $dsatz["subcategory"];
$date = $dsatz["date"];
$rating = $dsatz["rating"];
/* Here should be the Javascript code */
}
/* Close database connection */
mysql_close($mysql_link);
}
?>
Please note that I don't want to include the full Javascript function in the results part of the php code but the playlist variable which should repeat.

In PHP, you can make an array, and fill it with arrays of those attributes.
Something like:
$results = array();
while ($dsatz = mysql_fetch_assoc($res)) {
$results[]=$dsatz; }
$printout = json_encode($results);
Now to put it into the JavaScript, you'd do this:
var myPlaylist = <?php echo $printout; ?>;

If I understood you correctly, you'll need AJAX for doing that. Here's some places to start with:
W3Schools AJAX Tutorial
Tizag's AJAX Tutorial
Also, as you're already using JQuery, it can make your life with AJAX much easier.
Take a glance to JQuery AJAX API at http://api.jquery.com/category/ajax/

this is fairly possible, but how abt using json instead. JSON encoded string can be generated in php via json_encode($array) You can then, possibly using AJAX, load the json into the current page.
The other option is, generate javascript arrays from the php code, and then include the javascript array on to the web page.

Related

refresh a SQL query to display changes

I have the following query:
if (!isset($profile_id) || !is_numeric($profile_id))
return false;
if ( isset(self::$newMessageCountCache[$profile_id]) )
{
return self::$newMessageCountCache[$profile_id];
$filter_cond = SK_Config::section('mailbox')->section('spam_filter')->mailbox_message_filter ? " AND `m`.`status`='a'" : '';
$query = "SELECT COUNT(DISTINCT `c`.`conversation_id`)
FROM `".TBL_MAILBOX_CONVERSATION."` AS `c`
LEFT JOIN `".TBL_MAILBOX_MESSAGE."` AS `m` ON (`c`.`conversation_id` = `m`.`conversation_id`)
WHERE (`initiator_id`=$profile_id OR `interlocutor_id`=$profile_id)
AND (`bm_deleted` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_deleted` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
AND (`bm_read` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_read` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
$filter_cond AND `m`.`recipient_id`=$profile_id
";
self::$newMessageCountCache[$profile_id] = SK_MySQL::query($query)->fetch_cell();
return self::$newMessageCountCache[$profile_id];
This will return a number for any new mailbox messages, I have found an ajax code for checking if there is a change.
Code:
var previousValue = null;
function checkForChange() {
$.ajax({
url: '',
...
success: function(data) {
if (data != previousValue) { // Something have changed!
//Call function to update div
previousValue = data;
}
}
});
}
setInterval("checkForChange();", 1000);
But I really need to figure out how to update the query without refreshing the entire page? I figured maybe something with ajax can help but I am totally new to ajax and I don't have an no idea where to start.
Update: ok so I wrote a php script for the queries but not sure how to get ajax script to use my "emails" var.
here is the script.
<?php
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
die();
}
include("..\internals\config.php");
$host = DB_HOST;
$user = DB_USER;
$password = DB_PASS;
$dbname = DB_NAME;
$prefix = DB_TBL_PREFIX;
$cxn = mysql_pconnect ($host, $user, $password);
mysql_select_db($dbname, $cxn);
function get_user_id()
{
$userid = NULL;
if (!empty($_COOKIE['PHPSESSID']))
{
$result = $cxn->execute("
SELECT profile_id
FROM " . TABLE_PREFIX . "profile_online
WHERE hash = '" . $cxn->escape_string($_COOKIE['PHPSESSID']) . "'
");
if ($row = $cxn->fetch_array($result))
{
$userid = $row[0];
}
}
return $userid;
}
$profile_id = get_user_id();
public static function newMessages( $profile_id )
{
if (!isset($profile_id) || !is_numeric($profile_id))
return false;
if ( isset(self::$newMessageCountCache[$profile_id]) )
{
return self::$newMessageCountCache[$profile_id];
}
// check config for filter condition
$filter_cond = SK_Config::section('mailbox')->section('spam_filter')->mailbox_message_filter ? " AND `m`.`status`='a'" : '';
$query = "SELECT COUNT(DISTINCT `c`.`conversation_id`)
FROM `".TBL_MAILBOX_CONVERSATION."` AS `c`
LEFT JOIN `".TBL_MAILBOX_MESSAGE."` AS `m` ON (`c`.`conversation_id` = `m`.`conversation_id`)
WHERE (`initiator_id`=$profile_id OR `interlocutor_id`=$profile_id)
AND (`bm_deleted` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_deleted` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
AND (`bm_read` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_read` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
$filter_cond AND `m`.`recipient_id`=$profile_id
";
self::$newMessageCountCache[$profile_id] = SK_MySQL::query($query)->fetch_cell();
return self::$newMessageCountCache[$profile_id];
}
mysql_close($cxn);
$emails = newMessages();
?>
Ajax is correct - with Ajax you can send a request to the webserver which will execute your query and receive a request.
Its like visiting a page with the browser except that it happens in the background and not reloading the browsertab/page.
Lets say this is your file query.php and you can access it via my-domain.tld/query.php
query.php:
//First make this file only executeable for AJAX-Requests but no regular visit via browser:
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
die(); //User tried to enter query.php with a browser or similar...
}
//call function where query is stored or put your query here and save result
//Its important to echo what you want to be returned in the ajax-request.
echo self::$newMessageCountCache[$profile_id];
die(); //Best is die after last echo to make sure there are no extra outputs!
Now in your template or atleast where your HTML code is:
function checkForChange() {
$.ajax({
url: 'my-domain.tld/query.php', //See, here is the URL to your file on server
data: {}, //You need this only if you want to mpass any variables to your script. On PHP Server-side this data are available via $_POST array!
success: function(data) { //data contains all echo'ed content from query.php
$(".mailbox_messages").html(data); //The best is make your container to be updated to a class or ID to access. Its content can be overridden with .html() function. Simply echo all contents in query.php that you want to be displayed in your element and override the content with .html(data);
}
});
}
Now you just need to call checkForChange() when something special happens like a button click for example:
<input type="button" id="refresh-mailbox" value="Refresh my Mailbox" />
<script type="text/javascript">
$("#refresh-mailbox").on("click", function() {
checkForChange(); //Execute your function on button click and done!
});
</script>
I hope this helps. :)

Angular JS declare controller using data retrieved from PHP file

I have a controller declared and I was loading the data from a json file. THat was working fine, so I decided to create a database and a php file to do a select and retrieve the data from the table I am storing it.
The data from php is retrieved on json, this is my code on php:
<?php
$con = mysqli_connect("127.0.0.1", "root", "", "peopledir");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM people");
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
print json_encode($rows);
mysqli_close($con);
?>
It retrieves this:
[{"0":"1","id":"1","1":"Santiago","name":"Santiago"}]
My controller is:
'use strict';
/* Controllers */
var myApp = angular.module('myApp');
myApp.controller('PeopleController', function($scope, $http) {
$http.get('http://localhost').success(function(data) {
$scope.peoples = data;
});
});
But it is not showing any data on the frontend.
To be clear, if I paste the data to a json file, exactly as php is showing it, I can see the user Santiago on the page, but with above code, reading directly from http://localhost, I can not see anything.
Thanks
You should use mysqli_fetch_assoc:
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}

Get Data from Mysql instead XML?

hey i have this javascript for a bubble up... this script gets InfoID and InfoData tags from an xml file...
<script type="text/javascript">
$(document).ready( function ( ) {
// Get the XML data from your file
$.get('scores.xml', function( data ) {
// Because we've given jQuery the XML datatype, we can jump straight to finding the element.
$(data).find('Game').each( function ( ) {
// The current object now holds a single "GAME" - find the elements we need
var game_id = $(this).find('InfoID').text( );
var game_info = $(this).find('InfoData').text( );
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
}); // end of each
}, 'xml'); // The 'xml' tells jQuery to expect XML back from the request
});
</script>
i need to make this script get data from Database table instead of xml.
i have the same InfoID and InfoData rows in a table in my database...
i use this php script to get data from db:
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
<?php echo $row['Header'].""; ?>
<?php echo $row['Row'].""; ?>
<?php echo $row['Date'].""; ?>
<?php echo $row['Time'].""; ?>
<?php echo $row['AwayTeam'].""; ?>
<?php echo $row['Score'].""; ?>
<?php echo $row['HomeTeam'].""; ?>
<?php echo $row['Other'].""; ?>
<?php echo $row['InfoID'].""; ?>
<?php echo $row['InfoData'].""; ?>
<?php } mysql_close(); ?>
any idea how i can do that? so i can remove my xml file and use database :)
Thanks in advance.
You could use an ajax post with a seperate callback function and return json data from your php script.
Give this a shot:
// try this for your javascript
<script type="text/javascript">
$(document).ready( function ( ) {
function getGameInfo() {
$.post("path/to/phpScript.php",
// this is the success callback
function (json) {
// this calls the function with the returned data
parseReturnedData(json);
});
return false;
};
// process json data to set your game_id and game_info vars
function parseReturnedData(data) {
var obj = jQuery.parseJSON(data);
var game_id = obj.InfoID;
var game_info = obj.InfoData;
}
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
</script>
// try this for your php file
<?php
// declare vars
$response = array();
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
$response['Header'] = $Header;
$response['Row'] = $Row;
$response['Date'] = $Date;
$response['Time'] = $Time;
$response['AwayTeam'] = $AwayTeam;
$response['Score'] = $Score;
$response['HomeTeam'] = $HomeTeam;
$response['Other'] = $Other;
$response['InfoID'] = $InfoID;
$response['InfoData'] = $InfoData;
}
echo json_encode($response);
mysql_close();
?>

How to dynamically add an option to a select list that is build using json data retrieved from a php script?

I have an HTML form that builds a drop-down from json data that is retrieved dynamically on page load from a php script.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});});
});
</script></head>
<body>
<form name="index">
<select name="user_spec" id="user_spec" />
</form>
</body>
</html>
The php script fetches data from a MySQL table.
<?php
$username = "user";
$password = "********";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test"); $query =
"SELECT * FROM user_spec";
$result=mysql_query($query);
$outArray = array();
if ($result) {
while ($row = mysql_fetch_assoc($result)) $outArray[] = $row;
}
echo json_encode($outArray);
?>
I need to add functionality to it now that new options can be added dynamically from the form to the list. How can I do it? I am thinking to do it like user adds an option to a text box & presses a button. The same JSON data is modified & posted back to server that reads & stores it into database. The list is refreshed/re-drawn with this changed data.
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$("#user_spec").html("");//clear old options
jsonData= eval(jsonData);//get json array
for (i = 0; i < jsonData.length; i++)//iterate over all options
{
for ( key in jsonData[i] )//get key => value
{
$("#user_spec").get(0).add(new Option(jsonData[i][key],[key]), document.all ? i : null);
}
}
});

passing data from javascript to php using Jquery

Maybe this question has been asked before but I am struggling in doing this. I have got a php file which does not include any piece of php code (might be in the future),it includes just javascript and some html. What I want to do is clicking a button in this php file to send some amount of data to another php file.
put it this way..
1-I have got a saveProfile function in a.php and a button is calling this function
function saveProfile (){
var variableD = 'sample data';
$.post("dbConn.php", { js: variableD});
}
2-I have got another php which is called dbConn.php that receives data and stores in a database table.
I have found so many examples. I have applied them but it still does not work and is driving me nuts. I am a java programmer but new in php.
Any help is appreciated.give me some clean sample code or if you see any mistake please kindly warn me. Thanks to all in advance...
Regards.
Ozlem.
Take a look at the accepted answer to "Javascript Post Request like a Form Submit".
It provides javascript for for:
function post_to_url(path, params, method) {
...
}
I think this will do what you want.
Thanks for all the answers. I have solved the problem. The data had being passes but I was not able to handle it properly. I just add a dummy code to test it.It worked. I will upload the code after I have finished.Thanks to all.
This function is in a PHP file, but is full of JS code. The last line passes the data to another PHP file which saves the data into a database.
function saveProfile (){
var _profileId = 0;
var _profileName = document.getElementById('nameProfile').value;
var queryArr=[];
$(markersArray).each(function (index){
//alert(markersArray[index].name);
var _locationId = index;
var _locName = markersArray[index].name;
var _markerLat = markersArray[index].marker.getLatLng().lat();
var _markerLng = markersArray[index].marker.getLatLng().lng();
var locations = {
profileName: _profileName,
locationId:_locationId,
locationName:_locName,
lat:_markerLat,
lng:_markerLng }
queryStr = { "locations": locations}
queryArr.push(queryStr);
});
/*for ( var i=0; i<markersArray.length; i++){
alert(queryArr[i].locations.locationId+"--"+queryArr[i].locations.locationName +"--"+queryArr[i].locations.lat);
}*/
$.post('dbConn.php', { opType:"saveAsProfile" , data: queryArr}, showResult, "text");
}
This is dbConn.php, which is called by the saveProfile method. The data is handled as follows:
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'google_map_db';
$opType = $_POST['opType'];
//SAVE PROFILES WITH A PROFILE NAME
if(!strcmp($opType, "saveAsProfile") ){
$res = $_POST['data'];
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() );
mysql_select_db( $db_name ) or die( mysql_error() );
$queryString = "";
for($i = 0; $i < sizeof($res); $i++){
$profileName = $res[$i]['locations']['profileName'];
$locationId = $res[$i]['locations']['locationId'];
$locationName = $res[$i]['locations']['locationName'];
$lat = $res[$i]['locations']['lat'];
$lng = $res[$i]['locations']['lng'];
$sp = " ";
$queryString = $queryString . "(0 ".",'".$profileName."',".$locationId.",'".$locationName."',".$lat.",".$lng.") ";
if($i<sizeof($res)-1)
$queryString = $queryString . ", ";
}
$qInsertUser = mysql_query(" INSERT INTO `map_locations` (`profileId`, `profileName`, `locationId`, `locationName`, `lat`, `lng`)
VALUES ".$queryString." ");
if ($qInsertUser){
echo "successfully added!!!";
} else {
echo "Error";
}
}

Categories