ajax data passing to php not working - php

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(){});

Related

POST works, but php do not recognize it

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!

Calling a php function using ajax/javascript

Ok guys I know this question has been asked before but I am very new to PHP and JavaScript and hadn't even heard of ajax until i started looking for an answer to this question so do not understand previous answers.
I am creating a site that essentially is a bunch of videos in a SQL database, it shows one video at a time, I would like to have a next and previous video buttons.
However I cant get past this ajax thing so my question is even simpler. I have looked at this question/answer and think it pretty much sums up what im asking:
How do I run PHP code when a user clicks on a link?
I have copied that exact code,
<script type="text/javascript">
function doSomething() {
$.get("backend.php");
return false;
}
</script>
Click Me!
And in my backend.php file i have literally just got <?php echo "Hello" ?> just to test it and therefore my understanding is that when i click the link the javascript onClick event is trigged which in turn calls the backend.php file, which says to print "Hello" to the page. However when i click the link it does nothing.
Eventually obviously im going to need to get a lot more complex with my php functions and calling variables and all that stuff but i like to figure things out for myself for the most part so i learn. However im stuck on this bit. Also whilst im here i will ask another thing, I want to 'give back' to the users of the site for answering my questions but I can only really well enough in HTML and CSS to answer other peoples questions, any advice on being able to find the simpler questions on here so i can answer some.
Thanks in advance :)
It does nothing becuase you don't do anything with the result. My guess is that in the example you took, it does some work and doesn't show anything to the user. So if you just had some stuff you wanted to run on the server without returning any output to the user, you could simply do that, and it would work.
Example from jQuery's .get() documentation
What you do:
Example: Request the test.php page, but ignore the return results.
$.get("test.php");
What you want to do:
Example: Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
Take a look at the .get() documentation. You're using it incorrectly.
You should be passing data (optional) and handling the data that gets returned, at a minimum:
$.get("backend.php",
{
// data passed to backend.php goes here in
//
// name: value
//
// format. OR you can leave it blank.
}, function(data) {
// data is the return value of backend.php
// process data here
}
);
If you pass data, you can retrieve it on backend.php using $_GET. In this case:
$_GET['name'];
$.get("test.php", { name: "John", time: "2pm" }, function(data) {
alert("Data Loaded: " + data);
});
http://api.jquery.com/jQuery.get/
This would alert the data. right now that function only returns false.
$.get('backend.php', function(data) {
alert(data);
});
Your code will not print to the page the way you have it set up; you're part of the way there, in that you have called the page, but the response needs to be handled somehow. If you open up the developer tools in Chrome, you can click on the Network tab and see the request and response to verify that what you coded is actually working, but now you need to put the response somewhere.
By passing a function as the second variable into $.get, you can make your request show up on the page. Try something like this:
$.get("backend.php", function (data) { $('body').append(data); } );
Your code is not handling with that data. So instead, you should use following code :
$.get("backend.php", function(response) {
alert(response);
})
Or, to show that data on UI, assign it to any html element.
For more understanding , please visit :jQuery.get() link

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/

Passing Javascript String to PHP output

I'm using this web service that prints out table using Javascript functions. I need the table to print out in plain html. This could be done if the Javascript string was transferred to a PHP file. So basically, this is similar to AJAX, but it is in reverse.
You could do that with ajax also
var value = 'This is a test';
if ($(value).val() != 0) {
$.post("jquery2php.php", {
variable:value
}, function(data) {
if (data != "") {
alert('We sent Jquery string to PHP : ' + data);
}
});
}
Important thing here is we are using $.post, so we are can gather the information with $_POST
We are sending only 1 value, named variable.
PHP part;
<?php
$jqueryVariable = $_POST['variable'];
echo $jqueryVariable;
?>
I believe, this is the most elegant way to achieve what you want.
not necessarily reverse, You could pass the string as a URL variable (www.yoursite.com/?string=yourvariable) and have PHP process it from there.
I've quoted a ugly method down here But i dont recommend this..
Instead store values in hidden fields in forms and access them through js or do something else..
<?php
echo "<script type=text/javascript>var x = $value; </script>";
?>
then use the variable x in js..
Anyway if you explain ur situation a bit clearer, we can give u best alternate solution
what you should do is use jQuery's .load() to load in the php's html results into the page
in the docs i've linked above they give this example
<script>
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
</script>
EDIT
in response to your comment on Pixeler's post. You will not be able to just view the source of a ajax based solution. if your ultimate goal is to be able to read the source you have basically three options
send them to a new page
load in an iframe
do it the way you have, use fire fox and web devloper addon which will allow you to view generated source. (or something similar)
I'm not sure why there is a need to see the source users don't really care about the source typically the developer uses that

jQuery/Ajax call - It Doesn't work on IE7

i make a Jquery function that (for the moment) call a function dinamically and print it with an alert. with firefox, chrome : it works! when i try on IE7 (the first time), it fails. If i reload the page (F5) and retry , it works! o_O
I FINALLY understand why that's happen. In my old website i used the jquery-1.3.2.min.js library. On this i use the jquery-1.4.2.js and in fact it doesnt work. So what's up? A bug in this new version?
cheers
EDIT
actual functions (with Bryan Waters suggestions):
// html page
prova
// javascript page
function pmNew(mexid) {
var time = new Date;
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php' + '?dummy=' + time.getTime(),
data: 'mexid='+escape(mexid)+'&id=pmnew',
success: function(msg) {
alert(msg);
}
});
return false;
}
// ajax.php
if($_POST['id']=="pmnew") {
echo "please, i will just print this";
}
Fiddler result : if i use http://localhost/website fiddler doesnt capture the stream. if i use http://ipv4.fiddler/website it capture the stream, but at the ajax request doesnt appair. if i refresh the page, yes it works. mah...i really don't know how resolve this problem...
Best way to debug is to download Fiddler and see what the HTML traffic is going on and if the browser is even making the ajax request and what the result is 200 or 404 or whatever.
I've had problems with IE cacheing even on posts. And not even sending out the requests. I usually create a date object in javascript and add a dummy timestamp just to make the url unique so it won't be cached.
ok, I'm not exactly sure what the issue is here but I think you could probably fix this by simply letting jquery handle the click instead of the inline attribute on the tag.
first change your link like this to get rid of the inline event
<a class="lblueb" href="./asynch/asynchf.php?mexid=<?$value?>"><?=value?></a>
then in your javascript in the head of your page add a document.ready event function like this if you don't already have one:
$(function(){
});
then bind a click event to your link inside the ready function using the class and have it pull the mexid from the href attribute, then call your pmNew function like so:
$(".lblueb").click(function(e){
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
Your final code should look like this:
<script type="text/javascript">
function pmNew(mexid) {
$.ajax({
type: "POST",
url: "./asynch/asynchf.php",
data: "mexid="+mexid+"&id=pmnew",
success: function(msg){
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
//document.ready function
$(function(){
$(".lblueb").click(function(e){
//prefent the default action from occuring
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
});
</script>
I believe you have an error in your SQL code. Is userd supposed to be userid?
Gaby is absolutely right that your SQL code is wide open for injection. Please consider learning PDO, which will reduce the likelihood of SQL injection significantly, particularly when using placeholders. This way you will have query($sql) and execute($sql), rather than the code going directly into your DB.
As a matter of habit you should deal with your request variables early in your script, and sanitize them to death -- then assign the cleaned results to new variables and be strict in only using them throughout the rest of the script. As such you should have alarm bells ringing whenever you have a request variable in or near an sql query.
For example at the very least you should be stripping any html tags out of anything that will get printed back to the page.
That is in addition to escaping the quotes as part of the sql string when inserting into the database.
I'm all for coding things up quickly -- sure, neaten up your code later... but get security of request vars right before doing anything. You can't tack on security later.
Anyway sorry for harping on.... as for your actual problem, have you tried what Gaby suggested: change your html to:
<a class="lblueb" href="#" onclick="return pmNew('<?php echo $value; ?>')"><?php echo $value; ?></a>
And then update your JS function to:
function pmNew(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php',
data: 'mexid=' + escape(mexid) + '&id=pmnew',
success: function(msg) {
$('#pmuser').html('<a class="bmenu" href="./index.php?status=usermain">PANEL (' + msg + ')</a>');
}
});
return false;
}
Also, with IE -- check the obvious. Clear the browser cache/history
I didn't understood the "fail", but here's another example..
function pmNew(mexid) {
$.post("./asynch/asynchf.php", {mexid: mexid, id: "pmnew"},
function(msg) {
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
It appears that this issue is faced by several people.
One of them had luck with clean installation of browser:
http://www.geekstogo.com/forum/topic/22695-errorpermission-denied-code0/
Check to make sure the content returned to the DOM is valid for the DOCTYPE specified.
I've had a similiar problem with Chrome, FF and Safari all working just fine, but finding the ajax result broken in IE. Check to make sure you don't have any extra divs or spans in the ajax result breaking your markup.

Categories