Using ajax to call a php function - php

I have a main page in my app called index.php where i want to show some photos. Code in that file is:
<div id="main" name="main">
<input type="button" value="Photos" onclick="showIm()">
</div>
File function.php contains a function to show photos on the screen:
function showPhotos()
{
global $link;
$result = pg_query_params($link, 'SELECT photo_name FROM photos');
while($photos_row = pg_fetch_row($result))
{
echo '<a href="photos/'.$photos_row[0].'">
<img src="photos/'.$photos_row[0].'"></a>';
}
}
My last file is function.js where i try to call showPhotos using ajax
function showIm()
{
$.ajax({
url: "functions.php"
})
}
So inside the last function I want to call showPhotos() to get the results. I think that my implementation is a little complicated but I would like to know if anyone could help.

Well, you have to do something with that result! Add a success method and declare a return dataType
function showIm()
{
$.ajax({
url: "functions.php",
dataType: "html",
success: function(html) {
//do something with the response here
//the "html" variable will contain your PHP response
}
})
}

Related

How to send post to PHP by AJAX and load specific div

I am building a filter function in ajax and php (I am new to ajax). I have an html input like this:
<form>
<input type="text" placeholder="Search" onkeyup="getListSearch(this.value)" name="search_filter">
</form>
The current function getListSearch looks like this
function getListSearch(filter) {
$.ajax({
method : "POST",
url : "www.example.com/includes/content.php",
data : {
search_filter: filter
},
success : function(result) {
$("#list_content").html(result);
}
});
}
This works but loads the whole result, I only want to show the div with class .list_content from content.php.
I tried the below codes
$("#list_content").html($(result).find('.list_content'));
// Tried below also
$("#list_content").load(result + " .list_content");
But no success.
Any help would be appreciated.
function getListSearch(filter) {
$.ajax({
method : "POST",
url : "www.example.com/includes/content.php",
data : {
search_filter: filter
},
success : function(result) {
var dom_nodes = $($.parseHTML(result));
$("#list_content").html(dom_nodes.find('.list_content').html());
}
});
}
Thanks for the response, this worked for me:
function getListSearch(filter) {
$('#list_content').load('www.example.com/includes/content.php #list_content', {
search_filter: filter //Post for content.php
});
}

Why is my php variable made with ajax keeping empty?

First, precisions : I'm using MAMP and Brackets, and Chrome to test.
Here's what I have :
<ul>
<li class="brick" data-pseudo="one">Some text or elements</li>
<li class="brick" data-pseudo="two">Some text or elements</li>
<li class="brick" data-pseudo="three">Some text or elements</li>
</ul>
li.bricks are just rectangle articles "linking" to Work1, Work2 and Work3, and generated by a PHP function from an array.
I'm trying to get the "pseudo" data of the clicked .brick to put it in a PHP variable and use it to call another array in another php function, in order to generate the HTML elements of Work1, Work2,...
I found I had to use AJAX and managed to get that code :
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
$('.brick').click(function(){
//some code
pseudo = $(this).data('pseudo');
sendPseudo(pseudo); //calling sendPseudo() function
});
And here's my testing PHP function :
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
... I'm calling in my HTML document :
<section class="site">
<div class="left">
<?php loadWork() ?>
</div>
<div class="right">
//some other content
</div>
</section>
And so I have two problems. Firstly, when a .brick is clicked, the alert pops up but it's empty, absolutely nothing appears in it, but when I console.log the var pseudo, I see "one", "two"... And secondly, the echo in testing PHP function does not generate the paragraph with the pseudo.
Pleeeaaase, help me to find out what I'm doing wrong, it's making me go crazy !
Thank you !
I think there is some confusion in your order. loadWork(), as you say, is part of an html file gets called as soon as the browser reads the html file and it's only called once. If loadWork() hasn't been defined yet (or exists in another file as your AJAX request suggests based on it's call to my_php_function_page.php) then it won't output anything. In other words, loadWork() needs its post data to exist when the browser requests the html.
You can put the php in the same file as the html that is being called on, but it looks like you might be trying to get the results of loadWork() inserted into a div that already exists. Change your ajax function so that if(data!="") changes the inner html of your div to include the data:
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
$('.left').html(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
I think you have missed calling your function loadWork() in my_php_function_page.php, this code may be fix your empty alert issue.
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
data=data.trim(); // to remove the unwanted space around the string
success: function (data) { //testing the success
if(data!="")
{
alert(data);
$(".right").html(data); // This adds your AJAX success data to the class left inside your DIV
}
else
{
alert("You're wrong !");
}
},
});
}
my_php_function_page.php
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
loadWork();
I'm not sure why, but sometimes data function is not working, so I always use attr('data-pseudo') in your case.
so it would be like this:
pseudo = $(this).attr('data-pseudo');

Calling php function with ajax and passing return value to div

I have a function that adds social buttons to my blog posts , but once i load more posts using ajax I cant figure out how can I call add_social_buttons() and pass the data to div.
I'm not really familiar with ajax , i tried this method :
$.ajax({
type:"POST",
url:"functions.php",
data: "social_sharing_buttons()",
success: function(data){
$('.pp').html(data);
}
but it seems that it tries to invoke some totally other function Fatal error: Call to undefined function add_action().
As far as I am aware, you can't. What you can do is have a handler file for your classes, so for example say we have this PHP class,
<?php
class Car {
function getCarType() {
return "Super Car";
}
}
?>
Then in your handler file,
<?php
require_once 'Car.php';
if(isset($_POST['getCarType'])) {
$car = new Car();
$result = $car->getCarType();
echo $result;
}
?>
You'd post your AJAX request to the handler, you could make specific handlers for each request or you could have a generic AJAX handler, however that file could get quite big and hard to maintain.
In your case you'd have in that data,
"getSocialButtons" : true
Then in your AJAX handler file,
if (isset($_POST['getSocialButtons'])) {
// Echo your function here.
}
Then you'd echo out the function within that if statement and using the success callback in your AJAX request do something like this.
document.getElementById("yourDivId").innerHTML = data
That is assuming you're using an ID. Adjust the JS function to suit you.
Try to call that function social_sharing_buttons() like this in function.php:
$.ajax({
type:"POST",
url:"functions.php",
data: {action: 'add'},
success: function(data){
$('.pp').html(data);
}
in functions.php
if(isset($_POST['action']) && !empty($_POST['action'])) {
if($_POST['action'] == 'add') {
echo social_sharing_buttons();
}
}

Passing value from one page to other using ajax

This is my html code
<td class="saltr" style=" border-color:#000; cursor:pointer;" id="<?php echo $grade["DEALID"];?>" onclick="dealid(this.id)" ><?php echo $grade["DEALINGS"];?></td>
on onclick() javascrip is written.
function dealid(psid)
{
var serow = psid;
//alert (serow)
$.ajax({url:"../views/printdeal.php?proc=dealing",data:"dealdatres="+serow,success:
function(z)
{
//alert("hiiiii")
alert(z);
//window.location="printdeal.php";
}
});
}
and in printdeal.php page the code is written as
if($_REQUEST["proc"]=='dealing')
{
$dealdatres1=$_REQUEST["dealdatres"];
include_once("../classes/dbqrs.php");
$obj=new qrys();
$qremp="select deals.PROSPECS ,deals.DEALINGS,deals.BUYER,deals.BENEFICIARY,deals.GUIDE,deals.REMARKS ,deals.DATES,salescal.DEALID from salescal left join deals on deals.ID=salescal.DEALID where salescal.DEALID='$dealdatres1'";
$empr=$obj->exeqry($qremp);
$empres=mysqli_fetch_array($empr);
?>
but when I run this code and when i click on it ,it shows a notice as undifined "proc" .
Please help me to solve this.
It looks like you have placed you function somewhere out of usual global scope. I don't know what should be changed as far as I cannot know your structure.
At first, move all function's content into onclick:
onclick='$.ajax({url:"../views/printdeal.php?proc=dealing",data:"dealdatres="+this.id,success:
function(z)
{
//alert("hiiiii")
alert(z);
//window.location="printdeal.php";
}
});'
and get a proof that there is something wrong with the name/placement only.
P.S. BTW read about addEventListener/attachEvent as strong and more convenient alternative to "onclick" usage.
We have kinds of ways to get the function,one of them like this:
You may write the code in view page :
$.ajax({
url: "<?php echo url('/soc/cnews/savetop') ?>",
type: 'post',
data: "sets=" + $("#top10").val(),
sync: false,
dataType: 'json',
success: function(data) {
if (data.status == 'success') {
window.location.reload();
} else {
alert(data.msg);
}
}
});
and the write the code in page which get data:
if($success){
echo "{status:'success',msg:'victory'}";
}else{
echo "{status:'failur',msg:'I am sorry to failure :('}";
}
And again: if you want get data via ajax,make sure print or echo the message on data page.
Try This
$.ajax({type: "POST",url: "../views/printdeal.php",data: { proc:"dealing",dealdatres=serow }});
if your problem in php, i think you can check values in global variables with
<pre>
<?php
var_dump($_REQUEST);
?>
</pre>
the result can be like this
array(2) {
["asd"]=>
string(3) "qwe"
["zxcv"]=>
string(5) "lkjsf"
}
that's result is from my localhost with url localhost/a.php?asd=qwe&zxcv=lkjsf

codeigniter view won't show up from passing javascript/ajax parameter

I'm integrating codeigniter with phpgrid, and I'm having a trouble with passing the row values from phpgrid (in VIEW A) to another view (VIEW B) through javascript and codeigniter controllers
I have a virtual column like this in PHPGRID (VIEW A):
$col_formatter = <<<COLFORMATTER
function(cellvalue, options, rowObject, rowid){
var sessid = rowObject[0];
return '<input type="button" value="View" onclick="btnView('+sessid+')">';
}
COLFORMATTER;
and the javascript in VIEW A:
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
}
});
return false;
}
in the Codeigniter CONTROLLERS:
public function tes(){
$data['sessid'] = $_POST['sessid'];
$this->load->view('view_b', $data);
}
I can't seem to load the view. I used Mozilla's Firebug to know the response, it's true that the response is the code of my view_b view, but how can I switch to that view?
//Your are using ajax for some operation and want to reload the view page the you can test these options:
1) take a div in current view page and assing ajax retrun message to that div
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
$("#divid").html(msg);
}
});
return false;
}
//Or 2)just redirect to your view page again
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
window.location.href=path to your view page;//<?php echo base_url()."index.php/controller/function"; ?>
}
});
return false;
}
If I understand correctly you want to go from VIEW A to VIEW B (meaning an actual change in the window location) and pass a value to VIEW B so it can generate some dynamic content. Well, AJAX is not the solution here since it will not trigger a change of page but instead will return the markup/text of the response as a string.
But there are still a number of ways you can achieve what you want, using Codeigniter the simpler way would be to use an argument for your controller method that you can send as part of the uri in a link:
HTML
View
Since you're using Javascript to generate the markup you would need something like this
return 'View';
*Note that you will now have a link instead of a button but you can use CSS to style it any way you want it.
You would now retrieve the value in your controller like this:
PHP
public function tes($sessid){
$data['sessid'] = $sessid;
$this->load->view('view_b', $data);
}
Pretty simple. A second option will be to use a form instead of your button to send the value using either GET or POST, forms do trigger a change in page whenever they are submitted:
HTML
<form action="http://example.com/index.php/main/tes" method="get">
<input type="submit" value="{ssid}" name="sessid" />
</form>
Again using javascript:
return '<form action="<?php echo site_url('main/tes')?>" method="get">'
+'<input type="submit" value="'+sessid+'" name="sessid" />'
+'</form>';
And to get the value in your controller:
PHP
public function tes(){
$data['sessid'] = $_GET['sessid']; //OR $_POST['sessid']
$this->load->view('view_b', $data);
}
Turns out that passing a variable from javascript to codeigniter controller is just:
function btnView(sessid){
window.location = "printvo/"+sessid;
}
I was using ajax because I don't know how to pass the variable, I always thought that passing variable is using brackets: window.location = "printvo("+sessid+")"; and that didn't work.

Categories