user types something in input, it calls ajax defining it to go on some function in controller. then according to that input it should short list the table rows, matching it with 2 or 3 columns of that database. i have working code of this in simple php. which calls ajax and display the output from another page that ajax calls in the script. but i need it to work in codeigniter. i'm not sure how will i get this working. Any help or advice?this is the function that ajax calls on input change. i've tried to convert my simple php working page code into codeigniter. + i'm calling brandlookup1 which is another page then my current page. any syntax error or best practice? for this kind of issues.
You should try this:
In Controller
function fetch_brands(){
$search = $this->input->post('query');
$data['record1] = $this->Model_Name->Function_Name($search);
}
In Model
function Function_Name($search){
$this->load->database();
$search = $this->db->escape_str($search);
$sql = 'select * from brand where brand like "%'.$search.'%" OR description like "%'.$search.'%" OR status like "%'.$search.'%"';
$query = $this->db->query($sql);
return $query->result();
}
Related
I am trying to connect usetiful to my WordPress Backend.
I need to tag the users and pass information to Usetiful for further personalization.
After going through various similar Q/A threads, I managed to retrieve and pass the User ID to Usetiful, but having trouble getting the User First Name.
Here is the Code Snippet that I am using (Adding code to the Code Snippets Plugin)
<script>
window.usetifulTags = { userId : <?=get_current_user_id() ?>, firstName : <? $user_info = get_userdata(get_current_user_id());$first_name = $user_info->first_name;return $first_name;?>;};
The get_current_user_id() works well, but unable to get the User First Name/Display Name
Since this is a text, you need to wrap some quotes around it and you should make sure your PHP is a proper value to be evaluated. If you have more operations to be performed, then it is to be recommended to implement a function and only call the function.
<script>
window.usetifulTags = { userId : <?=get_current_user_id() ?>, firstName : "<? $first_name = get_userdata(get_current_user_id())->first_name ?>"};
I need Help on this, base on what I already did: In the output every time I click the button it shows the row (comments) in database. But I want that If I click the next button it will show the row (comments) in the database and when I click it again It will delete the previous row (comments) in the database and show the next row (comments).
Here is the code:
<?php
include 'dbh.php';
$commentNewCount = $_POST['commentNewCount'];
$sql = "SELECT * FROM comments LIMIT $commentNewCount";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['id'];
}
} else {
echo "There are number!";
}
?>
This is for the button:
<script>
//jQuery code here!
$(document).ready(function() {
var commentCount = 0;
$("button").click(function() {
commentCount = commentCount + 1;
$("#comments").load("load-comments.php", {
commentNewCount: commentCount
});
});
});
</script>
You have AJAX tagged in your question, so I am assuming that you are somewhat familiar with the term. This can indeed be done by AJAX, but I don't see any AJAX attempts in your code?
Also, when you say delete, do you mean specifically delete by the literal sense, or simply that your comment display works as sort of a sliding function, removing the previous comment from display, showing the next comment in queue? I am going by the literal sense in my example, since that's what I have to assume really.
What you could do, is to have a file that handles all the comments, and displays them however you like. For instance,
<?php
$sql="SELECT * FROM comments ORDER BY id DESC";
$result_set=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_assoc($result)) {
/*
html construction of displaying comments,
echo'ing the row value that displays the comments.
echo $row['comments']; as a guess
*/
}
?>
Let's call that PHP file comments.php for the sake of referencing later on. Also note, that I chose to make an ORDER BY in a descending order. Assuming your comment id is an auto increment, then this will always display the newest comments first, since the highest id's will be the latest entries.
Then, in another file, display-comments.php as an example, you could make a document.ready function, that loads your comments into an element, <div> element for example.
The AJAX function could look like this:
$( document ).ready(function() {
function loadCommentsAjax()
{
$.ajax({
type : "POST",
url : "comments.php",
data : { },
success: function (html) {
$("#commentContainer").html(html);
}
})
}
});
What I do here, is that I encapsulate an AJAX function in a document.ready function. What this does, is that when the document is ready, it fires the AJAX function.
How the AJAX function works, is that we declare a data type. The most common are probably POST and GET. You can look up the different data types, how to handle them, and what they mean specifically. The main difference between POST and GET for instance, is that GET displays its values as parameters in the URL. Since we aren't parsing any data, we could use a GET just fine, since it will have no influence. However, should you ever need to parse sensitive data, where you don't want the user to mingle with the data, then you should use POST.
We then tell the AJAX function, which page/file it should work with. In our example, it will be the comments.php that we created earlier. It will then in the success function, paste the html content into a container that we defined. In this case, commentContainer. Note that it's an id specific targeting, which means our container element needs to have that specific id. Note, that the container is in our main file, the display-comments.php file.
An example of the container could be the following:
<div id="commentContainer"></div>
This div element will then contain the comments and html logic that we made in our comments.php file.
In your button, you can then have another AJAX function, handling the comment deletion, and call our loadCommentsAjax() function on success, to reload our comments in the appropriate fashion.
The AJAX function handling the deletion of comments, would then again have a PHP file that will perform the delete. We'll call this delete-comments.php in our example.
example of our delete AJAX function:
function deleteNewestComment() {
$.ajax({
type : "POST",
url : "delete-comments.php",
data : { },
success: function (html) {
loadCommentsAjax();
}
})
}
Our delete-comments.php will look something like this:
<?php
/*
since you are deleting the latest entry each time, what we could do,
is make an SQL query that deletes the max id from the comments table
*/
$sql="DELETE FROM comments WHERE id=(SELECT max(id) FROM comments)";
$result=mysqli_query($conn, $sql);
?>
We will then have our button call the delete function like so:
<button onclick="deleteNewestComment();">Delete latest comment</button>
Let me know if this is what you were looking for at all, or whether you really just wanted a sliding kind of logic, where you simply iterate through your comments, displaying one at a time.
But in case you did mean literally delete, then wouldn't it be better to have delete buttons linked to each comment, so that you can delete them seperately, and independantly?
I am working on a posting system in PHP. The posting system goes through a SQL database and then prints out data from the database. I am trying to use javascript to see if the system has been updated. Basically, I want to use javascript to check whether any new posts have been added. I have some code that goes into the database
function minicheck (){
$query= "SELECT * FROM posts";
$result= mysql_query($query);
return mysql_num_rows($result);
}
The function returns the number of rows in the database every 10 seconds.I use javascript to call this function.
<?php
echo(" <script>
killPage();
function killPage () {
setInterval(function(){
x++;
alert(".minicheck().");
}, 10000);
}
</script> ");
?>
THe issue i am facing is that the function returns the exact same value no matter whether or not a row has been added into the sql databse. Even if I add a row into the sql database, the value that is returned by this function is the exact same every time.
How can I fix this?
Thank You,.
You cannot call PHP functions from JavaScript like that.
What you are doing is calling the function once when building your JavaScript, which is then being sent to the browser.
The browser only ever gets the static value you've put in the string, so naturally it can never update.
If you want to call something in PHP from JavaScript, you'll probably want to use XMLHttpRequest (or any of the readily available libraries like jQuery that can help w/AJAX) to query a PHP file that runs the function and returns the value.
how do we check if table is empty with cakephp and ajax? In my index.ctp I have an image that when clicked, it will inform the user if the table is empty or not. If it's empty, an alert box will appear, and if it's not, it will be redirected to another page.
<?php
echo $this->Html->image('movie.png', array('onclick'=>'check()'));
?>
JAVASCRIPT:
function check(){
//check browser comp, create an object
object.GET("GET", url, false);
//rest of the code here
}
MoviesController.php
function index(){
//something here
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
I know how to do it using the normal PHP coding, but with cakephp, and since I am new, I dont know yet. For regular PHP coding, I used the GET method for AJAX, and I can specify the URL for the PHP query inside the GET function. I don't know how to do it using cake.
You need to set the layout to AJAX then render your view. I strongly recommend not to use the index() method for this. Instead you can define a whatever() method in the MoviesController:
function whatever(){
//It is not a bad idea to do this only for GET - use the RequestHandlerComponent
$this->layout = 'ajax';
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
The in the view file whatever.ctp:
echo json_encode(array('moviecount' = $moviecount));
//It is a good idea to add an isset() ternary check here like:
// echo isset($moviecount) ? json_encode(array('moviecount' => $moviecount)) : json_encode(false);
Notice that I am creating an array and encoding it to JSON. This is the way to convert variables to and from JSON. To decode use json_decode() of course.
The Client-side code really depends on what you're using to make the AJAX call but let us say that the call succeeded and you got the data back in the data variable:
//Make the AJAX call to example.com/movies/whatever via GET
//Check what data is but it should definitely be an array
if (data['moviecount']) {
//If moviecount is 0 it will go in the else statement - 0 i falsey
window.location = 'example.com/redirect/url';
} else {
alert('No records');
}
I advice against using alert() to inform the user that there are no records. Better put it somewhere in the page - in some div or whatever. Since this is an AJAX request it could be repeated many times. Consecutive use of alert() is not really user-friendly in this case.
I have a view where ill have 3 divs:
Div 1: List of Brands with checkboxs.
Div 2: List of Categories with checkboxs.
Div 3: List of Items.
This last div will be refreshed with the all the items according to what is selected in the first two divs. At beginning it shows all the items, after we select some of the brands and/or categories and press refresh i'll want to refresh the div 3.
In Javascript I can get which of the categories/brands are selected and my biggest doubt is on how to refresh the last div...
Heres what I was trying:
function refresh() {
var brands= /*<code where i get all the brands selected (this will be a js array)>*/
var categories = /*<code where i get all the categories selected (this will be a js array)>*/
<?php echo $ajax->remoteFunction(array('url' => array('controller' => 'items',
'action' => 'men', brands, categories),
'update' => 'itemsContent')); ?>
}
My problems are:
- How do I pass the js vars into the php method?
- How do I receive an js array in a cakephp action? Because brands and categories will be used to filter the query that produce results for the div 3...
You won't be able to use the $ajax helper here, since it just outputs a static script which can't be changed/influenced at "run-time" in the browser. It just wasn't made for something more complex than it is.
So, you'll have to roll your own JS, which shouldn't be that hard though. All you need is:
a Cake action that outputs a list of items based on the data it receives (shouldn't be hard)
a bit of JS that figures out which brands and categories are selected (which you already have)
another bit of JS that packages that data and sends it to the Cake action
another bit of JS that updates the site with the list of items you received back
I'd take a look at jQuery's AJAX functions to accomplish #3. If you POST the data in a format like this, it's very easily accessible in $this->data in Cake:
{
'data[ModelName][categories]' : categories,
'data[ModelName][brands]' : brands
}
Regarding your question:
"How do I pass the js vars into the php method?"
You don't. PHP runs on the server and is already finished by the time the Javascript runs in the browser. The only "communication" between JS and PHP is via standard HTTP GET and POST requests, and there it doesn't matter whether the request comes from a standard browser or JS or Flash or whatnot.
The $ajax helper just has a bunch of pre-fabricated Javascript snippets it can put into your page, but your JS will not be able to "talk to" the $ajax helper in any way.
I had a similar scenario to yours, and I found a few methods on the Javascript helper that are applicable. I used codeBlock() to wrap a chunk of javascript, and event() to wire up the click event, but I'm not sure how much clearer this is than just writing the raw Javascript.
I found the AJAX section of the CakePHP manual to be really helpful for getting the basic set up. Then I took the generated Javascript and made it more dynamic.
In this example, I'm calling the add_topic action whenever the user clicks the link. Every time it gets called, I increment the topicIndex variable and pass it as a parameter in the AJAX call. The AJAX call returns a few rows that are inserted in the table above the link that the user clicked.
<tr id="add_topic_row"><td colspan="3">
<a id="add_topic_link" href="javascript:void(0);">New Topic
<?php echo $html->image('icons/add32.png');?></a></td></tr>
</table>
</fieldset>
<?php
echo $form->end('Submit');
$addTopicUrl = $html->url(array('action' => 'add_topic')) . '/';
$script = <<<EOS
var topicIndex = $index;
var addTopicUrl = '$addTopicUrl';
addTopic = function()
{
new Ajax.Updater(
'add_topic_row',
addTopicUrl + topicIndex,
{
asynchronous:true,
evalScripts:true,
insertion:Insertion.Before,
requestHeaders:['X-Update', 'add_topic']
});
topicIndex++;
}
EOS;
echo $javascript->codeBlock($script);
echo $javascript->event('add_topic_link', 'click', 'addTopic();')
?>