How do I run a .php function file from a .js file - javascript

How do I send data from a JavaScript file to a PHP file so that it does what it needs to do in the PHP server side. I want to send a SMS and my JavaScript is reading all the data that is coming though so all that is left is that my PHP activates and sends the data in a SMS which is already done with my PHP file. I just need to make them connect to be able to send.
Can PHP handle functions? That is what I am trying to do here by sending the data to a function in PHP from my .js file. If not, how do I send them via post?
.js file:
render : function(template,params){
var arr = [];
switch(template){
case 'smsLine':
arr = [
'<div class=" sms-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
'" width="23" height="23" onload="this.style.visibility=\'visible\'" />',
'</span><span class="author">',params.author,
':</span><span class="text">',params.text,
':</span><span class="text">',params.to,
'</span><span class="time">',params.time,'</span></div>'];
///////////////////////////////HERE/////////////////////////////////
//this is where I want to use a function that is in a php file
sendSMS(params.author, params.text, params.time, params.to);
///////////////////////////////HERE////////////////////////////////
break;
}
return arr.join('');
}
This is the function that I want to use in my PHP file.
.php file:
function sendSMS($from, $message, $time, $to){
$objGsm = new COM("AxSms.Gsm", NULL, CP_UTF8 );
$objGsm->LogFile = sys_get_temp_dir()."Gsm.log";
//Windows default: 'C:\Windows\Temp\Gsm.log'
//Form submitted
$obj;
$strMessageReference;
$objSmsMessage = new COM("AxSms.Message", NULL, CP_UTF8 );
$objSmsConstants = new COM("AxSms.Constants" , NULL, CP_UTF8 );
$strName = 'Modem';
$strPincode = '';
$strRecipient = '$number';
$iDeviceSpeed = '0';
$objGsm->Clear();
$objGsm->LogFile = '';
$objGsm->Open($strName, $strPincode, $iDeviceSpeed);
if ($objGsm->LastError != 0){
$strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);
$objGsm->Close();
}
else{
//Message Settings
$objSmsMessage->Clear();
$objSmsMessage->ToAddress = $to;
$objSmsMessage->Body = $message;
$objSmsMessage->DataCoding = $objSmsConstants->DATACODING_UNICODE;
//Send the message !
$obj = $objSmsMessage;
$objGsm->SendSms($obj, $objSmsConstants->MULTIPART_ACCEPT, 0);
$objSmsMessage = $obj;
$strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);
$objGsm->Close();
}
}

If you pull in jQuery to your front-end, you'll be able to send an AJAX request to execute that PHP function for you. it would look something like this (inserted straight into that sendSMS section in the .js code:
$.ajax() {
url: "/send/sms",
type: "POST",
data: {
author: params.author,
text: params.text,
time: params.time,
to: params.to,
}
}
Now what you will have to do is create the file for the AJAX request to be sent to, they call this an "end point". In my example I set the path of this file to being /send/sms, so perhaps you have a directory called "send" where you could send off an email or SMS, etc. For each of those methods you would have a PHP file containing the logic for it. So for this example, create an sms.php file inside YOUR_ROOT_DIRECTORY/send .
Once you send an AJAX request to that file, the PHP function will be executed. To fetch the given data, use $_POST['author'], $_POST['text'], etc.

Related

ajax responseText contains php source code

I am trying to make a ajax call and validate a input html field. But, instead of getting simple echo message. I am getting complete source code in responseText.
JavaScript
function checkUsername() {
document.getElementById("username").className = "thinking";
usernameRequest = createRequest();
if (usernameRequest == null)
alert("Unable to create request");
else {
var theName = document.getElementById("username").value;
var username = escape(theName);
var url= "checkName.php?username=" + username;
usernameRequest.onreadystatechange = showUsernameStatus;
usernameRequest.open("GET", url, true);
usernameRequest.send(null);
}
}
function showUsernameStatus() {
alert(usernameRequest.responseText);
if (usernameRequest.readyState == 4)
{
if (usernameRequest.status == 200) {
if (usernameRequest.responseText == "okay") {
document.getElementById("username").className = "approved";
document.getElementById("register").disabled = false;
}
else {
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("username").select();
document.getElementById("register").disabled = true;
}
}
}
}
checkName.php
<?php
$takenUsernames = array('bill', 'ted');
sleep(2);
if (!in_array($_REQUEST['username'],$takenUsernames )) {
echo 'okay';
} else {
echo 'denied';
?>
Previously, I tried to integrate PHP into tomcat, but I was advice it was not a good practice. TRIAL TO INTEGRATE PHP
What I can make out of this situation is that Tomcat is not parsing PHP file and instead it is returning the source code. I believe there should be a means for me to let tomcat parse php files and send the right response.
I have also tried with simple php code, with one statment <?php echo 'HELLO'; ?> and I still get the source code.
Thanks in advance.
NOTE : I do not know php, I am working an example from HEAD FIRST AJAX
you need to install PHP for Tomcat & set its path to compile it.see the below link for php configuration settings.
http://php-java-bridge.sourceforge.net/doc/tomcat6.php
http://www.studytrails.com/blog/php-on-a-java-app-server-apache-tomcat-using-quercus/

Validating a directory from a javascript page using $.post to call a webservice PHP function

I am trying without success to use the $.post function to test (via a webservice that calls a PHP function "is_dir") if a folder already exists on a server and then I want it to return a string or boolean value back to my javascript page before I proceed to dynamically write the new files that will be placed there. The file path of the folder to be tested is "built" using jQuery which captures form data. I need to define (in a variable) if the directory exists and then be able to access that variable from outside of the $.post function (not from within, using success callback). This is so I can proceed in javascript as follows:
if {directory exists} then
capture more form data (via jQuery) and
$.post to webservice that calls PHP to update database
Outside of the $.post function, the value of my return variable is undefined.
I think I may be over-complicating this. Any suggestions? Thank you, in advance.
Please see my comment to #Steve above:
<script type='text/javascript'>
//function gathers form data, validates constructed file path and then writes to DB
function post_FormData() {
var week_number = $("#form_week_number").val();
var program = $("#form_program").val();
var course = $.trim($("#form_course_number").val());
var form_content_type = $("input:radio[name=content_type]:checked").val();
var content_type = "";
var activity_title_Val = $.trim($("#form_activity_name").val());
var activity_title_Split = activity_title_Val.split(" ");
var activity_title_Clean = new Array();
//this for-loop constructs a valid directory folder name from form data
for(var i=0, l=activity_title_Split.length; i<l; i++) {
activity_title_Split[i] = activity_title_Split[i].replace(/[^a-z0-9\s]/gi,"");
activity_title_Clean[i] = activity_title_Split[i];
activity_title_Split[i] = activity_title_Split[i].replace(/\b[a-z]/g, function(letter){return letter.toUpperCase();});
}
var activity_title = activity_title_Split.join("");
var file_path = "";
file_path += "/CourseFiles/" + program + "/" + program + course + "/" + content_type + "/Week" + week_number + "/activity-" + activity_title;
var message = "<div id=\"confirmation_container_contents\"><p><b>Confirm Content Repository file path: </b><br></p>";
//begin web service call to PHP function
$.post('webservices/create_PA_webservices.php', {web_service: "go_check_if_exists", data_file_path: file_path}, function(data){
var exists = data.does_exist; //json_encoded RESPONSE FROM ASYNC REQUEST
if(exists == "Y") {
message += file_path;
message += "<br><br><br><center><b>An activity folder with this name already exists.</b></center>";
message += "<br><br><center>Please edit the activity title and resubmit.</center>";
message += "<br><br><br><center><input type=\"image\" src=\"pa_images/editButton.jpg\" id=\"editButton\" value=\"edit\"></center></div>";
$("#confirmation_container").empty();
$("#confirmation_container").append(message);
}
else if(exists == "N") {
message += file_path;
message += "<br><br><center><input type=\"image\" src=\"pa_images/editButton.jpg\" id=\"editButton\" value=\"edit\">";
message += "&nbsp\;&nbsp\;&nbsp\;<input type=\"image\" src=\"pa_images/confirmButton.jpg\" id=\"confirmButton\" value=\"confirm\"></center></div>";
$("#confirmation_container").empty();
$("#confirmation_container").append(message);
}
$(function(){//edit proposed file path
$("#editButton").click(function() {
$("#confirmation_container").empty();
});//end function edit path button
});//end anonymous function
$(function(){//confirm proposed file path and write to DB
$("#confirmButton").click(function() {
go_post_FormData(activity_title_Val, file_path, week_number, program, course, content_type);
$("#create_practice_activity").hide();
$("#build_practice_activity").show();
$("#activity_is_new").val("N");
});//end function confirm path button
});//end anonymous function
}, "json").fail(function() {alert("The go_check_if_exists webservice call has failed");}); //end web service call
}//end function post_FormData declaration
</script>

How to send variable from javascript to PHP on azure websites?

To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!

How do you access other files stored on an website with JavaScript?

I am trying to write a webpage for a list of files to download. The files are stored with the webpage and I want the webpage to dynamically list all the files in the folder to download. That way when more are added I don't have to modify the webpage. I know how to use JavaScript to create links on the webpage but I need to use it to find the names of the files first.
I found a website that had code for navigating files like a file browser but it only uses a string to store the current location.
This is in the header:
<script type="text/javascript"><!--
var myloc = window.location.href;
var locarray = myloc.split("/");
delete locarray[(locarray.length-1)];
var fileref = locarray.join("/");
//--></script>
this is in the body:
<form>
<input type=button value="Show Files" onClick="window.location=fileref;">
</form>
However this doesn't really help since I am trying to create download links to files not have a file browser.
Edit:
When you host a traditional HTML page you upload the htmlfile and any images or content for the page to what ever server you use.
I want to use javascript to dynamically link to every file hosted with the webpage.
I am trying to combine this with hosting the files in a Dropbox public folder for a simple way to make the files available.
If you want a list of files on the server you will need to use a server-side script to gather their names:
JS--
//use AJAX to get the list of files from a server-side script
$.getJSON('path/to/server-side.php', { 'get_list' : 'true' }, function (serverResponse) {
//check the response to make sure it's a success
if (serverResponse.status == 'success') {
var len = serverResponse.output.length,
out = [];
//iterate through the serverResponse variable
for (var i = 0; i < len; i++) {
//add output to the `out` variable
out.push('<li>' + serverResponse.output[i] + '</li>');
}
//place new serverResponse output into DOM
$('#my-link-container').html('<ul>' + out.join('') + '</ul>');
} else {
alert('An Error Occured');
}
});
PHP--
<?php
//check to make sure the `get_list` GET variable exists
if (isset($_GET['get_list'])) {
//open the directory you want to use for your downloads
$handle = opendir('path/to/directory');
$output = array();
//iterate through the files in this directory
while ($file = readdir($handle)) {
//only add the file to the output if it is not in a black-list
if (!in_array($file, array('.', '..', 'error_log'))) {
$output[] = $file;
}
}
if (!empty($output)) {
//if there are files found then output them as JSON
echo json_encode(array('status' => 'success', 'output' => $output));
} else {
//if no files are found then output an error msg in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
} else {
//if no `get_list` GET variable is found then output an error in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
?>

Zend_Form Jquery & fileUploadErrorIniSize

Edit, I fixed it by changing my JS to:
$('.zend_form input:not([type="file"]), .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
Hello,
As I posted earlier, I followed a ZendCast that allowed you to use jQuery to detect and display to users problem with their form.
However, file fields always return: fileUploadErrorIniSize (File 'image_front_url' exceeds the defined ini size" even if the file is within size limits.
TPL For Forms:
<?php $this->headScript()->captureStart(); ?>
$(function() {
$('.zend_form input, .zend_form textarea').blur(function() {
var formElementId = ($(this).parent().prev().find('label').attr('for'));
doValidation(formElementId);
});
});
function doValidation(id) {
var url = '/<?php echo MODULE; ?>/json/validateform/form_name/<?php echo get_class($this->form); ?>';
var data = {};
$('.zend_form input, .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
$.post(url, data, function(resp) {
$('#'+id).parent().find('.errors').remove();
$('#'+id).parent().append(getErrorHtml(resp[id], id));
}, 'json');
};
function getErrorHtml(formErrors, id) {
var o = '';
if (formErrors != null) {
var o = '<ul id="errors-'+id+'" class="errors">';
for (errorKey in formErrors) {
o += '<li>'+formErrors[errorKey]+'</li>';
}
o += '</ul>';
}
return o;
}
<?php $this->headScript()->captureEnd(); ?>
<?php
if (is_object($this->form) && $this->form->getErrorMessages()) {
echo $this->partial('partials/errors.phtml', array('errors' => $this->form->getErrorMessages(), 'translate' => $this->translate));
}
?>
<?php if (isset($this->errorMsg)) { ?>
<p><?php echo $this->errorMsg; ?></p>
<?php } ?>
<?php echo $this->form; ?>
Which is directed to
<?php
class Administration_JsonController extends Zend_Controller_Action {
public function validateformAction() {
$form_name = $this->_getParam('form_name');
$form = new $form_name();
$data = $this->_getAllParams();
$form->isValidPartial($data);
$json = $form->getMessages();
$this->_helper->json($json);
}
}
Example of returned json:
{"name":{"isEmpty":"Value is required and can't be empty"},"name_url":{"isEmpty":"Value is required and can't be empty"},"image_site_url":{"fileUploadErrorIniSize":"File 'image_site_url' exceeds the defined ini size"},"image_url":{"fileUploadErrorIniSize":"File 'image_url' exceeds the defined ini size"},"image_front_url":{"fileUploadErrorIniSize":"File 'image_front_url' exceeds the defined ini size"},"image_back_url":{"fileUploadErrorIniSize":"File 'image_back_url' exceeds the defined ini size"}}
I noticed a few people had this issue and they said that isValidPartial fixes it, so I changed
$form->isValid($data);
to
$form->isValidPartial($data);
but it didn't fix this issue.
Any ideas?
The problem is that you can't treat file fields in the same manner as regular text fields.
When you call $('input').val(), you get an actual text value for the text field, but for the file field you get the file name - and not the file contents.
Then your script tries to validate your file name as a file and, apparently, fails. In order for file validator to succeed you need to pass actual file contents to the script.
So, basically, you need to upload a file asynchronously to the server to perform all the necessary validations.
Unfortunately, uploading files via Ajax is not quite a trivial thing to do. Your basic options are uploading files via iFrame or swfObject. You can take a look at the broad selection of plugins suitable for this purpose here.
My personal choice for asynchronous file upload would be file-uploader jQuery plugin.
Are you putting an Encrypt type on your form?
I have found two different forum posts about this, including a stack post:
odd Zend_Form_Element_File behavior
You need to add enctype="multipart/form-data" to your form tag.
Basically what is happening is the form is using its default "application/x-www-form-urlencoded" method of encryption before it is sent to the server. File uploading is not supported with this method.

Categories

Resources