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.
Related
i need a a script that will refresh the functions:
$ping, $ms
every 30 seconds, with a timer shown,
i basicly got this script:
window.onload=function(){
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds;
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();
}
but it refreshes the whole page, not the functions i want it to refresh, so, any help will be appriciated, thanks!
EDIT:
I forgot to mention that the script has to loop infinatly
This here reloads the whole page:
window.location.reload();
Now what you seem to want to do is reload portions of the page, those portions having been generated by php functions. Unfortunately php is server side so that means you cant get the client browser to run php. Your server runs the php to generate stuff that browsers can understand. In a web browser open a page you made using php and choose to view source and you'll see what I mean.
Here's what you'll need to do:
Make your two functions ping and ms accessable via ajax
Instead of window.location.reload() do a call to jQuery.ajax. on success write to your page
Here's what I think would be the ideal way of dealing with this... I haven't seen the php side of your problem but anyway:
make a file called ping.php and put all your ping function code in there. ditto for ms
in your original php file that called those functions, make a div at each point where you wanted a function call. Give them appropriate ids. Eg: "ping_contents" and "ms_contents"
You can populate these with some initial data if you want.
In your js put in something like this:
jQuery.ajax(
{
url : url_of_ping_function,
data : {anything you need},
type : 'POST', //or 'GET'
dataType: 'html',
success : function(data)
{
document.getElementById("ping_contents").innerHTML = data;
}
});
do another one for the other function
What you want is AJAX, Asynchronous JavaScript and XML
You can use jQuery for that.
I can put an example here, but there is a lot of information to be found on the internet. In the past I wrote my own AJAX code, but since I started using jQuery, it's all a lot easier. Look at the jQuery link I provided. There is some usefull information. This example code might be the easiest to explain.
$.ajax({
url: "test.php"
}).done(function() {
alert("done");
});
A some moment, for example on a click on a button, the file test.php is executed. When it's done, a alert box with the text "done" is shown. That's the basic.
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
}
});
}
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 am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.