Using AJAX to execute a php file - php

I've created a custom template for wordpress and I'm trying to execute some php code (deleteUser.php) to delete a record from a db but I'm not sure how to run the code without using alert. At the moment I'm just getting an empty dialog box rather than my php code deleting a row from the db.
ajax part
<?php
echo '<script>';
echo 'function dltUser(siteID){';
echo "jQuery.ajax({";
echo "data: 'siteID=' + siteID,";
echo "url:"."'".get_stylesheet_directory_uri()."/deleteUser.php"."',";
echo "method: 'POST', ";
echo "success: function(msg) {";
echo "alert(msg);";
echo "}";
echo "});";
echo '}';
echo '</script>';
?>
deleteUser.php - the code to delete a row
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-config.php' );
global $wpdb;
$siteID = $_POST['siteID'];
echo '$wpdb->query("DELETE FROM my_site WHERE SiteID = %d",$siteID)';
?>

Don't wrap the $wpdb->query(...) inside an echo, that won't execute the query, it will just output the command as a string, and you want to return a value to the AJAX function after the code is executed, not echo it.
If you don't want to use alert() to prevent the message from displaying to the user, use console.log() instead, see Console.log()
Also, as Rory said, don't use an echo for every single line you write. Either use . to concatenate or write plain HTML and inject the PHP variables where needed.
Resuming, your code should look something like this:
Ajax:
<script>
function dltUser(siteID) {
$.ajax({
data : siteID,
url : <?php get_stylesheet_directory_uri(); ?> + '/deleteUser.php',
method : 'POST',
success : function(msg) {
console.log(msg);
}
})
}
</script>
deleteUser.php
<?php
include_once ($_SERVER['DOCUMENT_ROOT'] . '/wp-config.php');
global $wpdb;
$siteID = $_POST['siteID'];
if ($wpdb->query("DELETE FROM my_site WHERE SiteID = %d", $siteID)) {
return 'Success';
}
return 'Error';
?>

Remove the alert. An empty dialog box means alert is being called, but you have no message. However the PHP script ran returning an HTTP response with a 200 OK code. If you don't want the popup, remove the alert. If you want a message, echo something at the end of your script.
Oh, and ditch the closing ?> if there isn't any output after it.

Related

Include php file via Ajax and display on page

I was wondering if there is any way to include a php file after an AJAX call and display that included file in my page as response.
For example this is an ajax call:
$('#id').change(function(){
var selected = $(this).val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "select="+selected,
success: function (data) {
$("#here").html(data);
}
});
});
And this is what i tried in php but i got not result displayed on my html:
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
include("include.php");
}
}
Is there any way to display my included file in my html?
I tried to change my success response from Ajax $("#here").html(data); to $("#here").load(data); but it returned the whole page.
Any suggestions will help.
UPDATE: Inside the include.php file exist a long html code and some class methods
PS. Please don't mentioned that script is not safe, I know is just an example script.
Thank you in advance
In order to get the success data you need to return the data which you want to be included. And remember php will not work in html except it is action call. You can have php file for this since it has the html support also.
Also you need to remember, before setting the success data to the element it's better to console the value and make sure you are getting the correct data.
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
return include("include.php");
}
}
you can set all your "include.php" html in buffers and then you need to echo your content into console.
<?php
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
ob_starts();
include("include.php");
$include = ob_get_contents();
echo $include;
}
}
?>

ajax and php: how to select variables from database and insert in database using ajax

I really have never done this before and I am getting frustrated because I'm not sure how it fits together. I have a function that I want to call my php (one php file selects info from a database and the second inserts into the database)... I need to use ajax in the way my site is setup but I don't know how to pass data from and to the php files.
In first .js file:
q1LoadVar();
This is my ajax function in second .js file that I have so far (not working):
//ajax code has been edited here since original post:
function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {
console.log(data); //nothing happens!
// alert(data); //nothing happens!
}, "json" );
}
And here is the code I have in q1LoadVar1.php that I want to select data back from and be able to populate a text area in my html:
/*works when I type this file path directly into the url;
but the file is not communicating back to the ajax function on the
.js file that is calling it*/
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
echo '<script type="text/javascript">alert("working from php!");</script>';
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}
$json = json_encode($newRow);
echo $json; //works on php file directly!
/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/
mysqli_free_result($result);
mysqli_close($link);
?>
Can someone help me understand how to make this all work together? Thank you, Kristen
You can retrieve post data from ajax in php with
$_POST['action']
//in your case will return: test
To return data to ajax you need to use echo
If the success: callback function doesnt get called try to remove datatype: 'json'
I also think that you need to echo $newrow instead of $row.
If this still doesnt work you can catch the error with the error: callback function to see what is wrong.
Try to start with a simple request and work from there.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "yourphp.php",
data: {simplestring: "hi"},
success: function(result){
alert(result);
}
});
});
and yourphp.php
<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;

Get a PHP $_SESSION variable from Jquery?

I'm not yet a JSON/AJAX master so I don't know how to do this.
I need a $_SESSION['name'] PHP variable to work with in my jQuery stuff and I don't know how to access it... consider:
// the 'who is typing' shindig
$.ajax(
{
url: "whos_typing.html",
cache: false,
success: function(whos)
{
// here I need to access $_SESSION['name'] and do stuff with it
$("#soandso").html(whos); //Insert who's typing into the #soandso
}
});
You'll need to inject it, something like this:
var sessName = '<?php echo $_SESSION['name']?>';
The file containing this script must be executed by the php interpreter (i.e. a .php file)
EDIT: Conceding to Radu's point, it would be safer execute for unsanitized data:
var sessName = <?php echo json_encode($_SESSION['name']) ?>;
You need to use $.post to retrieve the variable from the server. You would have something like this:
$.post('echoMyVar.php', {post: 1}, function(data){
myVar = data['myVar'];
});
This is very basic, you first need to check if data is not null. In echoMyVar.php, you need just need basically the following:
header('Content: application/json', 1);
$returnVal = array('myVar', $_SESSION['myVar']);
echo json_encode($returnVal);
Again this is a shell, not secure, and would not handle any errors.
var name= "<?php echo $_SESSION['user_name'];?>"
will do it . . .
Remember php is a server side script, . . .so it takes precedence and get executed first and spits html to the client (Jquery , javacript) which will be executed in your browser . . . .
So, you can use server side variables to share with client . . . but not the other way around . . .
The easiest way is probably to include your javascript code in a .php file. Then you can simply do:
var phpVar = <?php echo $_SESSION['name']; ?>
SIMILAR POST
Server side in whos_typing.php:
<?php
//...
header('Content-Type: application/json');
echo json_encode(array(
'who'=>'Bob',
'session'=>$_SESSION,
// Be sure that you're not storing any sensitive data in $_SESSION.
// Better is to create an array with the data you need on client side:
// 'session'=>array('user_id'=>$_SESSION['user_id'], /*etc.*/),
));
exit(0);
Client side:
// the 'who is typing' shindig
$.ajax({
url: "whos_typing.php",
dataType: 'json',
cache: false,
success: function(data) {
var session = data.session,
who = data.who;
console.log(session.user_id); // deal with session
$("#soandso").html(who); //Insert who's typing into the #soandso
}
});
You need to echo the session variable from PHP when you send it to the browser. I'm assuming whos_typing.html is just the URL to a PHP script.

JQUERY - .html() can also view php

The following script sends data with ajax for login
I want to format the data returned by using, in essence, a session variable ($ _SESSION)
I can do it
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "inc/login.inc.php",
data: "username="+username+"&password="+password,
success: function(msg){
if(msg!='false')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
//valori menĂ¹
if(tipo=='1')
{$("#admin").css('display','none')}
}
else
{
$("#add_err").html("Username o password errata");
}
},
beforeSend:function()
{
$("#add_err").html("<img hspace='84' src='img/loading.gif' alt='Loading...' width='32' height='32'>" )
}
});
return false;
});
especially this is possible, in this way would print the name of the user just logged. otherwise I would not know how to do
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
You can't insert PHP code after the script has already been processed.
Either pull it in via ajax, or include the actual PHP output into your javascript.
ie, in page.php
<script>
var sessionName = '<?php echo $_SESSION['name']; ?>';
</script>
then when you need it later
$("#profile").html(sessionName + " Logout k2");
JavaScript is client-side, it simply can't execute your php code.
You have to return something (eg. the username) in the php file you use in your ajax request and use that in your JS.
See the jQuery ajax docs for examples.
You'll need to serve the php code:
$("#profile").load("inc/login-header.inc.php");
login-header.inc.php
<?php
print($_SESSION['name'] . " <a href='inc/logout.inc.php' id='logout'>Logout k2</a>");
?>
The easiest way to send information back from the php script to the javascript, is by using the msg variable in
success: function(msg){
If you just want to send back one string, you just echo that one string in your php file and you will have its value in msg. If there are multiple variables you want to send back, you can package the result in a json object.
So assuming that everything you want to send back is contained in the php array named $output, you do a echo json_encode($output); at the end of your php script to get the whole thing in msg.
that won't work, as the PHP code is never processed.
In login.inc.php try something like this
<?php
if (!loginOK()){
echo "{login:false}";
} else {
echo "{login:true, name:'".$_SESSION['name']."'}";
}
and then on the client
success: function(msg){
if (msg.login){
// stuff
} else {
$("#profile").html(msg.name + $('<a>').attr('href', 'logout.php').html('logout'));
}
}

Unable to perform any PHP operations in an Ajax application

My Ajax application was working fine, until I implemented an if statement in the PHP script... then like a contagious disease it seems that if I do anything to the data in PHP it returns nothing back to the Javascript layer.
All I can do is echo the data back...
For instance the query string I'm sending to the PHP reads...
index.back3.php?form=login&json={"email":"mo#maurice-campobasso.com","password":"asdasdfas"}
and I know its getting there because in the simplest debugging PHP file (index.back3.php) that I created all I have is a simple echo statement... and it never fails to send back the data to the Javascript file.
when index.back3.php reads
<?php echo $_GET[json]; ?>
the alert that I have triggering off in the javascript reliably spits out the json string.
also when it reads
<?php echo $_GET[form]; ?>
when I get any more complicated than that nothing comes back to the javascript. Even a simple concatenation...
<?php echo ($_GET[form] . $_GET[json]); ?>
...returns nothing!
A simple if...else statement also returns nothing.
<?php
if(!isset($_GET[form]) {
echo "no!";
} else {
echo "yes!";
}
?>
And this important operation also...
<?php
$array = json_decode($GET[json], true);
var_dump($array);
?>
returns nothing.
OK... so just to make sure everything is above board here is my Ajax output function in the Javascript layer.
function responseAjax() {
if (myRequest.readyState == 4) {
if(myRequest.status == 200) {
var foo = myRequest.responseText;
alert(foo);
} else {
alert("An error has occured: " + myRequest.statusText);
}
}
}
Can someone please explain what's going on? I'm truly stumped.
if(!isset($_GET[form]) {
echo "no!";
} else {
echo "yes!";
}
?>
you are missing a closing parenthesis in the if statement. And as said a few times before, put quotes around your array keys.
While in development, you should also maybe turn on error_reporting to E_ALL. it helps find out what a small error might be.
$_GET['form'] is the right way.
and using form as variable name is not at all good.
use anyother variable and pass $_GET['formname'].
Try to access the php page directly through url and pass the parameters , check first the php
return error or its working propelry.
You can use PHP , jquery and ajax in simple ways.
try to find .post or .get methods in jquery
http://api.jquery.com/jQuery.post/
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
I managed to sort it out, it had to do with a line of code which I omitted from this post, because I thought it was reduntant. The full version of the function went like this.
function responseAjax() {
if (myRequest.readyState == 4) {
if(myRequest.status == 200) {
var foo = myRequest.responseText;
var cookieData = eval("(" + foo + ")"); //this was the problem!!
alert(foo);
document.cookie = 'email =' + cookieData.email + '; path=/';
document.cookie = 'firstname =' + cookieData.FirstName + '; path=/';
} else {
alert("An error has occured: " + myRequest.statusText);
}
}
}
It was the 'var cookieData' line... though I'm not sure why.

Categories