Check what is the name of the POST - javascript

When I click a button, it is handled by ajax and then post to a PHP page. current problem is the PHP cannot recognize the POST name from the front end. It keep throwing me the else part whichis "NOT OK". Below are the snippet.
PHP part
if (isset($_POST['btn-agree'])){ echo "OK<br />"; } else { echo "NOT OK<br />"; }
END PHP part
$(function() {
$("#btn-agree").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "postAgreement.php",
success: function(msg){
//do something
},
error: function(){
//do something
}
});
});
});
<form id="agree-form" action="/" method="post" role="form">
<input type="submit" name="btn-agree" id="btn-agree" value="Agree">
</form>

You are not specifying the data to be sent to the server. Use the data parameter and serialize the form.
$(function() {
$("#btn-agree").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "postAgreement.php",
data: $('#agree-form').serialize(),
success: function(msg){
//do something
},
error: function(){
//do something
}
});
});
});
EDIT: It looks like .serialize() does not include the submit input type. To test the request method to the script, you can use $_SERVER['REQUEST_METHOD'] and test that it equals "POST". You can also set the data parameter to "btn-agree=Agree".

you forgot the parameter "data" on your ajax.
on isset($_POST['btn-agree']) will always be false because the $_POST['btn-agree'] is not define or set.
check this code or see sample on http://api.jquery.com/jquery.ajax/:
$.ajax({
type: "POST",
data: { btn-agree: $('#btn-agree').val() },
url: "postAgreement.php",
success: function(msg){
//do something
},
error: function(){
//do something
}
});

Related

PHP Form submit get return value to html [duplicate]

I want to alert the return value from a php method, but nothing happens. Here is the ajax and php methods. Can anyone see what I am doing wrong?
--------------------------------------…
Ajax script
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data');
}
});
--------------------------------------…
php method
function junk($id)
{
return "works11";
}
in PHP, you can't simply return your value and have it show up in the ajax response. you need to print or echo your final values. (there are other ways too, but that's getting off topic).
also, you have a trailing apostrophe in your alert() call that will cause an error and should be removed.
Fixed:
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
PHP:
function junk($id)
{
print "works11";
}
You have an extra ' in there on the alert(data') line
This should work
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
And your PHP code should call the method also and echo the value
function junk($id) {
return 'works11';
}
exit(junk(4));
All you're doing currently is creating the method
ajax returns text, it does not communicate with php via methods. It requests a php page and the return of the ajax request is whatever the we babe would have showed if opened in a browser.

How to intercept POST data with Javascript

I am using this javascript function to send data to my php script (via POST) I am then using this information to retrieve data from my database and I would like to reuse the information retrieved in my JavaScript code.
Here is my code :
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function() {
// HERE I would like to inctercept the data that my php script put in myFunctions.php produces and use it to generate content;
}
});
});
So basically, when clicking on the button #validerChoixDeCours, my code sends some data to myFunctions.php which generates a response stored in a php variable and I want to use that response in my JS code.
Thank you in advance for your help :)
Its actually quite easy!
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(e) {
e contains the response from the php script
}
});
});
The first parameter of success contains the response from the request. so, in this case, the 'e' variable contains the output which you can use.
Add data variable
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(data) {
alert(data);
}
});
});
make sure your server side code look like this
<?php
$output = "Any String or Array";
echo json_encode($output);
?>

not able to pass value using ajax in php file

I am not able to pass value using ajax in php file.
Corrected Code
<script>
$("body").on('change', '#area', function () {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'box.php',
type: 'POST',
data: {option: selectedValue},
success: function () {
console.log("Data sent!");
}
});
});
</script>
here the php code
<?php $val=$_POST['option'];echo $val; ?>
There are a few problems here:
It should be url, not rl. Also, you have type: POST' with it ending in a ', but no starting '.
It should be type: 'POST'.
It should then look like this:
$("body").on('change', '#area', function() {
var selectedValue = this.value;
$.ajax({
url: 'box.php',
type: 'POST',
data: {
option : selectedValue
},
success: function() {
console.log("Data sent!");
}
});
});
If you want to view your data on the same page after (as on box.php, you are echo'ing the value.), you can do this:
success: function(data) {
console.log(data);
}
This will then write in the console what option is, which is the value of #area.
Try the following code
$("body").on('change',function(){
$.ajax({
URL:<you absolute url>,
TYPE:POST,
Data:"variable="+$("#area").val(),
Success:function(msg){
<do something>
}
});
});
Hope this will help you in solving your problem.
Your just miss ajax method parameter spelling of 'url' and single quote before value of type i.e. 'POST'. It should be like
$.ajax({
url: 'box.php',
type: 'POST',
data: {option : selectedValue},
success: function() { console.log("Data sent!");}
});

ajax send form request to the same page to run SQL/PHP queries

<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#please_wait_box").hide();
$("#addnotification").submit(function(e){
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString=$("#addnotification").serialize();
$.ajax({
type: "POST",
url: "menu.php?addnotification=yes",
cache: false,
data: dataString,
success: function(res){
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
$('.overlay').fadeOut();
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
}
});
});
});
</script>
i am trying to run this ajax code to POST data to menu.php page from a submitted form
on menu.php i have
if($_GET["addnotification"] == 'yes') {
//do stuff here
echo 'form submitted';
}
but i cannot see the text form submitted
UPDATE
i have changed to this code:
<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#please_wait_box").hide();
$("#addnotification").submit(function(e){
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString=$("#addnotification").serialize();
$.ajax({
type: "POST",
url: "addnotification.php",
cache: false,
data: dataString,
success: function(res){
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
}
});
});
});
</script>
and put the SQL queries on a different page, but now the please_wait_box shows and does not hide, the queries are not running at all
In your url you've got no blank, but in your php document there is a blank.
menu.php?addnotification=yes
vs
$_GET["add notification"]
You are sending a POST request and then reading the $_GET response, try changing the
type: "POST",
for
type: "GET",
in your ajax call.
and also read addnotification and not add notification (probably a typo)
Check your this part of code:
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
You are searching for success in res whereas i think your res will be a string "form submitted". You can try calling alert(res); or console.log(res) to see what is being returned in your response.
Additional debugging process:
change your code for ajax to below:
var request = $.ajax({
type: "POST",
url: "addnotification.php",
cache: false,
data: dataString
});
request.done(function( msg ) {
$("#please_wait_box").hide();
$("#message").html(msg);
$('#message').fadeIn('slow');
if(msg.indexOf("success")!=-1)
{
window.location.href = msg.substr(8);
}
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});

Pass JavaScript function in ajax response

I'm trying to return a callback from an AJAX submitted form. The user submits a form, the server processes and returns the valid response, i.e. an error message and also a JavaScript function that could perform an action. I'm using Zepto.js faling back to jQuery depending on browser.
My ajax request is:
$.ajax({
success: function(data, status, xhr) {
data.callback();
},
url: form.attr('action'),
data: form.serialize(),
dataType: 'json'
});
On the server I want to return something like:
// PHP code
?>
{
return: false,
error: 'Sorry, we couldn’t find an account with that username or password.',
callback: function() {
console.log('this is the callback');
}
}
<?php
// more PHP code
When returned to the browser callback function should fire. I want the server to return the callback so I can use the same JavaScript code and have it respond accordingly to the server response.
Would I need to change the dataType to script? However I thought this was just for loading .js files, not blocks of code.
Any help appreciated.
The general feeling here is I am approaching this in the wrong way. So revised code:
$.ajax({
success: function(data, status, xhr) {
var callback = data['callback'];
callback();
},
url: form.attr('action'), // in this example it's badLogin
data: form.serialize(),
dataType: 'json'
});
// callback specified in PHP
badLogin: function() {
console.log('bad login');
}
And my PHP
if (!$valid) {
?>
{
"return": false,
"error": "Sorry, we couldn’t find an account with that username or password.",
"callback": "badLogin"
}
<?php
}
Thanks for pointing me in the right direction.
You can always return the code as a string and use eval() if you are absolutely sure that the string will always be correct and no code can be injected.

Categories

Resources