ajax load different php pages - php

How can I call functions on different pages?
For example if I click on the start button, it will run the code necessary to start the tomcat server.
Here is the code for the main page:
<input name="submit" class= "green" id ="start" type="submit" value=" Start ">
<input name="submit" id = "stop" class='red' type="submit" value=" Stop ">
Here's the second page that executes the program.
function (tomcatstart){
$ssh->exec('service tomcat start');}

There are a couple of different approaches you can take to accomplish this sort of task. Here's how I would do it:
Firstly, I'd replace the <input> tags with <button> tags. This is more personal preference than a real change in functionality, but since you're sending the request via AJAX, you don't need a form or inputs.
Secondly, I'd create the JS functions to make the AJAX request, something like this:
function start() {
$.post('urlToStart.php', {
data : 'Some data'
}, function(returnedData) {
//Optionally do something with the returned data, like alert 'Success' or 'Failed'
alert(returnedData);
});
}
Finally, you need a php page to handle the request. You can either have one page that handles both the start and stop requests, or you can have different pages for each one.
Example urlToStart.php:
<?php
$data = $_POST['data'];
if($data !== null) {
tomcatstart();
echo "Success";
}
else {
echo "Failed: " . print_r(error_get_last()); //Get the error message so you know what happened
}
function tomcatstart(){
$ssh->exec('service tomcat start');
}
And that should set you on your way

What you can do is
Add data-task attribute, so we can write single ajax to for
all
Add an additional class, trigger-ajax
change inputs to button or change the input type to button
make a jquery call on click event, using class we added
jQuery(".trigger-ajax").on('click', function(){
var _context = jQuery(this);
jQuery.ajax({
url: 'ajaxrequest.php',
type: "post",
data:{
task: _context.attr('data-task')
},
success:function(response){
console.log(response)
}
})
});
handle it in php
if(!empty($_POST['task'])){
switch(trim(strtotlower($_POST['task']))){
case "start-tomcat":
$ssh->exec('service tomcat start');
break;
case "stop-tomcat":
$ssh->exec('service tomcat stop');
break;
}
}

Related

Ajax/ Jquery in Zend framework

I’m using Zend framework (php) and I’m trying to submit a from using ajax/jquery.
Here’s the .phtml:
<form id="find">
<input type="text" name="name">
<input type="submit" id="submit" value="Submit">
</form>
Here’s the ajax/jquery part:
$(document).ready(function() {
$("#submit").click(function(){
$.ajax({
type:'POST',
url: "<?php echo SITE_URL;?>Training/test",
data:$('#find').val(),
success: function(response) {
alert (response);
}
});
});
});
Here, “Training” is the controller and “test” is the action inside the controller. The action has just 1 line of code which is echo “hello”. After the user types a number in the box and clicks on “submit”, the control has to go to the controller thus displaying “hello” on success. However, nothing happens when I click on it. Please help me. Thanks in advance.
You didn't name parametr in Ajax call
data:$('#find').val(),
change it to
data:{'param': $('#find').val()},
About Zend it doesn't matter if it's zend or not. You can handle request just providing proper URL. You can access param value in Zend via $this->getParam('param') method.
Also you don't prevent default submit action. Change your function to:
$("#submit").click(function(ev){
ev.preventDefault();
or use in the end of function return false;
I did not test your jQuery. But note you need the instruction event.preventDefault to ensure you haven't the normal form submit action.
The main problem is at your zend Controller because you need a
special response. I suppose you have a controller to perform the request logics. I'll name it AjaxController and I'll name the action ajaxrecuestAction to illustrate how to send a proper response.
<?php
// Filename: yourProject/module/ModuleName/src/Controller/AjaxController.php
namespace ModuleName\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AjaxController extends AbstractActionController {
public function ajaxrecuestAction(){
// This function is called by zend to procces your ayax request
// you must test if it's an xmlHttpRequest
$request = $this->getRequest();
$is_xmlHttpRequest = ($request->isXmlHttpRequest()) ? 1 : 0;
if(!$is_xmlHttpRequest){
// If not you must return a normal page, a message page
// perhaps a forgiven message page, etc. It depends on your site
// logics
}else{
// The solution's KEY
// You must disable the zend's normal output
$viewmodel = new ViewModel();
$viewmodel->setTerminal($is_xmlhttprequest);
// Proccess the input and prepare your output
$output = CallTheLogicsToPrepareIt($request->getContent());
// send your response
$response = $this->getResponse();
$response->setContent($output);
return $response;
}
}
**EDIT: Just noted that, in your HTML, you didn't give an ID attribute to the "find" field. Therefore $('#find').val() will give you an error, something like "cannot find method val() of undefined. Add the id=find tag to your and it should work.
** Other Edit: Sorry about the confusion. Your form has id=find but what you want to send to the server (I believe), is the value of the fields. So give an ID=name to your input then use:
var data = {find: $('#name').val()};
You should start by using your console to see if the event is triggered. Something like:
<script>
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log('Hello');
});
});
</script>
(You do use Fire bug or the Chrome dev tools, right) ? If not, look at the end of this post.
If you can see the Hello in your console, you're on the right path. Then try to set your url in a variable and try to check it in your console:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(url);
});
});
</script>
Then you should see the url in the console, meaning you're still doing good.
If that works, try to set the data and check the output in the same way:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(data);
});
});
</script>
Hoping everything still works (you saw the data), then try the actual full code and see if you have an error or something. Also, be sure to include an error function to your ajax call so you will have a response if something went wrong on the server.
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$.ajax({
type:'POST',
url: url,
data: data,
success: function(response) {
alert (response);
},
error: function(resp) {
alert(resp.responseText);
}
});
});
});
</script>
Some tools to help you out:
If you are using FireFox, use FireBug for your debugging: https://addons.mozilla.org/fr/firefox/addon/firebug/
If you are using Chrome (my personal favorite), learn a bit more about Chrome Developer Tools: https://developers.google.com/chrome-developer-tools/?hl=fr
If you are using IE, please switch to something else for development purposes, then try it in IE to make sure you code is compatible (most likely won't be but it will be easier to find out why it doesn't work afterwards).
As for the line e.preventDefault......, look into this SO post for more details: https://stackoverflow.com/a/15913969/1483513
Hope this helps !

returning value from ajax, back to the JS function that it

here is the problem.
i have HTML Form and it has a button submit with an onclick=validationFunction(). When i click this button, values from form goes to this function.
Now, in this function, the values of the form are cheenter code herecked ifenter code here they are correct or not. In addition, it has 1 input Field who has to be checked for validation, and also checked again from database to see it that value exists there. This part is done via ajax. Below the ajax call, there is a return value(boolen) for the function validationFucntion().
Now, what i want. i want either of the two things.
1) ajax should return true or false within its success
2) or ajax should send the value just below where the ajax call ends. By now, i m failing big times to do either of the things.
Here is a sample pseudo code.
function validationFunction()
{
validations checks in progress
$.ajax({
url:'checkIfNumberExists.php',
data : {
'number : num //this num is coming from above
},
method:'GET',
success: function(data)
{
console.log("Return Value = "+this.toReturn);
if( (this.toReturn) > 0 )
{
either return validationFunction from here or set a flag.
}
else
{
either return validationFunction from here or set a flag.
}
});
}
checkIfNumberExists.php
<?php
$num = $_GET['number'];
$toReturn = 0 ;
$queryCheckNo = mysql_query('SELECT * FROM `TABLE` WHERE `number_from_table`="'.$num.'" ');
while($row = mysql_fetch_assoc($queryCheckNo)){
$toReturn++;
}
echo ($toReturn);
?>
try this plug in
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and keep this inside your form
<form id="tempForm" enctype="multipart/form-data">
<input type="file" name="" id="" />
</form>
and you can find the plug in here

Trying to display errors next to input fields in ajax / jquery / php form

In this basic jQuery, AJAX, PHP form I want to display errors next to inputs instead of the bottom of the form. I use if(empty(something)) { jQuery here }. Why won't this work? Whats the best practice to do this? Thank you.
HTML:
Name:<input type="text" id="name" /> <span id="name_error"></span>
<input type="button" value="Update!" id="update" /> <span id="name_error"></span>
<span id="update_status"></span>
PHP
<?php
include('init.inc.php');
if(isset($_POST['name'])) {
$name = mysql_real_escape_string(htmlentities($_POST['name']));
if(empty($name)) {
?>
// Why wont this work here? It just outputs the the whole thing as text. in the update_status div (You can see that in the ajax part at the bottom of the code).
<script>
$('#name_error').text('Name required');
</script>
<?php
if(!empty($name)) {
$query = mysql_query("UPDATE users SET
name = '$name'
WHERE user_id = ".$_SESSION['user_id']."
");
if($query === true) {
echo 'Your settings have been saved';
} else if($query === false) {
echo 'Unable to save your settings';
}
}
}
// This is the jQuery / AJAX part -- no issues here. Just have it to include both parts.
$('#update').click(function() {
var name = $('#name').val();
$('#update_status').text('Loading...');
$.ajax({
type: 'POST',
url: 'page.php',
data: 'name='+name,
success: function(data) {
$('#update_status').text(data);
}
});
});
CODE UPDATED
Why aren't you checking for empty before the form submit?
You can stop the form submission and check for empty values with javascript, if all is clear then you can submit the form.
You can do this, but you are specifiying .text()
What you need to do is jQuery("#update_status").html(data);
jQuery("#update").click( function(){
if(jQuery.trim(jQuery("#name").val()) == ''){ alert("empty"); return false; }
jQuery.post("page.php", {name:jQuery("#name").val()}, function(html){
jQuery("#update_status").html(html);
});
});
Note that you PHP page is going to return more than just your intended code as it is now. It is going to try and return the form again also.
You need to wrap your processing and from in separate if/else statement. Better to put them in two separate files and keep ajax stuff separate.
That's a really bad way to do it. The reason it doesn't work is because that JavaScript needs to be parsed and run by the browser first, that's a whole different story and would involve using eval(). The better way to do it would be to send back a JSON object, then use it in your JavaScript to display the message to the user.

Make a jQuery $.post() to a PHP Controller, and then in the middle of it back to View, and then use $.get() to continue with the Controller

I am dealing with a View and Controller for a webpage, and I am trying to figure out how this would work:
Controller will initially define variables used in view upon page-load.
Once a user submits a form, it does an onclick jQuery function, which posts back to the controller.
The controller returns back to the View true or false, depending on whether the vote was successfully inserted into the database.
The View's jquery function continues, determining what to do next: if it was successful, perform another jQuery function.
the next jQuery function performs a $.get back to the controller, which determines the relevant variables to be used in the view.
Right now, mine works in terms of submitting the vote. However, I never see the alert pop-up when i'm running it, which leads me to worry that the set-up I have isn't working the way it should be.
Here is code from my PHP website controller:
if(!isset($_POST['poll'])) //UPON PAGE LOAD
{
//define relevant variables to be put into the view
}
if(isset($_POST['poll'])) //UPON jQuery $.Post() back to controller
{
if($_POST['poll']=='done')
$vote = 2;
if($_POST['poll']=='no')
$vote = 1;
$id = $_POST['id'];
$result = vote($user_id, $id, $vote); //inserts vote into Database
if( !$res )
echo json_encode(array('success'=>true, 'text'=>'success'));
else
echo json_encode(array('success'=>false, 'text'=>'fail'));
//I want ^this json data to be sent back to the jQuery of my view
}
if(isset($_GET['newListing']))
{
//code that would redifine relevant variables to be put into view
}
if(isset($_GET['newListing']) || !isset($_POST['poll']))
{
//code that does something--both upon page load and when needing to retrieve
//and define variables to put into view.
}
include('view.php');
Here is code from my HTML/jQuery website view:
<html>
<body>
<form name='poll' id='poll' >
<INPUT TYPE="radio" name='poll' value='done'checked/>Done it.<br/>
<INPUT TYPE="radio" name='poll' value='no'/>No.</br>
<button id='submit-vote' onclick="postVote();">Submit</button>
<INPUT TYPE='hidden' name='id' value='<?php echo $id; ?>'/>
</form>
</body>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function loadListing(){
$.get('controller.php?newListing=yes',function(data){
if(data.response == 'success'){
//something}
else{
return false;}
});
}
function postVote(){
$.post('controller.php', { poll: $('input:radio[name=poll]:checked').val(), id: $('input:hidden[name=id]').val()} , function(data){
if(data.success){
alert('data.text');
loadListing();
return true;}
else{
alert(data.text);
return false;}
},
"json");
}
</script>
</html>
Any help/suggestions appreciated!
EDIT:
From my View code:
the HTML:
<fieldset id='poll'>
<INPUT TYPE="radio" name='poll' value='yes' checked/>Yes!<br/>
<INPUT TYPE="radio" name='poll' value='done'/>Done it.<br/>
<INPUT TYPE="radio" name='poll' value='no'/>No.</br>
<button id='submit-vote'>Submit</button>
<INPUT TYPE='hidden' name='id' value='<?php echo $id; ?>'/>
</fieldset>
the jquery:
jQuery(function($){
$("#submit-vote").click(
function(){
alert("HELLO");
$.post('controller.php', { poll: $('input:radio[name=poll]:checked').val(), id: $('input:hidden[name=id]').val()} ,
function(data)
{
alert("THIS FUNCTION WORKS");
}, "json");
}
);
});
The controller is pretty much the same. When I click on the submit button now, the alert("HELLO"); is executed, and according to the Firefox's Firebug the $.post() does take place. However, the alert("THIS FUNCTION WORKS"); does NOT get executed.
I need help figuring out why that may be....
Thanks!
The problem is that json_encode creates a string. In your Javascript, however, you're trying to access it as if it's an object (data.success). You'd need to first use window.JSON.parse() to turn it into an object:
var dataObj = window.JSON.parse(data);
After doing that, you should be able to access dataObj.success.
To be honest though, I'm not sure why you're making it that complicated. Why not just return a simple string, such as "success" or "failure"? Then you don't need to encode the object in php or decode it in JavaScript. You'd simply do:
PHP
if( !$res )
echo 'success';
else
echo 'failure';
JavaScript
if(data === 'success'){
//do your stuff
}else{
//do other stuff
}
Edit in response to OP's first comment on this answer
Your JavaScript will regain control once the PHP script ends. In the code you posted, you include a view.php file at the end of the PHP script. I don't know what's inside view.php, and it's quite possible that including this file will cause your JS alert() to still not fire even if you make the changes I described above. That's because if there is any output (i.e. echo, print, etc.) that runs in the view.php file, that will get appended to the string created by json_encode. The result will be a string that can not be parsed by window.JSON.parse().
If you want the script to end after echoing "success" or "failure" (or your json_encoded version), simply put return; after the echo statement:
if( !$res ){
echo 'success';
else
echo 'failure';
}
return;
the include('view.php'); should ONLY to be put into the if(!isset($_POST['poll'])) //UPON PAGE LOADcode.

jquery ajax post - how to get data back?

I have a profile page that contains a series of images. I want to use jQuery to allow the user to delete an image from the server and have the page update without reloading the entire page. When it's successful, it will remove the image's containing div from the page. My delete function is PHP; fairly simple:
delete.php
<?php
if (isset($_POST['id'])) {
if (unlink($_POST['id'])) {
echo "success";
}
else {
echo "failure";
}
}
?>
(There's already user authentication in place just to get them to the page that calls delete.php.)
Here's the html of one displayed image - there can be up to 5 of these chunks one after another:
<div class="box">
<img src="uploads/t_10DOT_22C_1111_1300370702_3.jpg" />
<h5><a rel="external" href="uploads/10DOT_22C_1111_1300370702_3.jpg">See full version</a></h5>
<a href="#" id="10DOT_22C_1111_1300370702_3.jpg" class="delete" onclick="return ConfirmDelete();" >x</a>
<div class="clear"></div>
</div>
My jQuery so far looks like this:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(data){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The part I'm concerned with is the ajax post. How does the success part actually work? What do I need to do in my php file so that ajax knows whether the delete was a success or failure?
Once an ajax post request has finished executing the file you sent the request to, if there was no error, the code you add in the "success" section is executed, in this case
success: function(data){
/*The code you need*/
});
The previous part if where the code is executed, the "data" variable contains anything you return from your php file, it can be data, it can be a simple "true" or "false", you choose what to send to let your jQuery know if it was successful.
Hope this helps a bit.
Edit Note:
function(applyData){
if ( applyData.toString() == 'invalid' ){
$('#pollError').html('Global styles cannot be modified.');
$('#pollNotice').html('');
}
else{
$('#pollNotice').html('The changes to the style have been applied.');
}
});
The previous example is a live example of what you can do inside the function in the "success" event. There I handle an "invalid" status and otherwise it's successful, after that I refresh a couple DIVs in case of invalid or update a single DIV in case of success.
This is the php that executes:
if ( !$db->isGlobal($id_css)){
$data['id_poll'] = $id_poll;
$data['id_css'] = $id_css;
$data['css'] = $css;
$db->applyCssChanges($data);
}
else{
echo 'invalid';
}
You've two obvious options I can think of:
Your returned text should appear in the data parameter supplied to your success callback function - however you'll probably also need to make sure it's in a format compatible with the MIME Content-Type returned by your PHP, or jQuery might complain that it can't parse it, or:
Send back a 5xx Failure type message from your PHP using the header() function if the delete didn't work. That should then trigger an AJAX error callback, which you'll need to supply.
From delete.php return whether the delete succeeded or not. In the success even check for that data and handle it appropriately.
HTH.

Categories