I'm new into php and I am trying to call code from another file.
I try to use ajax to so, because later I would like to add parameters. But unfortunattely for me nothing appen when I click on my button.
I have a button in my file admin.php that is written like this:
<button onclick="clickMe()"> Click </button>
And in the same file I have my ajax code in script balise:
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: test() {
alert('ok');
}
error : test(){
alert("error");
}
});
}
</script>
And here is the code that I'm trying to call in my ajax, the function test in the file delete.php:
<?php
function test() {
echo "Hello the World! ";
}
?>
I wondering if I maybe need to put the code in delete.php in a function ?
Do you think I need to post the entirety of my admin.php file, even thought a lot of the code is not related to the question ?
EDIT: I forgot to mention; i have require delete file in my admin one:
require 'delete.php';
I don't know jQuery, but I think your code should look something like this:
<?php
// delete.php
// make somthing
return 'Helo Word';
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: response => {
alert(reponse);
},
error: error => {
alert(error);
}
});
}
</script>
let's assume that your js code is working(i'm bad with JQuery). The JS code and the PHP code are living in different worlds but can connect by HTTP requests(XML-AJAX) and some others.
You can do a request to a PHP page like my-domain.com/the-page.php?get_param_1=value(GET method), and you can pass the same params(and a little more) by POST method. GET and POST params are looking like :
param_name=param_value¶m_name=param_value¶m_name=param_value
You can't call directly PHP function(like var_dump('123);), but you can do this request with JS my-domain.com/the-page.php?call_func=myFunc123&printIt=HelloMate
to php page
<?php
function myFunc123($printText) { echo $printText; }
if (array_key_exists('call_func', $_GET)) {
$param_callFunc = $_GET['call_func'];
if ($param_callFunc == 'myFunc123') { myFunc123($_GET['printIt']); }
}
?>
Yes, you can pass any existing function name and call it, but it's not safe in future usage. Above, i use "page" word because you should do a request, not php file read or access.
Here is how I finally did it :
I gived an id to my button:
<button id="<?php echo $rows['id']; ?>" onclick ="deletedata(this.id)">Delete</button>
I give in deletedata the parameter this.id, it's a way to give the id of the button as parameter, then I use Ajax to call delete:
<script type="text/javascript">
// Function
function deletedata(id){
$.ajax({
// Action
url: 'admin',
// Method
type: 'POST',
data: {
// Get value
id: id,
action: "delete"
},
success:function(response){
}
});
};
</script>
Here is the tricky thing, I didn't use a fonction as I thought I needed. Instead I did this :
if (isset($_POST["action"])) {
echo "Hello the World! ";
// Choose a function depends on value of $_POST["action"]
if($_POST["action"] == "delete"){
mysqli_query($conn, "DELETE FROM bdd_sites WHERE id = " . $_POST['id'].";");
}
header('Location: '.$_SERVER['REQUEST_URI']);
}
?>
Related
little issue over here.
I have a php function that is called via AJAX and looks like this:
function processActiveDirectory(){
$var = new GetLDAPUsers;
echo "Getting Users from Active Directory.... <br />";
$adusers = $var->getAllUsers();
echo "setting up images.... <br />";
// processing more stuff
echo "finished";
}
I'm trying to get a "live- log" echo. Meaning before every step the echo should output to a Log area, one step after another. So the user knows what's going on.
But the Problem is, that the log doesn't appear during the process, it just fills in at the whole text at the end of the process. Everything else works fine. The Log just doesn't appear at runtime, but after the function is finished it appears at the right position.
My AJAX call:
jQuery(document).ready(function($) {
$('#lii-form').submit(function() {
data = {
action: 'lii_map_images'
};
$.post(ajaxurl, data, function(response){
$('#lii_log').html(response);
});
return false;
});
});
This is how it's build:
Edit
Other than in this thread I'm already using an ajax call, to call the function. It's within the called function that I'm echoing stuff...
Edit 2
I'm using wordpress
Sorry I can't offer more informations, because of enterprise restrictments.
This is a short over-view on your need. Please develop further with this idea.
This uses two AJAX calling - one for the main process and other for progress:
Script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//Start the main process
$.ajax({
url: 'main.php',
success: function(data) {
}
});
function getProgress(){
$.ajax({
url: 'progress.php',
success: function(data) {
$("#progress").html(data);
if(data != "finished"){
getProgress();
}
}
});
}
//Start the progress section
getProgress();
</script>
<div id="progress"></div>
main.php
<?php
$arr = ['Getting Users from Active Directory....','setting up images....','finished'];
foreach($arr as $value) {
session_start();
$_SESSION["progress"]=$value;
session_write_close();
sleep(1);
}
progress.php
<?php
session_start();
sleep(1);
echo $_SESSION["progress"];
So your processActiveDirectory will come under Main.php and echo should be replaced with SESSION variable
I think there is no need in such thing as LOG process WITH AJAX. AJAX is too heavy thing and it could be a bad design if you want it. It's better to use web sockets or not use at all
<form>
<input type="text" id="user"/>
<input type="button" value="Submit" onClick="post();" />
</form>
<div id="result"> </div>
<script type="text/javascript">
function post()
{
var username = $('#user').val();
$.post('battlephp.php',
{postuser:user}
)
}
</script>
Its a simple Ajax code.. It should take username and display the Php code!
But don't know why its not running?? Actually I am learning...so I cant rectify the error or fault??
I am running ii on localhost.. so is there any problem with using:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
display the Php code
No, it shouldn't.
First, you've changed your mind about the variable name you are using (user, username) half way through your script, so you are going to throw a reference error.
Second, you haven't provided a function (the third argument) to $.post, so you aren't doing anything (such as displaying it) with the returned data.
Third, the server should execute the PHP and return its output. You shouldn't get the actual PHP code.
function post() {
var username = $('#user').val();
$.post(
'battlephp.php',
{postuser:username}, // Be consistent about your variable names
function (data) {
alert(data);
}
);
}
Instead
document.ready()
you can use
jQuery(function($){...});
Try to do this:
<script>
$(document).ready(function() {
function post() {
var username = $('#user').val();
$.ajax({
type : 'post',
url : 'batttlephp.php',
data : {
postuser : user
},
success : function(data) {
alert(data);
},
error : function(data) {
alert(data);
}
});
});
});
</script>
if you're doing a ajax request then is good also handle success and error...
Also I suggest to you "to start the document".
Try the code above and let us know if worked
I'm working with this code snippet plugin : http://www.steamdev.com/snippet/ for my blog
but the plugin doesn't work on page load.
It only works at first page refresh.
I load my content in a specific div with jquery.ajax request and i'm trying this :
$(window).on("load", function(){
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
I also tried to trigger the load event but i don't know if it is correct..
Another question : i build my html with php string like this example:
$string = '<pre class="cplus">
#include <iostream>
int main()
{
//c++ code
}
</pre>
<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
echo $string; // ajax -> success
but the PHP snippet shows empty (the c++ is ok). Any other way (or plugin) to show php code snippet on my page?
Thank you.
SOLVED:
The problem isn't the plugin or Iserni suggestions.. i had a problem in page load (ajax)..
This is how i load the pages:
function pageload(hash) {
if(hash == '' || hash == '#php')
{
getHomePage();
}
if(hash)
{
getPage();
}
}
function getHomePage() {
var hdata = 'page=' + encodeURIComponent("#php");
//alert(hdata);
$.ajax({
url: "homeloader.php",
type: "GET",
data: hdata,
cache: false,
success: function (hhtml) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
});
}
function getPage() {
var data = 'page=' + encodeURIComponent(document.location.hash);
//alert(data);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(html);
$('#body').fadeIn('slow');
}
});
}
$(document).ready(function() {
// content
$.history.init(pageload);
$('a[href=' + window.location.hash + ']').addClass('selected');
$('a[rel=ajax]').click(function () {
var hash = this.href;
hash = hash.replace(/^.*#/, '');
$.history.load(hash);
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
$('#body').hide();
$('.loading').show();
getPage();
return false;
});
// ..... other code for menus, tooltips,etc.
I know this is experimental , i have made a mix of various tutorials but now it works..
comments are much appreciated..
Thanks to all.
The PHP snippet seems empty because the browser believes it's a sort of HTML tag.
Instead of
$string = '<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
you need to do:
// CODE ONLY
$string = '<?php
function foo()
{
// PHP code
}
?>';
// HTMLIZE CODE
$string = '<pre class="php">'.HTMLEntities($string).'</pre>';
As for the jQuery, it is probably due to where you put the jQuery code: try putting it at the bottom of the page, like this:
....
<!-- The page ended here -->
<!-- You need jQuery included before, of course -->
<script type="text/javascript">
(function($){ // This wraps jQuery in a safe private scope
$(document).ready(function(){ // This delays until DOM is ready
// Here, the snippets must be already loaded. If they are not,
// $("pre.cplus") will return an empty wrapper and nothing will happen.
// So, here we should invoke whatever function it is that loads the snippets,
// e.g. $("#reloadbutton").click();
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
})(jQuery); // This way, the code works anywhere. But it's faster at BODY end
</script>
</body>
Update
I think you could save and simplify some code by merging the two page loading functions (it's called the DRY principle - Don't Repeat Yourself):
function getAnyPage(url, what) {
$('.loading').show(); // I think it makes more sense here
$.ajax({
url: url,
type: "GET",
data: 'page=' + encodeURIComponent(what),
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
// Here you ought to allow for the case of an error (hiding .loading, etc.)
});
}
You can then change the calls to getPage, or reimplement them as wrappers:
function getHomePage(){ return getAnyPage('homeloader.php', "#php"); }
function getPage() { return getAnyPage('loader.php', document.location.hash); }
ok for the first issue I would suggest to
see what your JS error console saying
ensure correspondent js plugin file is loaded
and use the following code when you are using ajax (the key thing is "success" event function):
$.ajax({
url: 'your_url',
success: function(data) {
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
}
});
for the second issue lserni answered clearly
you need to use to jquery on load function like so:
$(function(){
RunMeOnLoad();
});
I am trying to pass two variables (below) to a php/MySQL "update $table SET...." without refreshing the page.
I want the div on click to pass the following variables
$read=0;
$user=$userNumber;
the div Basically shows a message has been read so should then change color.
What is the best way to do this please?
here's some code to post to a page using jquery and handle the json response. You'll have to create a PHP page that will receive the post request and return whatever you want it to do.
$(document).ready(function () {
$.post("/yourpath/page.php", { read: "value1", user: $userNumber}, function (data) {
if (data.success) {
//do something with the returned json
} else {
//do something if return is not successful
} //if
}, "json"); //post
});
create a php/jsp/.net page that takes two arguments
mywebsite.com/ajax.php?user=XXX&secondParam=ZZZZ
attache onClick event to DIV
$.get("ajax.php?user=XXX&secondParam=ZZZZ". function(data){
// here you can process your response and change DIV color if the request succeed
});
I'm not sure I understand.
See $.load();
Make a new php file with the update code, then just return a json saying if it worked or not. You can make it with the $.getJSON jQuery function.
To select an element from the DOM based on it's ID in jQuery, just do this:
$("#TheIdOfYourElement")
or in your case
$("#messageMenuUnread")
now, to listen for when it's been clicked,
$("#messageMenuUnread").click(function(){
//DO SOMETHING
}
Now, for the AJAX fun. You can read the documentation at http://api.jquery.com/category/ajax/ for more technical details, but this is what it boils down to
$("#TheIdOfYourImage").click(function(){
$.ajax({
type: "POST", // If you want to send information to the PHP file your calling, do you want it to be POST or GET. Just get rid of this if your not sending data to the file
url: "some.php", // The location of the PHP file your calling
data: "name=John&location=Boston", // The information your passing in the variable1=value1&variable2=value2 pattern
success: function(result){ alert(result) } // When you get the information, what to do with it. In this case, an alert
});
}
As for the color changing, you can change the CSS using the.css() method
$("#TheIdOfAnotherElement").css("background-color","red")
use jQuery.ajax()
your code would look like
<!DOCTYPE html>
<head>
</head>
<body>
<!-- your button -->
<div id="messageMenuUnread"></div>
<!-- place to display result -->
<div id="frame1" style="display:block;"></div>
<!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
//attach a function to messageMenuUnread div
$('#messageMenuUnread').click (messageMenuUnread);
//the messageMenuUnread function
function messageMenuUnread() {
$.ajax({
type: "POST",
//change the URL to what you need
url: "some.php",
data: { read: "0", user: "$userNumber" }
}).done(function( msg ) {
//output the response to frame1
$("#frame1").html("Done!<br/>" + msg);
});
}
}
</script>
</body>
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>