How to get the values of ajax post in iis7.5 - javascript

Good day to all..
I have a problem.. I can't get the values that are send in my ajax code..
This is my ajax code
$(function(){
$('#login').on('submit',function(e){
e.preventDefault();
var user = $('#username').val();
var pass = $('#password').val();
$.ajax({
url:'confirm_login.php',
type:'POST',
data:{user:user, pass: pass},
success : function(data){
alert(data);
}
});
});
});
this is my php code
<?php
echo "outside";
if(isset($_POST['user']) && isset($_POST['pass'])){
echo "inside";
}
?>
When I tried it, the result is outside..
I also tried to remove the echo "outside" but the result is empty..
So I can assume the problem is in the $_POST.. If you guys have encountered and resolved this pls help..
Note: This is in the iis7.5.

I've already resolve it.. When I was looking in the networks tab in the chrome dev tools, I saw that it send a request to confirm_login.php and confirm_login..
I also remember I have a rewrite rule in my web.config that removes the .php in the url.. So what I did was just simply remove the .php in the url of the ajax and it works like a charm..
Just this url:'confirm_login',

Related

PHP JSON Encoded Object causes Ajax Error

This has been bugging me for the last few hours, and I've tried various searches but never found exactly this issue with an answer. Maybe asking and showing some code will help me get this figured out.
I am using ajax to do a post to PHP, which I want to just give a notification so that I may update a div on the page. In this case, I just need the PHP to say something like "Cfail" which the javascript would use to update page content.
Originally, I was going to try just text responses. So, my PHP for example would be like this:
<?php
session_start(); //Because have an encoded captcha answer.
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
echo 'Cfail';
}
?>
The Javascript would be:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'text',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned=='Cfail'){
alert("I read it right!");
}
}
});
});
});
It would run through the script just fine, but the result never would be what I was asking for. Alert showed the corrct text, however, research indicated that the issue with this was PHP apparently adding white space. The common answer was the encode a JSON response instead. So, I tried that.
Updated PHP:
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
$result = array('result' => 'Cfail');
echo json_encode($result);
exit;
}
?>
Updated Javascript:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'json',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
}
});
});
});
Which now no longer runs successfully. The alert doesn't come up, and the loader object remains visible(indicating the success never goes through). I tried putting an error section to the ajax, and it indeed fired that. However, I had no idea how to parse or even figure out what the error was exactly. The most I got in trying to get it was what PHP was outputting, which was {"result":"Cfail"} .... Which is what I would EXPECT PHP to give me.
I can work around this, I've done a similar set-up with just echoing a number instead of words and it used to work just fine as far as I knew. I'd just like to figure out what I am doing wrong here.
EDIT:
I managed to figure out what the issue was in my case. I had a require('config.php'); between the session start and the json_encode if statement. For some reason having the external file added, which was just me setting a couple variables for the code further down, some hidden character was added before the first { of the JSON object.
No idea why. As I said, it was just a $var='stuff'; situation in the require, but apparently it caused the issues. :/
Use this like
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
//$result = array('result' => 'Cfail');
$data['result'] = 'Cfail';
echo json_encode($data);
exit;
}
?>
This works for your javascript
use the below code, in your success call back, first parse the encoded json object that you are recieving from the back end and access the object property result to check it's value
success: function(returned){
returned = JSON.parse(returned);
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}

PHP request through AJAX fails

This is probably something very simple, and I've seen that there are/have been more people with the same issue. But the solutions provided there did not seem to work.
So, I want to execute a .php file through AJAX. For the sake of testing the php file (consolefunctions) is very small.
<?php
if(isset($_POST['action'])) {
<script>console.log('consolefunctions.php called.');</script>
}
?>
And now for the javascript/ajax part.
$(".startConsole").click(function(){
var consoleID = $(this).attr("value");
$.ajax({ url: 'include/consolefunctions.php',
type: 'post',
data: {action: 'dosomething'},
success: function(output) {
//alert("meeh");
}
});
});
Somewhere, somehow there's an issue because the message from the PHP file never shows. I've tested the location from the php file, which is valid.
First the php code is not correct, you should add an echo
<?php
if(isset($_POST['action'])) {
echo"<script>console.log('consolefunctions.php called.');</script>";
}
?>
but the problem is, when you send this code to js, you'll get it as a string on your variable output, not as a code that will be executed after making the ajax call, so the best way to do this is to echo only the message to display on your console and then once you receive this message you can call console.log function
<?php
if(isset($_POST['action'])) {
echo"consolefunctions.php called";
}
?>
in the success function :
console.log(output);

unable to get the data value of ajax on another page

I'm trying to update the user votes into database. This below ajax codes returns correct rating datas. But, I'm unable to get the alert data on another page. In my car_user_rating.php page I have tried this echo $post_rating = $_POST['performance_rating'];. But it doesn't get the performance_rating data value.
I have checked my console. It returns the rating values (4). I'm confused why it doesn't get the data value?
ajax request
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: "<?=CAR_USER_RATINGS?>",
data: { performance_rating: performance_rating },
success : function(data){
alert(performance_rating)
},
});
});
});
you should alert the data which you pass in success: function()
like
success : function(response){
alert(response);
},
use 'var' in submit handler, may it's because of scope:
var performance_rating = $('input:radio[name=rating]:checked').val();
I am not sure of your context so cant say exactly. Also i dont know if you are using exact same code as above or you have written teh above code in a hurry since there are mistakes there!!!
However Firstly try these
data: { "performance_rating": performance_rating },
url: "<?php=CAR_USER_RATINGS?>" //you have forgotten php
success : function(data, testStatus, xhr){
},
and check each values of data, testStatus, xhr
Also what is the value of
performace_Rating before $.ajax
"<?php=CAR_USER_RATINGS?>" before $.ajax
Just to summarize. I could figure out from your comment that your php is as below:
no. I have this codes on my php page inside the body tag
<?php echo $post_rating = $_POST['performance_rating'];
/*var_dump($get_rating); echo $sql = "UPDATE ".TBL_CAR_USER_RATINGS." SET performance = '$get_rating' WHERE model_id = '2'"; die(); mysql_query($sql, $CN) or die(mysql_error()); */ ?>
This is present inside the body tag!!! Well if you are using body tag i presume you are using other html, header(optional) tags as well
For a ajax response page the reply to client should "ONLY" be the value you want to send back.
Having tags will result in the the ajax response containing these tags as well.
So if you want your ajax page to return performance rating do the below:
//car_return_Rating.php
<?php echo $_POST['performance_rating']; ?>
If you have below code your response is shown below
//car_Return_rating.php
<html>
<body>
<?php echo $_POST['performance_rating']; ?>
</body>
</html>
then response i.e. data in success(data){}
will be equal to
data = "<html><body>4</body></html>"; //assuming 4 to be equal to $_POST['performance_rating'];

Jquery Ajax Fails... randomly succeeds

Here is my problem:
I try to make an Ajax call with JQuery,
this calls a PHP page, the code gets executed, and echoes OK if alright, STOP if not.
I don't get any text back (first problem),
and the real problem is that:
SOMETIMES the query succeeds, but ALWAYS returns an error. (even if my sql query in php page gets executed)
Here is the code :
<script>
$("a.confirm").click(function(event){
var id = event.target.id;
$.ajax({
type :"POST",
url :'./PHP/UTILS/confirm.php',
data :{ "id" : id,
},
beforeSend: function(){
alert("in progress");
},
complete: function(){
alert("done");
},
success: function(){
alert("OK");
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err + "\n");
}
});
});
</script>
This is for the ajax, now the page it calls :
<?php
include "./functionsExt.php";
$db = connectToDb('mydb');
$id = $_POST['id'];
$mysql = $db->prepare("UPDATE `test` SET `test_date_p` = CURRENT_TIMESTAMP, `test_status` = '2' WHERE `test_id` = '$id'");
if($mysql->execute()){
echo "OK";
}else{
echo "STOP";
}
?>
Thanks for help
i would like to suggest that you should try it after removing the comma in data after 'id'.
And i please do mention the following :
echo the post variable and check the response.
then echo that you want and check whether it is coming or not in response
a better way to write the success and failure
success: function(data)
{
alert(data);
}
failure : function(){
alert(failed);
}
It will eventually alert you with the data that you are receiving in response. So it is good for testing purpose.
hope it helps:)
i think i found something interesting...
i tried echoing the post...
The post is well sent to the php file,
But i noticed that :
if i add event.preventDefault(); in my jquery code, i have the post echo + the "ok" displayed in an alert (guess it's the success alert cuz i don't have the log message this time...)
i will try again... (if it works like this, i need then to find a way to re-enable default link click function, i need to refresh the page... the page content is not the same after calling the ajax...)
tried again, and it seems to work now...
but, i don't close the topic, cause i have to add few more queries in my php file now... and i still need a way to refresh the page after execution... any idea?
(thanx stacky, you advice seems to have solved the "main" problem :P )

Not getting the success callback for an ajax query to my php page

Edit: changed $.alert() to alert()
I've got a file, planner.php that uses JQuery to send an ajax request to the same page.
Using the debugger, I can see that the php correctly gets the request, accesses my database, and then sends the data. However even after sending it I get no success callback in the javascript. What's wrong?
JQuery:
$(function()
{
$.post('planner.php', {"want": "keys"}, success_func, 'json');
});
function success_func(result)
{
//This is never called :(
alert("Worked");
}
PHP:
<?php
require_once "./php/couch.php";
require_once "./php/couchClient.php";
require_once "./php/couchDocument.php";
if (count($_POST) > 0 && array_key_exists("want", $_POST)) {
$couch_dsn = "http://localhost:5984/";
$couch_db = "subjects";
$client = new couchClient($couch_dsn, $couch_db);
header('Content-type: application/json');
$response = $client->getView('subject_views', 'keys');
echo json_encode($response); //This all seems to work fine
}
?>
It's that simple. All of the PHP code there is just accessing couchDB which you don't have to worry about because I know that $response is set correctly.
For knowing where the ajax call is done or faced a error
$(function()
{
$.post('planner.php', {"want": "keys"},function(){
alert( "success" );
})
.done(function(){
alert("second success");
})
.error(function(){
alert("error");
});
});
link : http://api.jquery.com/jquery.post/
This is probably be cause there is no such thing like $.alert(), use simple alert() instead.
Also your success_func is declared below the ajax call, move it up before $.post();
EDIT:
as the function is declared, there is no need to type it before executing.
you can use like that it may be your sucess function not calling
var data = 'want=keys';
$.post(
'planner.php',
data
).success(function(resp){
json = $.parseJSON(resp);
alert(json);
});
Credit to vivek for giving me a method to work out the problem.
Basically I fundamentally didn't understand how php worked. The code for sending the POST response was halfway down the page, so PHP was sending back the entire page along with any extra json I had encoded, and then JQuery attempted to parse this html page as json, failed, and then didn't run the success function because it never succeeded in its request. Read this answer for some more insight
The obvious solutions are:
Make a new page for the response
Put the php at the top of the
page.
I ended up going with option #2 for simplicity's sake.
Thanks everyone!

Categories