I was trying to build web application where user clicks a button and it prompts them to enter email address using JavaScript prompt functionality like this.
function mail_me(x)
{
var person = prompt('Please enter your email Address','emailme#me.com');
}
than I want to call PHP function inside my JavaScript and pass person as parameter of that PHP function. Is it possible to do it. I have tried this so far.
function mail_me(x)
{
var person=prompt('Please enter your email Address','emailme#me.com');
alert('<?php mail_tome('person'); ?>');
}
Its not possible, PHP is processed on the server, while Javascript is rendered on the client side after the server has completed it works.
You would need to use Ajax to take the value of person, and pass it via ajax back to a php script on the server which would then process your request.
http://api.jquery.com/jQuery.ajax/
Such a thing is impossible. PHP is executed on the server, and the result is passed to the browser.
You can, however, use AJAX to send the variable to the server. Example:
var a = new XMLHttpRequest();
a.open("POST","/path/to/script.php",true);
a.onreadystatechange = function() {
if( this.readyState != 4) return;
if( this.status != 200) return alert("ERROR "+this.status+" "+this.statusText);
alert(this.responseText);
};
a.send("email="+person);
This will cause whatever the PHP script echos to the browser to appear in the alert. Of course, you can customise this as much as you like, this is just a basic example.
You need something that is called AJAX. If you know and using JQuery it has built in functionality for AJAX.
Example:
function mail_me() {
var person = prompt('Please enter your email Address','emailme#me.com');
$.ajax({
type: 'post',
url: URL TO YOUR SCRIPT,
data: {
email: EMAIL_VARIABLE
},
success: function(result) {
//handle success
}
});
}
Related
I am a PHP beginner.
I want to send a form data to more than one form/pages. Is it possible?
It sends data to use.php. But I want that it also sends data to two more PHP files: lock.php and unlock.php.
How is it possible?
Make your formdata go to one script, and simply include to the other scripts and they'll have access to the $_POST variable as well.
I use this a lot myself. I have a script where everything runs through the index.php file, but functions are stored in different php files depending on what they're doing. My index.php includes all the php files I need, and inside these php files I have scripting like this:
index.php:
<?php
include('pagename.php');
include('otherpage.php');
echo $return; //output from previous pages
?>
and pagename.php:
<?php
if( $_GET['page'] != 'pagename' )
{
return ('');
}
if( isset($_POST['var']) )
{
// some code
}
You can use Ajax on a client side. I recommend Jquery because it is very easy to start with, or you can use CURL on server side, but it is much more complicated, you can find a bunch of tutorials, just google: sending post data with curl.
Now Jquery Ajax approach:
Lets say your form has an ID of myForm:
make a selector:
$(document).ready(function () {
$("myForm").submit(function (e) {
e.preventDefault(); //prevent default form submit
var url1 = 'your path to url1';
var url2 = 'your path to url2';
var url3 = 'your path to url3';
sendAjax(data,url1);
sendAjax(data,url2);
sendAjax(data,url3);
//do the regular submit
$(this).submit();
});
function sendAjax(data,url){
$.ajax({
url: url,
type:'POST',
data: data,
success: function (data) {
//here you do all the return functionality
},
cache: false
});
});
}
What have we done here:
prevented default sending of form,
made X ajax requests, and send the form normally.
We have made a function for simple ajax handeling just to make our code cleaner.
The problem with this method is that you must make form checking in javascript before you start sending.
I have the following function that is called when I click on a button to submit a form:
function dadosFormularios(preenchimentoForm){
//var path = document.location.pathname;
//alert(path);
alert(preenchimentoForm);
//window.location.href = 'wp-content/themes/template/index.php';
var qstringA = '';
//dados dos campos
var nome=document.getElementById("nome").value;
qstringA = 'nome='+ nome;
//alert(qstringA);
if(preenchimentoForm==false){
alert('Please correct the errors in the Form');
}
else{
if(preenchimentoForm==true){
window.location.href = 'index.php?'+qstringA;
return false;
}
}
}
Since I'm using this way of processing the data, how can I alert my page index.php that the data sent by the function arrived on the index? I can't use a if (isset($_POST['button']..) since I send the information by the function and not through the button of the form, right?
window.location.href = 'index.php?'+qstringA;
This line is just redirecting to index.php with a query string ?nome=nome_value.
For example. index.php?nome=nome_value
So, in your index.php You can simply get everything posted with $_GET.
Check it by doing a print_r($_GET); there.
In index.php, you can simply check
if(isset($_GET["nome"])){
//Nome is set
//Do something here
}
P.S. Although, without knowing the other circumstances or reasons behind usage of this function, it can be said that this function is just doing what a simple <form action=index.php> would have done.
P.P.S. Although you have mentioned jQuery in title and also tagged it, I am not sure this function is using any of the jQuery code. I think it is just a simple Javascript function.
If you're using jQuery, check out .ajax(). Just remember, it's asynchronous, so the results may not be what you think they are. You don't need to reload the whole page (which is what your window.location.href = 'index.php?'+qstringA; would do) just to submit information.
If you want to alert or something when the ajax call completes, you can define a function to call on a successful ajax call.
Use ajax() like :
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
http://api.jquery.com/jQuery.ajax/
I'd like to have a form on a HTML page not refresh when it's sent, which I've done, but I'd also like to allow the echo command in the PHP file to be able to call JavaScript from within the HTML file.
So far, all the echo commands aren't being carried out, which isn't what I expected.
Here's some code from the HTML and PHP files:
HTML:
<script type="text/javascript">
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
var content = $(this).serialize();
$.post('signup.php?', content);
return false;
});
});
</script>
and the PHP:
echo '<script type=\'text/javascript\'>functionInFile()</script>';
So basically, I'd like the PHP file to be able to invoke a function in the HTML file, while not being redirected when I click submit.
Any help appreciated.
You can use the success callback of the $.post() to execute a function which your PHP passes back. Try this:
PHP
// do some stuff with the posted data
echo 'functionInFile'; // name of js function to execute in calling page
jQuery
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
$.post(
'signup.php?',
$(this).serialize(),
function(func) {
window[func]();
},
'text'
);
return false;
});
});
It could be better to use the callback function of post
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [,
dataType] )
So you would execute what ever code is within the reply or pre determined login onsusccess
$.post( 'signup.php?', content,
function( data ) {
//data contains the reply of the post so you can
//exec the code like this using JavaScript
//altogether eval is frowned upon because it is high overhead and opens
//opens up to code injection or whatever
//eval(data);
//so you just execute whatever method you need
functionInFile();
//or you reply from server in json and converto tobject
//reply: {'executeFunction': true}
var obj = jQuery.parseJSON(data);
if (data.executeFunction == true) { functionInFile(); }
}
);
ParseJSON
In order for PHP echo to work. the page MUST reload baecause it is server side.
A webpage cycle is SERVER SIDE, then Client side.
[SERVER] -> [CLIENT -> AJAX to SERVER -> SERVER REPLY ATTACH]
It looks like you're sending the right <script> tag. XHR return values are treated as data though, not executable code. Luckily for you, jQuery has code to check if you insert a <script> tag into the dom and execute it. You should be able to just do:
$.post('signup.php?', content, function(html) {$(document).append(html);});
and your script will execute.
(I would recommend making this happen in a different way though. I've worked on Apps that send large portions of javascript back in AJAX calls, and it's a pain to debug. It would be much better to send back a JSON object with a string for the next action, then keep an object of "approved" actions as a string -> function lookup table.)
I have an jquery ajax request that calls a PHP script that will send an email. This email is happening from the admin, so a user must be authenticated in order to be able to do this. I've got two questions:
How can I lock this PHP file down from somebody being able to go directly to the path in the browser and keep submitting it?
How do I only run the file if the user is authenticated?
PHP:
$emailer = new GiftCardEmailer();
$emailer->SendGiftCardEmail($gift_card);
jQuery:
$(document).ready(function() {
var status = $('p#status');
status.hide();
$('#sendemail').click(function() {
$.ajax({
url: 'mail-handler.php',
beforeSend: function() {
status.fadeIn();
status.html('<img src="images/ajax-loader.gif" />');
},
success: function( data ) {
if (console && console.log){
console.log( 'Sample of data:', data.slice(0,100) );
}
status.html('Email Sent Successfully.');
setTimeout(function() {
status.fadeOut();
}, 4000);
}
});
});
});
One approach would be to check for a valid session at the head of the file containing the actual mail code. If no session exists then simply terminate the script.
Check out ajax and security, might be helpful.
I do all of mine with session_start() at the top of a php page and then check for my specific session variables for authentication.
No session, no access.
Many websites have an "check availability" button. And I want to have this to. But this seems to be only available when using Ajax and Jquery. Is there any way for me to do this using only PHP and Javascript. Because i'm a starting programmer, which does not have the skills to work with Ajax or Jquery.
What I want, I have a username field. I typ in a username, and I want to check if the name is available. If the person clicks on the check availability button, I want a pop-up that says "This username is available" or "This username has already been taken".
If any knows how to do this in just PHP and Javscript, I would be very obliged to know.
Using ajax (and jquery) is easier than it seems. on your client-side you have a request like this:
$.ajax({
url: 'usernameChecker.php',
dataType: 'GET',
data: 'username=' + $("#yourUserNameFieldID").val(),
success: function(result)
{
alert(result);
}
});
Of course you need to include jquery to implement this. jQuery makes it easy to make ajax-calls.
On your serverside you can use something like this:
<?php
if(isset($_GET["username"]))
{
// check username
if(username_is_free)
// of course this needs to be a bit different, but you'll get the idea
{
echo "Username is free!";
}
else echo "Username is taken!";
}
?>
$(document).ready(function(){
// available-button is the ID of the check availability button
//checkAvailability.php is the file which gets the username param and checks if its available
// user is the id of the input text field where the user enter the username
// available-message is the id of a div which displays the availability message. Use this instead of alert
$('#available-button').click(function() {
$.ajax({
type : 'POST',
url : 'checkAvailability.php',
data: {
username : $('#user').val()
},
success : function(data){
$('#available-message').text(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("Some Error occured. Try again")
}
});
return false;
});
});
Use jQuery ajax, that is the best & easy way to do it.
Using Ajax send a request to a php page which will take username as parameter (get or post method, you can specify in ajax call) and then on server side search for uniqueness of username in database & return appropriate response.
Is there any way for me to do this using only PHP and Javascript.
Because i'm a starting programmer, which does not have the skills to
work with Ajax or Jquery.
I think you'll find making an AJAX request in jQuery a lot more simple than writing one in pure javascript.
As jQuery is an extension on Javascript, you can use minimal jQuery to make the request to the server, and then deal with the response using pure javascript.
Look into using jQuery AJAX:
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Here you would change the success part to something like:
success: function(data){
if (data == 1){
$(".message").html("Available");
}
else {
$(".message").html("Already Taken");
}
}
I would recommend using jQuery for this task.
jQuery (or another Javascript library) will make the task simple to complete compared trying to do it without using one of them.
jQuery docs are good and for there are plenty of online tutorials matching what you want to do.
You will benefit from putting in the time to learn about the jQuery library.