POST works, but php do not recognize it - php

I've seen a lot of examples of the same but it just doesn't work for me! I really don't know what is wrong with my code. When I perform a post via
window.location.href = "teste.php?name=" + javascriptVariable;
it work perfectly, but sadly, reloads the page, and I really don't want it.
So the only solution I've seen was to do it via jQuery. So here is what I am doing.
<script>
function opa() {
//var javascriptVariable = "John";
//window.location.href = "teste.php?name=" + javascriptVariable;
//alert (dataString);return false;
var dataString = "axius";
$.ajax({
type: "POST",
url: "http://localhost/teste.php",
data: {
name : dataString
},
success: function() {
alert("postado!");
}
});
return false;
}
function opa2() {
alert("<?php
if(isset($_POST['name'])){
$value = $_POST['name'];
} else {
$value = "NotWorking";
}
echo $value;
?>");
}
</script>
<button onclick="opa();"> AperteOpa1 </button>
<button onclick="opa2();"> AprteOpa2 </button>
The POST works PERFECTLY, when i see it at the web console at Firefox, it happens pretty well, and i can see the values at the parametters. I think the problem is with the PHP that don't recognize the data. I've tried to perform POST request trough
xmlhttp.open();
but it didn't worked too, same problem, the post happen, but the php don't recognize...
what's wrong with the code?

Your code does work, But it never gets called.
The ajax call doesnt reload the page, So when the page was processed, there was no $_POST['name'] there.
The ajax version of the page will have that variable set, but the one your currently running in does not.
Your process is
GET PAGE => => show post name
AJAX Request => Post =>
It should be
GET PAGE =>
AJAX Request => post => show post name
As you can see, The Ajax request doesnt touch the post name in your version. You need to get the data from the ajax request and then do something with that. Not the original page version
Your post should return something javascript can parse, Either plain text or JSON

The problem is that the page is generated by PHP first while the POST variable isn't set. The ajax request does not cause the page to reload, so it doesn't get regenerated, so this code never sees the submitted data.
I'm not sure what you're really trying to accomplish, so I can't suggest the proper way to fix this, but it seems you have an incomplete understanding of how and when server side and client side processing happen.

The problem is that you are posting to a different script (teste.php) and not the same script you are trying to run the javascript from.
While some say that you can't mix PHP and Javascript, I disagree. PHP happens before (on the server side) so your intuition was ok. The only problem is that the $_POST will not contain any value (unless you access it from teste.php).
You need to send the data back from the php file to the success function:
success: function(response) {
alert(response);
}
Also, just for general information, I'd rather replacing
if(isset($_POST['name'])){
$value = $_POST['name'];
} else {
$value = "NotWorking";
with
$value = isset($_POST['name']) ? $_POST['name'] : 'NotWorking';
It is much cleaner!
Hope this helps!

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.

PHP SCript Not Accepting AJAX Data

This is really bizarre. I am trying to submit data to the server and have a PHP script parse the data and then send back a response. A correctly formed URL is being sent:
http://localhost/ajax/test.html?row=rec_no_1
, but the server does not seem to respond with content from the PHP script despite a return code of 200. In fact, Developer Tools (in Google Chrome) doesn't say anything about the PHP file. The AJAX "data" statement must be formatted properly otherwise I wouldn't get the correct URL. POST (instead of GET) doesn't help.
If I change the AJAX data to a string, then it works fine. This implies there is something wrong with the AJAX data. But I can't understand what given that the URL is correctly formed and does change depending on which row I select.
Any ideas?
Here is the Javascript:
$(document).ready(function() {
$(".submit").click(function() {
$.ajax({
type: 'GET',
url: 'getTable.php',
dataType: 'html',
data: {row: $('input[type='checkbox']:checked').val()},
//data: {row: 'rec_no_2'},
success: function($result) {
$('.tableHolder').text($result);
}
});
return false;
});
});
Here is the PHP code:
<?php
if (isset($_GET['row'])) {
$tableRow = $_GET['row'];
echo $tableRow;
}
else
echo 'TEST';
?>
Your syntax is incorrect:
$('input[type='checkbox']:checked').val()
You should use double quotes around checkbox:
$('input[type="checkbox"]:checked').val()
Anyway do a console.log( $('input[type="checkbox"]:checked').val() ) before the ajax call just to find out which value is being sent.
Try moving your javascript file to server. Ajax don't work on cross domain. You are running the javascript file on localhost and trying to fetch information from live server. Keep both php and javascript file on same server, either live or localhost. It will work fine.
One more thing, try changing the url parameter of your ajax request. try complete url or try putting or not putting a slash / before your filename.

Receive data on php file send by jquery function

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/

Simplest jQuery, PHP, AJAX, and sqlite example?

I'm having a really difficult time understanding how this all works together. I've fiddled for a few days with this and have been unable to come up with any results. I'm trying to fill in a text field in a form, and when the form is submitted, I want to add the text to my sqlite db using ajax.
I understand that you need a $.get call in jquery which is triggered on the form's submit. That seems to work fine as I can trigger js alert boxes from there. However, when I pass the address of the php script which has lines to add to the sqlite db using PDO, nothing is added to the db. However, when I run this php script from using php cli, something will get added to the db.
I seem to be missing an essential step here. I would really appreciate it if someone could bridge this gap for me!
Edit:
As requested by Martin here's some code:
My php generates some list like this with a form in the middle:
<ul>
<li>hello</li>
<li id="formItem">
<form action="" method="post">
<input type=text name="content"/>
</form>
</li>
<li>world</li>
</ul>
Then my jquery code looks to add whatever is in the textbox right above it on the list does an ajax call. This is inside a $(document).ready(function(){.
$("form").submit(function() {
var inputText = $("input").val();
$.ajax({
type: "POST",
url: "add.php",
data: inputText,
success: function() {
$('#formItem').prev().after(
"<li>" + inputText + "</li>"
)}
});
});
My add.php file looks like this and it will insert something into my db if I execute the php script on the cli:
<?php
$base = new PDO('sqlite:todo.db');
$sql = $base->prepare("INSERT INTO ThisTable (content, priority) VALUES ('lolololol', 1);");
$sql->execute();
$base = null;
?>
Do not forget that HTTP is a stateless protocol. Each HTTP request you make to your webserver is treated the same. This stands for whether the HTTP request was made using AJAX or not.
What I'm trying to say is that AJAX is a client side implementation. All AJAX means is that you can interact with your webserver without having to reload your page. Implementing an AJAX request for the first time in JavaScript is often a brain bender, because the requirement of callbacks and the general asynchronous nature of the interaction makes it difficult to grasp.
On the server however, there should be nothing to worry about. An AJAX request is still an HTTP request, so whether you navigate to http://www.yourwebsite.com/ajax/interact.php?a=1&b=2 in your browser, or make a HTTP GET request using AJAX, your PHP script will still behave exactly the same. If you var_dump($_GET); in either situation, you will get an array whose a and b members equal 1 and 2 respectively.
If you can emulate the AJAX request in your browser successfully by navigating to the URL manually, that's the server work done.
Having established that, your JavaScript should look something like this:
$('#yourForm').bind('submit', function (event) {
jQuery.get('/ajax/interact.php', 'a=1&b=2', function (response) {
alert("AJAX request succeeded, response from the server was: " + response);
});
event.preventDefault();
});
Once you're confident using jQuery's AJAX methods, you might want to look at methods such as serialize() to help you out, and you can develop your jQuery code to something as follows:
$('form.ajax').live('submit', function (event) {
var self = $(this);
jQuery[(self.attr('method') || 'get').toLowerCase()](self.attr('action'), self.serialize(), function (response) {
alert("AJAX request succeeded, response from the server was: " + response);
});
event.preventDefault();
});
Hope this helps :)
Your submit function should return false;

Categories