jquery ajax json doesnt return true - javascript

i have large form in my website and using serialize() to process the form.
my problem is:
the result always return false after the form has been completed! i checked using firebug. if false, the result being shown. it was actually data.ok == true had been called, but it didnt show the message in the page? and it didnt redirect the page to the destination address?
jquery ajax:
$("#details").live("submit", function(e){
var form = $(this).serialize();
var data_string = form;
$.ajax({
type: "post",
url: "../_include/ajax.php?details",
cache: false,
data: data_string,
dataType: "json",
success: function(data) {
if(data.ok) {
("#pop").html(data.message).addClass("oke").fadeIn("slow");
setInterval(function() {
location.href = data.redirect
},2000)
} else {
$("#pop").html(data.message).addClass("warning").fadeIn("slow");
}
}
});
e.preventDefault();
})
in PHP:
if (isset($_GET['details'])) {
if (empty($name)) {
$data['ok'] = false;
$data['message'] = 'Please enter name!';
} ................ {
.............
} else {
$db->query("UPDATE query....");
$data['ok'] = true;
$data['message'] = 'Your details has been submitted!';
$data['redirect'] = 'index.php?p=details';
}
echo json_encode($data);
}

You appear to have a syntax error in your success function (if that's not a copy/paste error):
("#pop").html(data.message).addClass("oke").fadeIn("slow");
should be:
$("#pop").html(data.message).addClass("oke").fadeIn("slow");

you check for GET in your PHP (if (isset($_GET['details']))), but send POST (by specifying the type as post) in your AJAX.
Either check the $_POST array instead of the $_GET, or change the type to get.

Related

Check if alert box was shown in PHP using AJAX

I am sending data to a PHP file using AJAX and depending on what data is sent, an alert() is either shown or not shown.
Inside the success function in AJAX, how do I detect if an alert box was shown?
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if(alert box was shown) {
// something happens
}else{
// alert box wasn't shown, something else happens.
}
}
});
send.php:
<?php
if($_POST['name'] == 'john') {
echo'
<script>
alert("Correct name");
</script>
';
}
It would be better to send back a result form the ajax request and show/don't show the alert in the success callback:
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if ( data == "show" ) {
// something happens
alert("Correct name");
} else {
// alert box wasn't shown, something else happens.
}
}
});
And on your server:
if ( $_POST['name'] == 'john' ) {
echo "show";
}
You could use json_encode() php function to return data from php.
This will be a better approach :
PHP :
if (!isset($_POST['name'] || empty($_POST['name']) {
die(json_encode(array('return' => false, 'error' => "Name was not set or is empty")));
} elseif ($_POST['name'] == "John") {
die(json_encode(array('return' => true)));
} else {
die(json_encode(array('return' => false, 'error' => "Name is different than John.")));
}
At this point, you will be allowed to check the returned values from JS and decide if you need to display the success alert or send an error message to the console (or do what ever you want...).
JS :
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
dataType: "JSON", // set the type of returned data to json
data: {name: called}, // use more readable syntaxe
success: function(data) {
if (data.return) { // access the json data object
alert("Congrats ! Your name is John !");
} else {
console.log("Sorry, something went wrong : " + data.error);
}
}
});
So, json_encode() allows to return easy accessible object from JS and will also allows you to set and display error messages easily in case the return is false.
Hope it helps !
PHP does not know if an alert has been shown, because in javascript the alert() function has no return value and no events which you could use to send an ajax request a click confirmation to the server.
One solution is to use a confirm() command inside the success event of your $.ajax(), which sends anothe ajax request if the user clicked "ok" or "cancel".
Something like this
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,
success: function(data) {
if (data == "show") {
var clicked = confirm("Correct name");
if (clicked == true || clicked == false) {
$.ajax({
url: "send.php?clicked=1",
});
}
}
else {
// Whatever to do than...
}
}
});

passing login data from ajax to php script

Here is my script in the html page:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid=$('#loginid').val();
var password=$('#password').val();
alert("loginid="+loginid);
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid:loginid,password:password},
success: function(html) {
//alert(html);
$('#status').html(html);
}
});
});
});
</script>
I am trying to get the values from the html input boxes and then passing those values to the ajax code which passes it to the php script, which then validates the login id and password and echoes a message
The php script:
<?php
require_once('dbconfig.php');
//if (isset($_POST['signin'])) {
$loginid = $_POST['loginid'];
$password = $_POST['password'];
if ($operations->login($loginid, $password)) {
header("Location:../view/admin_home.php");
} else {
echo "wrong details";
}
//}
$conn = null;
?>
html div where message should be printed:
<div id="status"></div>
When I run the code in the browser no errors are shown, but the code does not work and neither the message is displayed nor is the validation done.
My contribution:
In ajax requests I suggest you to end the php script, you can use a simple die(); for this. After this, you must to print the response, you can use numeric or string pattern to expose this like: 'success' or 'fail', also: 1 or 0.
Here is the same example with a new solution:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid = $('#loginid').val();
var password = $('#password').val();
e.preventDefault(); //for avoiding conflict with default form function
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid: loginid, password: password},
success: function(response) {
if (response == 'success') {
// if a successful response, redirect your client
window.location.href = '../view/admin_home.php';
} else {
// if login fails, put a message on screen
$('#status').html('Wrong credentials, try again.');
}
}
});
});
});
</script>
Don't forget to filter data in php, never trust in your user!
require_once('dbconfig.php');
// pre setting a response status as fail, this avoid you to use an
// else statement
$result = 'fail';
if (isset($_POST['signin'])) {
// Apply filter and sanitize data, if the loginid is an e-mail
// use the FILTER_SANITIZE_EMAIL else a simple string filter is ok.
$loginid = filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
if($operations->login($loginid,$password)){
// If everything is ok, you just override the response message
$result = 'success';
}
}
// Ath the end you simply close the connection, print the response and
// stops the PHP script
$conn = null;
print(result);
die();
i solved it by preventing it from performing the default function
i used e.preventDefault() it worked but i have a new problem now
the page to which the php script tries to redirect appears on the same login page how should i solve this now??
here is a screen shot of the same
Give this a try:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: "../controller/login_check.php",
data: form.serialize()
}).done(function (html) {
$('#status').html(html);
});
});
});
</script>
You must redirect with javascript, you are not actually going to the php page, you are just retrieving whatever is printed.
window.open(page,'_self')
rather than
header(...)

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

jQuery AJAX response always returns blank message

Hi I'am trying to make HTML form, and need to validate it before executing the form action. But the AJAX respond always returns a blank message?
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $(this).serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
} else {
console.log(msg);
}
}).fail(function() {
// Catch ajax errors here
console.log('AJAX error');
});
});
});
PHP:
$post = (!empty($_POST)) ? true : false;
if ($post) {
$orderid = stripslashes($_POST['orderid']);
$amount = stripslashes($_POST['amount']);
$betingelser = stripslashes($_POST['betingelser']);
$error = ''; // Check ordreid
if (!$orderid) {
$error. = 'Venligst indtast dit ordreid.<br />';
} // Check amount
if (!$amount) {
$error. = 'Venligst indtast et beløb.<br />';
}
if (!$error) {
echo 'OK';
} else {
echo '<div class="notification_error">'.$error.
'</div>';
}
}
Can anyone tell me what wrong?
You're in the click handler of a submit button. You're calling $(this).serialize(), where this is that submit button. Calling serialize on the submit button is going to return an empty string.
So, you're not passing any data to the server. The first thing you do server-side is check empty($_POST), which it will be, so if ($post) is false, and none of your server-side code is eve executed.
You need to serialize the form, not the submit button.
A simple solution would be to serialize the form itself....
str = $('"#ajax-payment-form').serialize()
but really, the larger problem is that you're binding to the click of the submit button, instead of to the submit event on the form itself.
Instead of this rather convoluted way of handling form submits...
$("#ajax-payment-form input[type='submit']").click(function(e) {
Just do this:
$("#ajax-payment-form").submit(function (e) {
try this in jquery:
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this,
success: function(msg){
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
}
else {
console.log(msg);
}
}
error: function(msg){
// if call fails or any error occurs
}
});

Execute ajax call right after all fields are filled

So I need to check all the fields first:
<script type="text/javascript">
<!--
$(document).ready(function(){
$("#loginform").submit(function(){
LIKE:
//CHECK INPUT
$('#loginform :input:not(:button)').each(function(n,element){
if ($(element).val()=='') {
$(".message").css('margin-top', '13px').html('<p>O campo '+element.id+' tem de ter um valor!</p>').fadeIn("slow").delay(2000).fadeOut(1000);
return false;
}
});
AND MAKE AJAX CALL AFTER ALL FIELDS ARE FILLED:
//AJAX CALL
$.post(...
BLÁ BLÁ
return false;
How can I submit values after check all fields?
Thank you as always.
UPDATE:
The solution "I found".
First validate in client side.
Second validate server side.
With the first measure several ajax call's are prevented before all fields are ok!
With the second "move" we prevent malicious intentions.
Thank you very much.
I been learning so much with you :)
Is this what your looking for?
var callAjax = true;
//CHECK INPUT
$('#loginform :input:not(:button)').each(function(n,element){
if ($(element).val()=='') {
//Code then set bool
callAjax = false;
}
});
if(callAjax){
$.ajax( {
url: "form action",
type: "POST",
data: $("#loginForm").serialize(),
....
}
If you mean whats the easiest way to get the form data into you ajax request?
use the .serialize() method on your form like:
$.ajax( {
url: "form action",
type: "POST",
data: $("#loginForm").serialize(),
....
// Add these to your onReady code
function checkFields() {
var filledIn = true;
$('#loginform :input:not(:button)').each(function(n,element){
if ($(element).val()=='') {
filledIn = false;
return false; // stop loop execution
}
});
return filledIn;
}
$('#loginform :input:not(:button)').change(function() {
if (checkFields()) {
$.ajax( {
url: "form action",
type: "POST",
data: $("#loginForm").serialize(),
....
});
}
})

Categories

Resources