passing data from javascript to php using Jquery - php

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";
}
}

Related

Sending POST data from actionscript 3.0 to PHP

I have a actionscript game that send data to a php with POST.
But I don't know how to make it working, first to get the data in php then to insert in database.
Here is the ActionScript, a part from game that send the post to php.
public function post()
{
var _loc_1:* = new ByteArray();
_loc_1.writeUnsignedInt(1);
_loc_1.writeUnsignedInt(this.Args.u);
_loc_1.writeUnsignedInt(this.Args.r);
_loc_1.writeUnsignedInt(this.Args.t);
_loc_1.writeUnsignedInt(this.Args.p);
_loc_1.writeUnsignedInt(this.apples);
_loc_1.writeUnsignedInt(this.calories);
_loc_1.writeUnsignedInt(this.StartTime);
var _loc_2:* = 0;
while (_loc_2 < this.moves.length)
{
_loc_1.writeShort(this.moves[_loc_2]);
_loc_2 = _loc_2 + 1;
}
var _loc_3:* = new URLRequestHeader("Content-type", "application/octet-stream");
var _loc_4:* = new URLRequest("http://mywebsite.com/Game.php");
_loc_4.requestHeaders.push(_loc_3);
_loc_4.method = URLRequestMethod.POST;
_loc_4.data = _loc_1;
var _loc_5:* = new URLLoader();
_loc_5.load(_loc_4);
_loc_5.addEventListener(Event.COMPLETE, this.PostCallback);
return;
}// end function
public function PostCallback(param1)
{
this.tf.text = "PHP:" + param1.currentTarget.data;
return;
}// end function
Somewhere is the this.post();(is used when game is finished and win)
This is the data what i want to get in php, is like a scores:
var _loc_1:* = new ByteArray();
_loc_1.writeUnsignedInt(1);
_loc_1.writeUnsignedInt(this.Args.u);
_loc_1.writeUnsignedInt(this.Args.r);
_loc_1.writeUnsignedInt(this.Args.t);
_loc_1.writeUnsignedInt(this.Args.p);
_loc_1.writeUnsignedInt(this.apples);
_loc_1.writeUnsignedInt(this.calories);
_loc_1.writeUnsignedInt(this.StartTime);
Page Game.php
<?php
$dbhost = 'localhost';
$dbname = 'dbname';
$dbuser = 'root';
$dbbg = 'pass';
mysql_connect($dbhost, $dbuser, $dbbg)or error("Could not connect: ".mysql_error());
mysql_select_db($dbname) or error(mysql_error());
if(isset($HTTP_RAW_POST_DATA))
{
mysql_query("INSERT INTO game (gameinfo) VALUES ('".$HTTP_RAW_POST_DATA."');");
}
?>
It insert me in database a text like with nonsense characters.. 'YPDèU"ˆ†U"~µIk€†œ«¹ãV„–' I am appreciate any hand of help.

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. :)

Fetch variable from php with javascript

I have a php file which contains the following code:
function render() {
//fetches all the data from input.
$date = date("Y-m-d H:i:s");
$con = mysql_connect("127.0.0.1","root","");
$database = mysql_select_db("guestbook");
$name = $_POST['name'];
$email = $_POST['email'];
$post = $_POST['post'];
$sql = "INSERT INTO gast(name, email, post, date) VALUES('$name','$email','$post','$date')";
$input = mysql_query($sql);
mysql_close($con);
}
With javascript, I'd like to retrieve those variables, something like this:
document.getElementById('button').onclick = clicked;
function clicked() {
var name = document.render.name.value;
var post = document.render.post.value;
var email = document.render.email.value;
}
I have included that javascript code in my body, but it doesn't work. How do I get the value?
Use AJAX. With jQuery you can get any data from the server very easy.
$.get('test.php', function(data) {
alert(data);
});
You can't really, unless the js and php code is on the same page, then you could do
var namn = "<?php echo $name; ?>";
but unless the php is passing the variables to the file that your js is in, you can't really do anything.

Inserting a javascript code into 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.

How do I get javascript to read the output of a php file

First off hello, I am new here.
My problem is that I have a php file pulling info from a database. I will post the code below.
What I need is for my JavaScript to take the output and load it into a list that generates some flash cards.
code sample `$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
$query1 = "SELECT * FROM category_tb WHERE cat_name = '$category'";
$result1 = mysql_query($query1) or die ("Error in query: $query1. " . mysql_error());
while ($row = mysql_fetch_array($result1))
{
$cat_num = $row[1];
}
// This establishes a link to MySQL
$query = "SELECT * FROM english_lang, finnish_lang ".
"WHERE english_lang.lang_id = finnish_lang.lang_id AND english_lang.cat_id = $cat_num";
$rt = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
while($nt=mysql_fetch_array($rt)){
echo "{\"english\": \"$nt[1]\", \"finnish\": \"$nt[6]\" , \"asked\": states.notAsked},";
}
`
So this basicly gets some data and formats it to be used by the javascript.
if you want to look at the output of this to get a better idea the go here
http://languagelearner.byethost2.com/vocabulary2.php
select 1 of the first 2 categories as they are the only ones with data right
now.
the javascript is this:
code sample `
var string1;
var string2;
var number;
var states = {"oneVisible": 0, "bothVisible": 1, "notAsked": 2, "asked": 3}
var state = states.bothVisible;
var numberOfWordsAsked = 0;
var words = {"list": [
]
}
function displayWords(){
if (state == states.bothVisible) {
if (numberOfWordsAsked < words.list.length) {
state = states.oneVisible;
number = Math.floor(Math.random() * words.list.length);
while (words.list[number].asked == states.asked) {
number = Math.floor(Math.random() * words.list.length);
}
string1 = words.list[number].english;
string2 = words.list[number].finnish;
document.getElementById("fin").style.display = 'none';
document.getElementById("eng").innerHTML = words.list[number].english;
document.getElementById("fin").innerHTML = words.list[number].finnish;
document.getElementById("b").value = "Show word";
document.getElementById("correct").style.display = 'none';
}
else {
document.getElementById("eng").innerHTML = "You know all the words in this category, congratulations!";
document.getElementById("fin").style.display = 'none';
document.getElementById("b").style.display = 'none';
document.getElementById("correct").style.display = 'none';
}
}
else {
document.getElementById("fin").style.display = 'inline';
state = states.bothVisible;
document.getElementById("b").value = "Wrong";
document.getElementById("correct").style.display = 'inline';
}
}
function setCorrect(){
words.list[number].asked = states.asked;
numberOfWordsAsked += 1;
displayWords();
}
//-->
</script>
`
so the output needs to go in here.
var words = {"list": [
]
Any help would be appreciated. I did not write the javascript, a friend did.
He used static info in the list.
Try AJAX. Check out http://www.w3schools.com/PHP/php_ajax_database.asp
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
alert(ajax.responseText);
}
};
ajax.open("GET", "ajax.php", true);
ajax.send(null);
outputs "hello world" when used in the same directory as a php file ajax.php:
<php
echo 'hello Word!';
?>
To put php data structures into something javascript can parse, use json_encode. That should be enough to help you on your way.

Categories