Receive data on php file send by jquery function - php

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/

Related

ajax data passing to php not working

Okay so, I've scoured stackoverflow for this answer and have come across several threads talking about how to do this, and well, they just haven't helped me yet.
This is all on one page, so that's probably the big problem. I really don't wanna send the post data to some other page and then redirect back to the one in order to get this to work, but I will if you guys cannot assist me in this endeavor.
Anyway, I have this page and I'm trying to pass data to the php via ajax, and I know that php is a server-side language, so the page would have to be reloaded once the data is passed.
php:
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
}
jquery:
var whateva = "hello";
$.post('index.php', {'location': whateva}, function(){
//alert(data);
//window.location.reload(true);
});
alert(data); does get it to work and echo out given the isset (and also prints out all of the other html), but that is an alert which isn't practical, especially from a user standpoint. But that means that this ajax function is working. The problem here is that I want the same page to load, just with the $_POST['location'] variable set, so I had the bright idea of just reloading the page as the function in this case, which doesn't work. The isset never succeeds
Any help will be appreciated, besides telling me that combining php and javascript is a horrible idea as I already know that
Edit:
I was told to try making another page to post the data back which still didn't work, here's the code for that (with the main page ajax adjusted to direct it there instead):
window.onload = function(){
var inter = <?php echo json_encode($_POST['location']); ?>;
$.post('index.php', {location: inter});
}
I have tried it with and without quotes around location in the .post. Also I have tried to just have the plain javascript there, without the onload, still nothing. The response on the main page when changed to this
$.post('intermediary.php', {location: whateva}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
it prints out the html of the hidden page, with the variable filled in (var inter = "hello" instead of having the php there, as it should), so the passing to that page works
Ok, here's the breakdown.
File one: index.html
This file is HTML and Javascript only, and is the page seen by the user. This could be a php page, but it does not need to be. Notice the quotes around the string 'whateva'.
<html><head></head><body>
<script>
$.post('intermediary.php', {location: 'whateva'}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
</script>
</body></html>
File two: intermediary.php
This file is PHP only. It receives data silently through POST and returns data by echoing it.
<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
} else {
echo 'No data received!';
}
?>
Oh.... It's a simple mistake. your ajax syntax is wrong... Remove the quotes of ajax parameter inside the curly brackets. Just like
var whateva = "hello";
$.post('index.php', {location: whateva}, function(){
//alert(data);
//window.location.reload(true);
});
It will working fine.... But you might use variable to ajax paramete then, you should use variable name for ajax location parameter value. But you might use string for location parameter value, then you should use it value inside the quotes like this, $.post('yourfile.php',{location:'your_name'},function(){});. But you might use some value of location parameter use should type this code.$.post('yourfile.php',{location:30},function(){});

PHP send form data more than one form/pages

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.

Problems with multiple PHP functions in the same file

I want to make an AJAX call to a php file called functions.php, where I have mutliple related functions (all making database changes to accounts, ie. add, edit, delete). I've been struggling with this, because the AJAX call seems to work fine, but the response that comes back from the server is empty (content-lenght: 0). I went back to square one and just used AJAX to send data to a php file that only contained the php code to handle that one call (ie. no functions), and it works fine. As soon as I wrap that simple statement into a function, it fails again. So something I'm doing causing the php not to send a respone when I'm wrapping it in a function.
Do you have to call a specific php function somehow from your ajax script, or somewhere in your form element? How does the php file know which function you're requesting in your ajax call if there are multiple functions? Or does it just sort it out by matching the $_POST element with the data being sent over, regardless of which function that $_POST element is in?
I suspect that my PHP code is to blame:
function delete_account(){
require(ROOT_PATH . "/inc/database.php");
$deleteAccount = $_POST['accountName'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
exit;
}
return;
}
Also, when I press the submit button and my ajax call is fired off, it immediately returns the success message in the browser, and as I'm watching the Network tab on my google dev tools window, the success message is displayed seemingly before the php file is even loaded. I've tried setting async: false.
Adding AJAX code:
function deleteAccount(){
event.preventDefault();
var accountName = $('.account_name').filter(":selected").attr("name");
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: {accountName:accountName},
async: false,
success: function(response){
$('#results').html(response + " has been deleted.");
}
});
};
If you have multiple functions in your PHP file, then you can do something like:: pass in extra parameter in you jQuery ajax, like:
$.ajax({
url: "some_file.php?action=get_accounts"
}).done(function() {
$( this ).addClass( "done" );
});
and in your PHP file use switch to call appropriate function depending on value of action variable in your ajax, like:
//in PHP
.....
$action = $_GET['action'];
switch ($action) {
case "get_accounts":
//call the function
get_accounts();
break;
case "otherFunction":
....
break;
}

HTML form stop redirect and allow PHP to call JavaScript from within the HTML file

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.)

Getting a value from a variable , send to php to process and add that value to mysql database?

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.

Categories