I am implementing tags feature in my project.
In my demo tags i found they are passing names in a javascript function for the autocomple.
This is a function in my demo project,
<script>
$(function()
{
var sampleTags = ['c++', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
..................
.................
So , i want pass values from my php controller to this function ,inorder to get the autocomplete value from my database table
For example i am getting tags values from my db in my Controller like this:
` $data["query"] = $this->ordermodel->fetch_orderlist();`
$this->load->view('tagpage', $data); //loading my page tag page where above function exists
Now how can i pass that $data["query"] values into the above javascript function?
Please help
You could echo the variable onto the page using PHP's json_encode. This function will convert a PHP array or object into a JSON object, which JavaScript can work with:
<script>
$(function() {
var sampleTags = <?php echo json_encode($query); ?>;
})();
</script>
But a better way would be to request these values via Ajax. Say you have a PHP script named values.php:
<?php
#...
#assign $query here
#...
echo json_encode($query);
Then, in JavaScript (on the page where you want to use the sampleTags variable), you can use jQuery's .ajax function to make an easy Ajax request:
<script>
var sampleTags;
$.ajax({
url: 'values.php'
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
</script>
I haven't tested this example. Obviously you'll want to tweak it to fit your environment.
You will have to write an ajax function for this
$.ajax(
url : "<?php echo site_url('controller/method')?>",
type : 'POST',
data : 'para=1',
success : function(data)
{
if(data){
var sampleTags = data;
}
}
);
Just echo your php variable
$(function()
{
var sampleTags = '<?php echo $data["query"]; ?>'
Related
I am trying to pass a string from a query into a javascript function.
An integer will pass into the function but string will not.
echo "<a href='#' onclick='delete_game({$title});'
class='btn'>Delete</a>";
<script type='text/javascript'>
function delete_game(title){
var answer = confirm('Really?');
if(answer){
window.location = 'delete.php?id=' + title;
}
}
</script>
I expected the javascript function to be executed, but instead nothing happens.
Why don't you use ajax for this? As mentioned in comments mix PHP/JS isn't good.
In your HTML, you can do something like
I'm assuming that you are using Blade.
Delete Game
Then in your javascript, you do this using jQuery:
function deleteGame(title){
var answer = confirm('Really?');
if(answer){
$.ajax({
url : "your-php-file.php",
type : 'post',
data : {
title : title
}
})
.done(function(msg){
$("#result").html(msg);
})
.fail(function(error){
console.log(error);
});
}
}
In your PHP you process receiving the data from post $_POST
$title = $_POST['title'];
You can understand better the Ajax function of jQuery here.
A few things:
I would change window.location to window.location.href
Change your echo to:
echo "Delete";
Check if $title is set
var_dump($title);
If you'd like to make it a bit cleaner and are prepared to use jQuery:
Delete
<script type='text/javascript'>
$(document).on('click', '#delete', function () {
var title = $(this).data('title');
var answer = confirm('Really?');
if (answer){
window.location.href = 'delete.php?id=' + title;
}
});
</script>
I am new to javascript and I've searched this question everywhere but no suitable answer.
I have a "code.php" page as
$query = "SELECT * FROM users WHERE id=1";
$result= mysqli_query($con,$query);
$row=mysqli_fetch_array($result);
echo $row[1];
On the other side in "index.php" i have
<h1>"the value for number is: " <span id="myText"></span></h1>
function myFunction() {
document.getElementById("myText").innerHTML = $row[1];
}
I want to load the value of $row[1] from code.php to index.php.
I know that i have to use ajax but how?
In index php use ajax to get data from code php.
this is example :
<script>
$.ajax({
url: 'code.php',
type:'get',
success:function(data){
$("#myText").html(data);
}
});
</script>
<script>
$(document).ready(function(){
$.ajax({
type:'get',
url:'code.php',
success:function(response){
// ajax will assign the result of code =,php into response
document.getElementById("myText").innerHTML = response; //response;
}
});
});
</script>
Place this at header of your index.php
You can find more tutorials on line to get more understanding of ajax
dont forget to download jquery and embed it your code
https://jquery.com/download/
Or u can copy this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)
I am working on an application where I fetch data from database and process it using javascript/jquery like this:
$sqlEdit = "select revisionContent from tbl_revision where revisionId='".$_SESSION['contentId']."'"; //Query to fetch the result
$rsEdit = $dbObj->tep_db_query($sqlEdit);
$resEdit = $dbObj->getRecord($rsEdit);
$IdLessContent = $resEdit['revisionContent'];
<script language="javascript">
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
I get the required data in viewContent.I want to display it on the page in this section
<div id="mainWrap" onClick="fnDestroyEditable();">
<?php echo $resEdit['revisionContent']; ?> //THis is the unprocessed data displayed directly from database.I want to display the processed data here
</div>
I know we cannot get javascript variables to PHP as both are different (one server side and other client). But then how can I achieve this in my scenario?
EDIT I would like to add that the returned data is HTML stored in the database.So,I get the html->process it(add id attribute)->want to return back after processing
you can put the viewContent inside #mainWrap using javascript.
just make sure the DOM is loaded wrapping your js code with $(document).ready()
and add:
$('#mainWrap').html(viewContent);
at the end of your function.
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
});
if you need to send back info to the server you have to do it with ajax.
I added a javascript function addId() that will be invoked on click on one of the elements.
the new code is:
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
$('#mainWrap .addId').children().click(function({
addId(this);
}));
}
addId = function(elem){
// elem is the child element you clicked on
// $(elem).attr('id') should be "com-[randomString]"
$.ajax({
type: "POST",
url: "path/to/php/script", // update id PHP script
data: data, // whatever you need in json format
dataType: "json",
error: function() {
// error function you want to implement
errorFunction();
},
success: function(resp) {
// do whatever you need with the response from you PHP action
}
});
};
if you need to to call server with out human interaction just substitute
$('#mainWrap .addId').children().click(function({
addId(this);
}));
with:
$('#mainWrap .addId').children().each(function({
addId(this);
}));
if I undesrstand you, you shold only add in the end of your js code this line:
$('#mainWrap').html(viewContent);
If you want to send JS data to PHP, you should use ajax request.
I have a link that looks like this:
<p class="half_text">
<?php echo $upvotes; ?>
<strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a></strong> |
<?php echo $downvotes; ?>
<strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#">Vote Down</a></strong>
</p>
and I have the jQuery code that looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.vote_up').click(function()
{
alert("up");
alert ( "test: " + $(this).attr("problem_id") );
// $(this).attr("data-problemID").
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
//Return false to prevent page navigation
return false;
});
});
</script>
How can I get the parameter value which is problem_id ? If I add a url in the href parameter, I think the browser will just go to the url, no? Otherwise - how can I pack parameter values into the jQuery?
Thanks!
Because your $.ajax is defined in the same scope of the variable, you can use problem_id to obtain the variable value.
An overview of your current code:
var problem_id = "something"; //Defining problem_id
...
$.ajax(
...
success: function(){
...
//problem_id can also be accessed from here, because it has previously been
// defined in the same scope
...
}, ...)
....
If what you're trying to figure out is how to embed the problem ID in the link from your PHP so that you can fetch it when the link it clicked on, then you can put it a couple different places. You can put an href on the link and fetch the problem ID from the href. If you just do a return(false) from your click handler, then the link will not be followed upon click.
You can also put it as a custom attribute on the link tag like this:
<a class="vote_up" data-problemID="12" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a>
And, then in your jQuery click handler, you can retrieve it with this:
$(this).attr("data-problemID").
do you mean, getting variables from the php page posted?
or to post?
anyway here's a snippet to replace the $.ajax
$.post('/problems/vote.php', {problem_id: problem_id, action: 'up'}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
{problem_id: problem_id, action: 'up'} are the variables posted... use $_POST['problem_id'] and $_POST['action'] to process..
use simple variables names with jQuery.data and make sure you have latest jQuery..
let me try to round it up..
up
down
<script type="text/javascript">
$('.votelink').click(function() {
$.post('/problems/vote.php', {problem_id: $(this).data('problemid'), action: $(this).data('action')}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
});
</script>