Include php file via Ajax and display on page - php

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;
}
}
?>

Related

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;

passing /retrieving data from jquery to php function

I have actually read all related answers to my question but I need a clear and simple example on how to properly implement my code below.
myHome.php
jquery
var url = "computeArea.php";
var data = $('thisForm').serialize();
$.post(url,data,function(response)); // how do i get the area being returned from
computeArea function? i need to save the
return value to a javascript variable
computeArea.php
function computeArea ($data){ // do i need to parse $data to make it an array?
return $area;
}
im new to jquery and your help is very helpful. thank you!
You can do:
$.post(url,data,function(response){
alert(response)
});
ps: you are missing the . between $ and post.
In your php code you could do that:
echo json_encode($area);
Do a simple teste.
jQuery:
$.post("url/to/file.php",{variable_name: "hello"/*(we'll give this value to variable_name*/)},
function(response){
if(response>0)
alert('Something went wrong');
else
alert(response);
});
Now, on server side:
<?php
if(isset($_POST['variable_name']) && $_POST['variable_name']!=="")
echo $_POST['variable_name'];
else
echo 1;
?>
You are misunderstanding the use of post requests. This will not call the computeArea function in computeArea.php and pass data as its parameter:
var data = $('thisForm').serialize();
$.post(url,data,function(response));
You can do this instead for computeArea.php:
$data = $_POST['watever_you_are_serializing'];
// Do computations, etc.
$area = 123; // Contains computed area
echo $area; // Or json_encode($area);
If you need to call that function from computeArea.php, then you can create a new file for $.post request (eg. computeArea2.php) and include computeArea.php from there. It would be something like this:
include 'computeArea.php';
$data = $_POST['watever_you_are_serializing'];
echo computeArea($data);
Something along the lines of:
var url = "computeArea.php",
data = $('thisForm').serialize(),
new_variable;
$.post(url, data, function(response) {
new_variable = response;
});
Though I presume there's a bit more to your PHP script, as otherwise $area isn't defined anywhere.

Retrieve data from dynamic php page to javascript using jquery

This is arrivalPlay.php. This page is loaded if user click data from arrivalRead.php and make the url become arrivalPlay.php?id=1 (2,3,4,5 and so on).
<?php
$con = mysqli_connect("localhost","admin","admin","flight_status");
$id = $_GET['id'];
$getrow = mysqli_query($con, "SELECT * FROM arrival WHERE id='$id'");
$row = mysqli_fetch_array($getrow);
mysqli_close($con);
$order = array(1,2,3,4);
foreach ($order as $o) {
$res[$o][f] = $row[$o];
}
json_encode($res);
?>
This is getData.js file. The file file receive res and will be passed to 'mp'.
<script>
function aha() {
$.ajax({
url:'arrivalPlay.php',
data:{id:3},
dataType:'json',
type:'GET',
success:function(data){
document.write(data[1].f);
document.write(data[2].f);
document.write(data[3].f);
document.write(data[4].f);
}
});
}
</script>
Page arrivalPlay.php only has data if the url become arrivalPlay.php?id=X. Is there any way to retrieve data from the 'dynamic' php to the javascript page? Feel free to change my approach if you think it is odd. Thank you...
Try this:
First in your server page apply echo before json_encode($res);
It should be echo json_encode($res);
And then if it not works then try this code
<script>
$(document).ready(function(){
$(document).on('click','#a',function(e){
e.preventDefault();
$.ajax({
url:'arrivalPlay.php',
data:{id:1},
dataType:'json',
success:function(data){
$('#res').html(data);
}
});
});
});
</script>
If you want json from server then only json data should be passed from server
like in your code
<?php
$con = mysqli_connect("localhost","admin","admin","flight_status");
$id = $_GET['id'];
$getrow = mysqli_query($con, "SELECT * FROM arrival WHERE id='$id'");
$row = mysqli_fetch_array($getrow);
mysqli_close($con);
$res=array();
$order = array('airline','flight','origin','status');
foreach ($order as $o) {
$res[$o] = $row[$o];
}
echo json_encode($res);// echo the json string
// remember that no other output should be generated other than this json
return; //so you can use this line
?>
is enough
but you don't want json then you use this code
echo implode(',',$res); instead of echo json_encode($res);
also in javascript remove this option dataType:'json', in this case.
Read jquery.ajax
Since you are receiving JSON data, I doubt that you would like to place them into an HTML element. I would either change my PHP file to produce HTML elements, or implement som javascript logic to create elements based on the JSON data the server provides.

ajax send data to "test.php", and then open "test.php" directly to show the result

I want to send an array from javascript to php via ajax function.
And I don't want show the result as callback, but immediately open the target php file and show the images.
I mean, I want open the php file directly on the server side.
I think this is quite simple, but I just have no idea.
My javascript looks like:
var stringArray = new Array("/images/1.jpg", "/images/2.jpg", "/images/3.jpg");
$.ajax({
url: 'test.php',
data: {stringArray:stringArray},
success: function() {
window.open('test.php'); // It opens test.php in a window but shows nothing!
},
});
the test.php file:
$stringArray = $_GET['stringArray'];
foreach($stringArray as $value) {
echo "<img src=" . $value . "></img>";
}
Thanks for any help!
Likely the window.open command is being called without the POST data needed.
Now, I don't know what you want to do here but, why send an Ajax request when you don't really want to make use of it?.
Edit: just to make it a bit clearer, you seem to be calling the php file with no data trough POST. There is no clean way of opening a window in JS with POST data, just try GET for no critical information. Let is know how it goes.
As I can see, You are sending data by post method and accessing in test.php
but when u open file via window.location it doesn't get POST data hence no data get populated
You can achieve it via $_SESSION.
in test.php
session_start();
if(!empty($_POST['stringArray'])) {
$_SESSION['stringArray'] = $_POST['stringArray'];
}
$stringArray = (isset($_SESSION['stringArray']) && $_SESSION['stringArray'] != '') ? $_SESSION['stringArray'] : $_POST['stringArray'];
foreach($stringArray as $value) {
echo "<h3>" . $value . "</h3>";
}
Hope this will work for you...
you should write
var stringArray = new Array("apple", "banana", "orange");
$.ajax({
type: 'post',
url: 'test.php',
data: {stringArray:stringArray},
success: function(message) {
window.open(message); // It will open a window with contents.
},
});
I doesn't show the output because when you open the page on the callback you are not sending anything through to the test page through the post variable. Why you would want to do this I don't know. Send the information through the url, get.

How to add ajax to wordpress theme

I've got a problem that I'm stuck on for days now...
I'm trying to use a simple ajaxPOST function to send data to a MySQL database (not WP database).
This code is located within "single-post.php" in the theme, because it must be checked before every post.
$.ajax({ url: 'library/functions/admin_checkuser.php',
data: {action: userID},
type: 'post',
success: function(output) {
alert(output);
}
});
I'm simply sending a variable to a "admin_checkuser.php" script which in turn calls another script that take actions on the database.
This is the code for "admin_checkuser":
$userid = $_POST['action'];
echo $userid;//for testing
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
echo $bb;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
But I don't think the calls go through to the script.
These scripts where tested outside of WordPress and did work, so it must be something in WordPress that blocking the ajax call.
BTW, I tried placing the "admin_checkuser.php" in many diffrent folders but nothing worked.
Thanks in advance.
You're much better off using the inbuilt Wordpress AJAX request.
So in your themes functions.php file, add your function to be called, for example:
function checkUser() {
$userid = $_POST['user']; //validation also :)
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
echo $bb;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
} else {
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
}
After that, you add your hook with connects to the inbuilt AJAX System
add_action('wp_ajax_check_user', 'checkUser');
add_action('wp_ajax_nopriv_check_user', 'checkUser');
wp_ajax_nopriv_%s allows it to be called from the front end.
And then, in your javascript file, you just fire off your ajax request.
$.post(ajaxurl, { action: 'check_user', user: userId }, function(output) {
alert(output);
});
If ajaxurl is undefined, you will need to create it in your template file, something like this should work, but there are other ways.
add_action('wp_head','ajaxurl');
function ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
Backend of wordpress does the rest.
It takes the action passed in the AJAX request, looks for the corresponding `wp_ajax(_nopriv)_%s hook and then calls the function that is assigned to the hook.
It will also pass in either the $_POST or $_GET depending on the type of AJAX request.
You can read a little more about using AJAX inside of Wordpress.
You should check your url for your ajax call.
Maybe use the full url instead of the relative one.
It could be because of the location of your theme makes the url incorrect. I'm assuming your ajax code is in your theme folder.
There are some wordpress functions that get the theme directory.
For example if you at this page http://yourwebpage/test/ then the ajax call will go here http://yourwebpage/test/library/functions/admin_checkuser.php. This I assume would be the incorrect location.
This is why you need to add the absolute url to your script. And if it is in your theme, you can use this method get_template_directory_uri() to get the template directory.
See here: http://codex.wordpress.org/Function_Reference/get_template_directory_uri

Categories