Get public function via ajax based on a custom script - javascript

I am trying to execute a public function with an ajax script with the following
In the front end, root folder from where I am trying to call the public function I have within the contents of the file
details-page.php
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function () {
$("#formaddtofav").on("submit", function (e) {
$.ajax({
type: "post",
url: "lib/execute-ajax.php",
data: $("#formaddtofav").serialize(),
success: function(){
alert("form was submitted");
}
});
e.preventDefault();
});
});
</script>
and HTML
<form id="#formaddtofav">
<input type="submit" name="addtofav" onclick="displaymessage()" id="addtofavs" class="addtofav" value="">
</form>
the public function is located in lib/details-page.inc and looks like this http://pastebin.com/U5tCxwVc
and in the file lib/execute-ajax.php I am echoing the function like I would if i would have not used ajax
<?php
include_once('detail-page.inc');
echo $objWebUser->addtofavorites();
?>
The problem is that I get a success message just that the data is not inserted in the database, what am I missing here.
Function addtofavorites() works 100%, tested with the old method of inserting data (<form action="" method="post"> and if isset).
EXPECTED OUTPUT
When i click the input submit, function should be run and do all the things I have written:
Add data into dbs, check if data is already there and print the coresponding messages.
Please help me on this. It's my first attempt on integrating ajax. It's much appreciated any help.

Related

Submitting a form for use with php inside content loaded with AJAX

I've been search for a solution to this for a while and haven't been able to find one.
My company has quite a few webtools that we use for our jobs and I have been tasked with combining them all into a dashboard page. One of my coworkers started this project but never finished it before he left, so now I have to figure it out and there are quite a few problems.
The dashboard page is composed of a couple of sidebars, plus a "main" element. The sidebar includes a bunch of links that when clicked load specific php pages into the "main" via a call to jQuery AJAX. Here's a simplified example:
<html>
<head>
<script>
$(function() {
$("#pageToLoad").click(function() {
$.ajax({
url: "some_directory/pageToLoad.php",
success: function(result) {
$("#main").html(result);
}
});
});
});
</script>
</head>
<body>
Load Page
<main id="main"></main>
</body>
</html>
The problem here is that most of our tools use forms that are submitted via POST and then parsed with PHP (has to be php because it connects to our database to get information needed). Here's a simplified example of a tool page:
<?php
$action = htmlspecialchars($_SRVER["PHP_SELF"]);
function getResults() {
if(isset($_POST["infoForQuery"])) {
//Do some sort of query to database and print out results
}
}
?>
<body>
<form action="<?php echo $action;?>" method="post">
<input type="text" name="infoForQuery">
<input type="submit" value="submit" />
</form>
<div>
<?php getResults();?>
</div>
</body>
I need to be able to use these tools inside the dashboard page, but whenever I try to submit a form, it just reloads the entire dashboard page, resulting in the POST data not existing (maybe this is because the PHP code is run before ajax loads the content into the dashboard page? not sure).
I know I can use AJAX to send the POST like so:
$(function() {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});
However, this does not allow me to use the data collected in the form to query a database and print results out on the page.
Is it possible to accomplish this without having to leave the dashboard page, and if so, how?
Edit: I believe I've figured it out! What I wasn't realizing was that when I overrode the submit function and used ajax to send the post instead, I could actually retrieve the result of that post and put it into my page. Here's what I did:
<script>
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'some_directory/pageToLoad.php',
type: 'post',
data: $('form').serialize(),
success: function(result) {
$("#main").html(result);
}
});
});
</script>
Could be because the submit event is not firing. Since your forms are loaded dynamically do it like this:
$(function() {
$(document).on('submit', 'form', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});

Load .php site in to div without reloading

I am trying to create the following scenario:
A form in my index file collects input from a user, which is used to do some computation. The results of this computation should be echoed to him in a nice interface on the same page without reloading.
Currently, the results.php page is receiving the inputs correctly. Now, I just want to show it back inside the results div on the main page without reloading the results.php. .load is the wrong command for that. I need something like ".show"... Any ideas?
html:
<form action="results.php" method="post" class="ajaxform">
//all the inputs
<input type="submit" value="see your results" class="button"/>
</form>
<div id="results">
//here he should see the results.php output
</div>
jQuery
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
alert('Form is successfully submitted');
setTimeout(function() {
$('#results').load('results.php');
}, 1000);
},
error : function(){
alert('Something wrong');
}
});
return false;
});});
change this
$('#results').load('results.php');
To
$('#results').html(data);
if the returned results in data variable.
If i understood your problem correctly, results.php recieves the output you would show in the div #result.
To use the return-data from ajax-request you have data as javascript variable. To show the result in the div you need the following statment in the success function from ajax-call.
$("#result").html(data);

Pass variables from HTML form -> ajax load()

What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.

Execute PHP function with onclick

I am searching for a simple solution to call a PHP function only when a-tag is clicked.
PHP:
function removeday() { ... }
HTML:
Delete
UPDATE: the html and PHP code are in the same PHP file
First, understand that you have three languages working together:
PHP: It only runs by the server and responds to requests like clicking on a link (GET) or submitting a form (POST).
HTML & JavaScript: It only runs in someone's browser (excluding NodeJS).
I'm assuming your file looks something like:
<!DOCTYPE HTML>
<html>
<?php
function runMyFunction() {
echo 'I just ran a php function';
}
if (isset($_GET['hello'])) {
runMyFunction();
}
?>
Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</html>
Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST), this is how you have to run a PHP function even though they're in the same file. This gives you a level of security, "Should I run this script for this user or not?".
If you don't want to refresh the page, you can make a request to PHP without refreshing via a method called Asynchronous JavaScript and XML (AJAX).
That is something you can look up on YouTube though. Just search "jquery ajax"
I recommend Laravel to anyone new to start off right: http://laravel.com/
In javascript, make an ajax function,
function myAjax() {
$.ajax({
type: "POST",
url: 'your_url/ajax.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
Then call from html,
Delete
And in your ajax.php,
if($_POST['action'] == 'call_this') {
// call removeday() here
}
It can be done and with rather simple php
if this is your button
<input type="submit" name="submit>
and this is your php code
if(isset($_POST["submit"])) { php code here }
the code get's called when submit get's posted which happens when the button is clicked.
You will have to do this via AJAX. I HEAVILY reccommend you use jQuery to make this easier for you....
$("#idOfElement").on('click', function(){
$.ajax({
url: 'pathToPhpFile.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
)};
http://api.jquery.com/jQuery.ajax/
Solution without page reload
<?php
function removeday() { echo 'Day removed'; }
if (isset($_GET['remove'])) { return removeday(); }
?>
<!DOCTYPE html><html><title>Days</title><body>
Delete
<script>
async function removeday(e) {
e.preventDefault();
document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
}
</script>
</body></html>
Here´s an alternative with AJAX but no jQuery, just regular JavaScript:
Add this to first/main php page, where you want to call the action from, but change it from a potential a tag (hyperlink) to a button element, so it does not get clicked by any bots or malicious apps (or whatever).
<head>
<script>
// function invoking ajax with pure javascript, no jquery required.
function myFunction(value_myfunction) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML += this.responseText;
// note '+=', adds result to the existing paragraph, remove the '+' to replace.
}
};
xmlhttp.open("GET", "ajax-php-page.php?sendValue=" + value_myfunction, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php $sendingValue = "thevalue"; // value to send to ajax php page. ?>
<!-- using button instead of hyperlink (a) -->
<button type="button" onclick="value_myfunction('<?php echo $sendingValue; ?>');">Click to send value</button>
<h4>Responses from ajax-php-page.php:</h4>
<p id="results"></p> <!-- the ajax javascript enters returned GET values here -->
</body>
When the button is clicked, onclick uses the the head´s javascript function to send $sendingValue via ajax to another php-page, like many examples before this one. The other page, ajax-php-page.php, checks for the GET value and returns with print_r:
<?php
$incoming = $_GET['sendValue'];
if( isset( $incoming ) ) {
print_r("ajax-php-page.php recieved this: " . "$incoming" . "<br>");
} else {
print_r("The request didn´t pass correctly through the GET...");
}
?>
The response from print_r is then returned and displayed with
document.getElementById("results").innerHTML += this.responseText;
The += populates and adds to existing html elements, removing the + just updates and replaces the existing contents of the html p element "results".
Try to do something like this:
<!--Include jQuery-->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
Click Me!
This is the easiest possible way. If form is posted via post, do php function. Note that if you want to perform function asynchronously (without the need to reload the page), then you'll need AJAX.
<form method="post">
<button name="test">test</button>
</form>
<?php
if(isset($_POST['test'])){
//do php stuff
}
?>
Try this it will work fine.
This will work without form tags and button tag.
<div onclick="window.location='?hello=true';">
<?php
if(isset($_GET['hello'])) {
hello();
}
function hello()
{
echo "hello world";
}
?>

Execute script after load input file

I have an input file field to select files to upload, and I use ajax to send these pics to server. For execute all script after a file is selected, I use submit, but I think it could be better not to include the submit button and use jquery to detect when I select the file and process the submit action then.
My code:
<script>
jQuery(document).ready(function () {
jQuery('#form_up').ajaxForm({
dataType: 'json',
success: bol
});
});
function bol(datab) {
if (datab.field_empty == "bad") {
jQuery(".bol_request_fail").fadeIn(3000);
} else {}
}
</script>
<form name="form" method="post" id="form_up" runat="server" action="indexer_upload_user_pic.php" enctype="multipart/form-data" style="margin:0px;">
<input type="file" name="upload[imagen][]" id="logo2" class="file-upload"/>
</form>
I use one plugin for send the fields and all form by this you can see ajaxForm function.
The question is: How I can avoid using submit and instead send the pic when it is selected via file input?
I didnt test it, but this might work:
jQuery(document).ready(function () {
$("#logo2").change(function(){
jQuery('#form_up').ajaxSubmit({
dataType: 'json',
success: bol
});
});
});
Check the Plugin API if this dont work, I just quick checked it, and saw there is a ajaxSubmit...

Categories

Resources