Access JavaScript variables value in php to store in mysql - php

Just simple,
I am trying to access the variable in javascript inside the php while working with elrte,
bleow is my index.php file
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>One textarea with elRTE and file upload plus one text field with elFinder</title>
<!-- jQuery and jQuery UI -->
<script src="js/jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery-ui-1.8.7.custom.min.js" type="text/javascript" charset="utf- 8"></script>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.7.custom.css" type="text/css" media="screen" charset="utf-8">
<!-- elRTE -->
<script src="js/elrte.min.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="css/elrte.min.css" type="text/css" media="screen" charset="utf-8">
<link rel="stylesheet" href="css/elrte.full.css" type="text/css" media="screen" charset="utf-8">
<!-- elFinder -->
<link rel="stylesheet" href="css/elfinder.css" type="text/css" media="screen" charset="utf-8" />
<script src="js/elfinder.full.js" type="text/javascript" charset="utf-8"></script>
<!-- elRTE and elFinder translation messages -->
<!--<script src="js/i18n/elrte.ru.js" type="text/javascript" charset="utf-8"></script>
<script src="js/i18n/elfinder.ru.js" type="text/javascript" charset="utf-8"></script>-->
<script type="text/javascript" charset="utf-8">
// elRTE with elFinder on a textarea
$().ready(function() {
var opts = {
cssClass : 'el-rte',
lang : 'en', // Set your language
allowSource : 1,
height : 450,
toolbar : 'maxi', // 'tiny', 'compact', 'normal', 'complete', 'maxi', or 'custom' (see advanced documentation for 'custom')
cssfiles : ['css/elrte-inner.css'],
fmAllow : 1,
fmOpen : function(callback) {
$('<div id="myelfinder" />').elfinder({
url : 'connectors/php/connector.php',
places : '',
lang : 'en', // Set your language
dialog : { width : 900, modal : true, title : 'Files' }, // Open in dialog window
closeOnEditorCallback : true, // Close after file select
editorCallback : callback // Pass callback to file manager
})
}
}
$('#editor').elrte(opts);
// Text field with elFinder
var opt = {
url : 'connectors/php/connector.php',
places : '',
lang : 'en',
editorCallback : function(url) {document.getElementById('field').value=url;}, // The id of the field we want elfinder to return a value to.
closeOnEditorCallback : true,
docked : false,
dialog : { title : 'File Manager', height: 500 },
}
$('#open').click(function() { // The id of the button that opens elfinder
$('#finder').elfinder(opt) // The id of the div that elfinder will open in
$('#finder').elfinder($(this).attr('id')); // it also has to be entered here.
})
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
});
})
})
</script>
</head>
<body>
<?php
$q=mysql_query("select * from aw_about_us")or die(mysql_error());
$r=mysql_fetch_array($q);
extract($r);
?>
<div id="finder"></div>
<table cellpadding="5" cellspacing="5" border="0" width="100%">
<form name="feedback" id="frm" method="post">
<tr>
<td>Title : </td>
<td><input type="text" id="atitle" size="75" value="<?=$abt_title?>"></td>
</tr>
<tr>
<td>Tag Line : </td>
<td><input type="text" id="atag" size="75" value="<?=$abt_small_line?>"></td>
</tr>
<tr>
<td colspan="2"><textarea id="editor" id="acontent" cols="50" rows="4">
<?=$abt_content?>
</textarea></td>
</tr>
<!--<input type="text" id="field" name="field" size="60"/> -->
<!--<input type="button" id="open" value="Browse..." /><br>-->
<tr>
<td><input type="submit" id="btnsub" value="Submit"></td>
</tr>
</form>
</table>
<?php
/*echo $_GET['val'];
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
*/?>
</body>
</html>
I am able to get the value of elrte inside the javascript variable, but now I wanted store this value inside the mysql database, as I am using PHP I want to access this value inside a php so that I can store it in database,
I tried using window.open("abc.php?val="+content); but the value is very large so get method cannot be acceptable here, so is there any way to get this value inside the php? or any alternate way to do this?
** Edit :**
Now it gives me a value of content variable after making following changes, but I want all 3 variables, but unable to get
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
var title = document.getElementById('atitle').val;
var tag = document.getElementById('atag').val;
alert('title'+title);
$.ajax({
type: "POST",
url: 'abc.php',
data: {title : title, tag : tag, content : content},
success: function(html) { $('result').append(html); },
dataType: 'html'
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
and php file
<?php
include('inc/conn.php');
if(isset($_POST['updabt']))
{
$cont=$_POST['updabt'];
$q1=mysql_query("update aw_about_us set abt_title='$title', abt_small_line='$tag', abt_content='$cont'") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
Now how to get all three variables??

You'll need to submit the value to your PHP script using a POST request to your server. You can do this with Ajax requests, and I believe jQuery has built-in methods for Ajax which are cross-browser.

You need 2 pages, one which will send AJAX (this you have) and one wich will respond (below):
<?php
///ajax.php
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
In javascript you create AJAX post
data['updabt'] = '';
$.ajax({
type: "POST",
url: 'ajax.php',
data: data,
success: function(html) { $('result').append(html); },
dataType: 'html'
});

You can use AJAX (easiest with a library such as jQuery) to submit the variables to another PHP script that will INSERT the values to your database.
Start by reading the following...
jQuery.ajax
jQuery.post
This is actually very simple once you get your head around the subtleties of AJAX.
Here is a simple example to get you off and running. Suppose you wanted to log something to your PHP error log...
This would be my JavaScript function:
var log = function(val) {
$.post("ajax.php", {"mode": 'log', "val": val}, function() {});
}
ajax.php would be a collection of functions, ideally a class...
public function __construct() {
$arrArgs = empty($_GET)?$_POST:$_GET;
/**
* using 'mode' I can send the AJAX request to the right method,
* and therefore have any number of calls using the same class
*/
if (array_key_exists('mode', $arrArgs)) {
$strMethod = $arrArgs['mode'];
unset($arrArgs['mode']);
$this->$strMethod($arrArgs);
}
}
protected function log($arrArgs) {
error_log($arrArgs['val']);
}
The same idea can easily be adapted to write data to a database.

Related

Make Each Row of DataTables a Hyperlink to ID

I've tried the other solutions but been unable to make it work.
How do I make each row of DataTables a hyperlink to its ENSG ID?
I've tried to do it outside the Ajax interface.
<!DOCTYPE html>
<html>
<title>Datatable Demo1 | CoderExample</title>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
var dataTable = $('#gene-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"gene-grid-data.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".gene-grid-error").html("");
$("#gene-grid").append('<tbody class="gene-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#gene-grid_processing").css("display","none");
}
}
} );
} );
</script>
</head>
<body>
<div class="container">
<table id="gene-grid" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
<thead>
<tr>
<th>ENSG ID</th>
<th>Gene</th>
<th>Biotype</th>
</tr>
</thead>
</table>
</div>
</body>
I would store the id of the row in a data attribute and then write a click handler to do this... Just remember though, datatables creates dynamic html so if setting a click event for something that is getting destroyed and redrawn, you will need to attach the handler to a parent element. I usually use the body element.
//add this option to datatables initialization
//this will add a data attribute containing the id
//to each row in table.
"rowCallback": function( row, data ) {
$(row).data('id',data.ID);
}
//handler to redirect to detail page...
$('body').on('click', 'tr', function(){
window.location = "http://svr/app/controller/action/" + $(this).data('id');
});

Passing variable using ajax and open next page

I try passing variable from one page to next using ajax.
I have running passing, but I don't know how to open page with this variable.
My actual code:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<!-- <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<button id="test" class="btn btn-lg btn-primary">Test</button>
<script>
$(document).ready(function () {
$("#test").click(function () {
var variable = 'AAAaaa';
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'view.php',
data: {"temp": variable},
success: function (data) {
alert("success!");
}
});
});
});
</script>
</body>
</html>
And second page where I want watching what is in $_Post table
<?php
$table = $_POST;
?>
<pre>
<?= print_r($table);?>
</pre>
Edit for comment:
Not a problem. You can create a callback function inside ajax's
success event. On success, take that data from view.php and send it to
the second page with another ajax call. It will all be done
asynchronously and accomplish what you're asking for. – putipong
I have array in view. For example:
$array = array(
"foo" => "bar",
"bar" => "foo",
);
How to send via post and ajax this array to controller function and open this action, when I press the button.
I tried as above , but does not work
public function actionUuuu()
{
$request = Yii::$app->request;
$array = $request->post();
print_r($array)
In your view.php, you can assign the table data to $_SESSION and then retrieve later in your second page, simply by starting a session with session_start();
A session must be started on every page that requires the use of session data, else it will not work.
view.php:
session_start();
if ($_POST['temp'] == 'AAAaaa') {
$_SESSION['tableData'] = $tableData;
echo true;
} else {
echo false;
}
return;
Javascript:
$(document).ready(function () {
$("#test").click(function () {
var variable = 'AAAaaa';
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'view.php',
data: {"temp": variable},
success: function (data) {
if (data == 'true') {
window.location.replace('secondPage.php');
}
}
});
});
});
secondPage.php
session_start();
$table = $_SESSION['tableData'];

How to create an auto-complete search in Ajax and PHP?

I am creating a basic autocomplete ajax script to fetch the mysql database search results but am unable to display the results in the php page.
I can see the data getting fetched from the database in search.php as an array, but the same doesn't get displayed in the check.php page. Is this something because of some kind of css, or some other issue?
Any suggestions would be of great help!!
Here is the code >
check.php
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<style type="text/css">
li.ui-menu-item{
font-size: 12px !important;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('#regionsearch').autocomplete({
source: 'search.php',
minLength:1
});
});
</script>
</head>
<body>
<form action="" method="POST">
Search: <input type="text" name="search" id="regionsearch"/>
</form>
</body>
</html>
search.php
<?php
$dblink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('user_information');
if(isset($_REQUEST['term']))
exit();
$rs = mysql_query('Select * from registered_users where first_name like "'.ucfirst($_REQUEST['term']).'%" order by id asc limit 0,10',
$dblink);
$data = array();
while($row=mysql_fetch_assoc($rs, MYSQL_ASSOC)){
$data[] = array(
'label'=>$row['first_name'],
'value'=>$row['first_name']
);
}
echo json_encode($data);
flush()
?>
Yes, since you are using a jquery ui plugin, you will need to embed the appropriate css.
To follow what you've already done, use this line in your html template :
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css"/>
You should as well se the doc to fetch remote data and adapt your code :
https://jqueryui.com/autocomplete/#remote-jsonp
$(document).ready(function(){
$('#regionsearch').autocomplete({
source: 'search.php',
minLength:1,
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
});

How to get value FROM Ajax in index.php

I would like to get the value sent from php via AJAX in php. But i can not get value. Where is my mistake?
It is my functions.js
$(document).ready(function(){
$(".yeni_problem").click(function(){
var uid = 1;
$.ajax({
url: 'admin.php',
type: "post",
data: {'uid': uid},
success: function(data){
// $("#cvb").text(data);
},
statusCode: {
404: function(){
alert("admin.php not found");
}
}
});
});
});
and it is my php page that, i control sending value in here. The Codes is large but i write small form. Which that when i run the small codes on other folders as other site it does't work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HELPDESK</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/css.css">
<link rel="stylesheet" href="css/default.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/icon.css">
</head>
<body>
<button class="yeni_problem">Yeni Problem</button>
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "<hr>Value not found<br/>";
}
var_dump($_POST);
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="js.js"></script>
<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript" src="bootstrap.min.js"></script>
<?php
echo "</body>
</html>";
?>
When i click to ".yeni_problem" class i can not get value.
1st- check you include Jquery
2nd- Be sure admin.php page in the same directory with file you called functions.js in if not check its path
3rd- you pass uid not data so in php use
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "Value not found";
}
?>
4th: and if you dynamically generate the element with class="yeni_problem" .. so use
$('body').on('click',".yeni_problem", function(){
instead of
$(".yeni_problem").click(function(){
5th: if yeni_problem is a submit button or anchor so you need to use e.preventDefault(); to prevent page from reloading
$(".yeni_problem").click(function(e){
e.preventDefault();
// rest of code here
6th: if yeni_problem is a form use .submit()
$(".yeni_problem").submit(function(e){
e.preventDefault();
// rest of code here
Pay attention to your code: in the JS snippet, the parameter passed to the server is "uid", which means your server will be getting a $_POST array with a position labeled "UID".
<?php
if(isset($_POST["uid"])){
echo "Value:".$_POST["uid"];
}else{
echo "Value not found";
}
?>
You should also check what is in the $_POST variable, insert var_dump($_POST) and comment out the rest of the code.

jquery cannot post with ajax php

I've got this simple script where I want to post data using AJAX to the server and then spit it out (echo), but it won't work...
This is my output:
Your viewport width is 1338x684
Ajax wasn't initialized!
And in this case, the Width and Height are only set to 880px * 495px when the PHP script doesn't get any data.
The web page head of testajax.php:
<head>
<script type='text/javascript' src='js/jquery-1.7.2.min.js'></script> <!-- Main Java library script-->
<!-- The following 3 scripts are utilized by the Accordion Menu in the aside side bar -->
<script type='text/javascript' src='js/jquery.cookie.js'></script> <!-- Acco. Menu script-->
<script type='text/javascript' src='js/jquery.hoverIntent.minified.js'></script><!-- Acco. Menu script-->
<script type='text/javascript' src='js/jquery.dcjqaccordion.2.7.min.js'></script> <!-- Acco. Menu script-->
<!--The following 2 scripts are utilized by the Pan and Zoom Slide Show -->
<script type="text/javascript" src="js/jquery.carouFredSel-6.2.1.js"></script>
<script type="text/javascript" src="js/panzoomslideshow.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Testing Ajax</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.min.css"> <!-- used to normalize-->
<link rel="stylesheet" href="css/main.css"> <!-- Main CSS styling-->
<script type="text/javascript">
document.write('<p>Your viewport width is '+ window.innerWidth+'x'+window.innerHeight+'</p>');
$(document).ready(function() {
$.ajax({
url: "ajaxresponse.php",
type: "POST",
dataType: "json",
data: {
width : window.innerWidth,
height : window.innerHeight
},
success: function( data, textStatus, jQxhr ){
$("#response pre").html( JSON.stringify( data ) );
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
</script>
<!-- ********** panzooom.php prints the java script to make a pan and zoom transition slide show, depending on the width and heigth of the viewport *********** -->
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>window.html5 || document.write('<script src="js/vendor/html5shiv.js"><\/script>')</script>
<!--<![endif]-->
<?php include 'ajaxresponse.php';?>
</head>
And here is the ajaxresponse.php file:
<?php
if (is_ajax()) {
if (isset($_POST["data"]) && !empty($_POST["data"])) { //Checks if data value exists
$data = $_POST["data"];
echo "Ajax was initialized :)<br>";
echo '<p>var_dump($_POST):<br>';
var_dump( $_POST );
}else{
"Ajax was initialized, but the value isn't set or it's empty (same same)!<br>";
}
}else{
echo "Ajax wasn't initialized!<br>";
}
//Function to check if the request is an AJAX request
function is_ajax() {
echo "\$_SERVER['HTTP_X_REQUESTED_WITH'] -> " . $_SERVER['HTTP_X_REQUESTED_WITH'] . "<br>";
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?>
Problem 1
Here you tell jQuery that when it makes the request it:
Should say that it is sending JSON
Should not convert the data you pass it into a different format
contentType: 'application/json',
processData: false,
Here you don't pass it JSON:
data: {
width : window.innerWidth,
height : window.innerHeight
},
and in the PHP:
You try to read from $_POST which won't be initilised if the request is formatted a JSON.
isset($_POST["data"]
Remove the contentType and processData configuration from your JavaScript. Let jQuery do its default of encoding the data using form encoding.
Problem 2
You are trying to read a piece of data called data:
$data = $_POST["data"];
but the only pieces of data you are sending are called width and height:
data: {
width : window.innerWidth,
height : window.innerHeight
},
You need to test for data you are actually sending.
Problem 3
You say (dataType: 'json',) you expect JSON in the response but testajax.php returns an HTML document.

Categories