AJAX success and failure reporting - javascript

Trying to figure out how to report inside this popup only on failure. Currently this works, but it alerts for both success and failure:
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
alert(response);
console.log(response);
}
});
}
</script>
I have tried the following, but so far with no luck:
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
console.log(response);
},
error: function(response)
{
alert(response);
console.log(response);
}
});
}
</script>
Any help would be appreciated. Thanks!
* EDIT *
Here is the full code:
<?php
$static_password = "1234";
if(isset($_POST['data'])){
$submit_password = $_POST['data'];
if($submit_password == $static_password){
die("UNLOCK THE RECORD");
}
else{
die("SORRY WRONG PIN");
}
}
?>
<html>
<head>
<script src="js/jquery-3.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<h2>Simple AJAX PHP Example</h2>
UNLOCK
<p>Pin is "1234"</p>
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
alert(response);
console.log(response);
}
});
}
</script>
</body>
</html>

For the error callback to be executed, server must respond with status of 404, 500 (internal error), etc. When you write die('blah'); server responds with a status of 200, and the message that it died with. This is a successfull request as far as both AJAX and PHP are concerned.
You have to check the response
if($submit_password == $static_password){
die("UNLOCK THE RECORD");
}
then:
success: function(response)
{
if (response == 'UNLOCK THE RECORD') { /* success */ }
else { /* failure, do what you will */ }
}

Related

How to handle an error on ajax login form?

I have several login forms that use ajax, but now when information is wrong the page just refreshes. I want to catch some keyword/variable from my php, right now I am echoing 'error', and I want some alert on the page with no refresh. Here's my current js. When I submit, a login object is created and then the login method performed, if successful it redirects to a dashboard if not it echos 'error' and then how can I accomplish what I need with javascript?
<script>
$('#doctor_login').on("submit", function(e){
frmReg = document.getElementById("doctor_login");
if(frmReg.user_name.value == "") { alert("<?php echo _USERNAME_EMPTY_ALERT; ?>"); frmReg.user_name.focus(); return false;
}else if(frmReg.password.value == ""){ alert("<?php echo _PASSWORD_IS_EMPTY; ?>"); frmReg.password.focus(); return false;
}else{
$.ajax({
type:'POST',
url: '../page/handler/handler_ajax_login.php',
data: $(this).serialize()
}
});
}
});
jQuery exposes a error callback on the $.ajax method, as documented on http://api.jquery.com/jquery.ajax/
$.ajax({
type:'POST',
url: '../page/handler/handler_ajax_login.php',
data: $(this).serialize(),
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
}
To trigger the error callback, you must return a 400 or 500 range HTTP code.
<?php
header("HTTP/1.1 400 Bad Request");
you can use the success and error options
Here is an example
var yurl = ""
var furl = "proxy.php";
$.ajax({
url: furl,
data: { url: escape(yurl) },
dataType: "html",
success: function (data) {
$("#homecon").load("proxy.php .content");
},
error: function (xhr, err, e) {
alert("error");
}
});
return false;
Evaluate the data if it is equal to 'error' in the success function.
$.ajax({
type:'POST',
url: '../page/handler/handler_ajax_login.php',
data: $(this).serialize(),
success: function(data){
if(data == "error"){
console.log("error");
}
}
});

Can't post variable to PHP using AJAX

I am trying to send a variable to PHP using JavaScript but I don't get any response whatsoever. Any ideas?
PHP/HTML:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="dashmenu.js"></script>
</head>
<body>
<?php
$selection = $_POST['selection'];
if($selection == 'profile'){
?>
<p> it works
<?php
}
?>
<button id="button"> profile </button>
</body>
JS file (dashmenu.js):
$('#button').click(function() {
var menuSelection = "profile";
$.ajax({
type: 'POST',
url: 'dashboard.php',
data: {selection: menuSelection},
success: function(response) {
alert('success');
}
});
});
In your html file (let's say index.html) you could have:
$('#button').click(function() {
var menuSelection = "profile";
$.ajax({
type: 'POST',
dataType: "html",
url: 'dashboard.php',
data: {selection: menuSelection},
success: function(response) {
alert(response);
},error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + errorThrown);
}
});
});
In your dashboard.php, you should ONLY have code that processes requests, and returns (echoes) the desired output:
<?php
$selection = $_POST['selection'];
if($selection == 'profile'){
echo "It works";
}else{
echo "It failed";
}
?>
$('#button').click(function() {
var menuSelection = "profile";
$.ajax({
type: 'POST',
url: 'dashboard.php',
data: {selection: menuSelection},
success: function(response) {
alert('success');
}
});
});
Run this in your console in your browser.
Right-click > Console tab.
If you want to check whether this function has successfully bind to the button. If your browser returns you 'success' alert, meaning you include it wrongly I guess.
If nothing happen when you click, please include .fail() in your $.ajax()
Which will look like this:
$.ajax({
type: 'POST',
url: 'dashboard.php',
data: {
selection: menuSelection
},
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
}
});

How to pass data to another page using jquery ajax

I have a problem on ajax call.
Here is my code regarding the ajax:
$('#Subjects').click(function() {
$.ajax({
type: 'POST',
url: '../portal/curriculum.php',
data: 'studentNumber='+$('#StudentID').val(),
success: function(data)
{
$('#curriculum').html(data);
}
});
});
When I echo studentNumber on another page, the studentNumber is undefined. Why is that?
Simply modify your code like this:
JS
$('#Subjects').click(function() {
$.ajax({
type: 'POST',
url: '../portal/curriculum.php',
data: { studentNumber: $('#StudentID').val() },
success: function(data)
{
$('#curriculum').html(data);
}
});
});
PHP
<?php
$var = $_POST['studentNumber'];
?>
If you still can not make it works.. other things you should consider..
url: '../portal/curriculum.php',
1) Please use full URL http://yourdomain.com/portal/curriculum.php or absolute path like /portal/curriculum.php
2) Add an error callback to check out the error message
$('#Subjects').click(function() {
$.ajax({
type: 'POST',
url: '../portal/curriculum.php',
data: { studentNumber: $('#StudentID').val() },
success: function(data)
{
$('#curriculum').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("test1.php",
{
name: "Makemelive Technologies",
city: "Mumbai"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
The above will make a call to test1.php and its code will be
<?php
$fname=$_REQUEST['name'];
$city= $_REQUEST['city'];
echo "Company Name is ". $fname. " and it's located in ". $city ;
?>
$('#Subjects').click(function() {
$.ajax({
type: 'POST',
url: '../portal/curriculum.php',
data: { studentNumber: $('#StudentID').val() },
success: function(data)
{
//here data is means the out put from the php file it is not $('#StudentID').val()
$('#curriculum').html(data);
}
});
});
as exsample if you echo some text on php it will return with data $('#curriculum').html(data);
try to change
//change
success: function(data)
{
$('#curriculum').html(data);
//to
success: function(result)
{
$('#curriculum').html(result);
check what will happen.
post us php file too curriculum.php
You can use through Jquery,Ajax and php
step 1. index.php
<div id="div_body_users">
</div>
<form method="post" id="frm_data" action="">
<input type="button" id="target" name="submit" value="submit">
<input type="key" id="key" name="key" value="1234">
</form>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function(){
$( "#target" ).click(function() {
// alert("test");
var frm_mail = document.getElementById("frm_data");
var frm_mail_data = new FormData(frm_mail);
$.ajax({
url: "http://localhost/test.php",
data: frm_mail_data,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (result) {
document.getElementById('div_body_users').innerHTML=result;
}
});
});
});
</script>
step 2. create test.php
<?PHP
//print_r($_POST);
if($_POST['key']=='1234'){
echo "success";
exit(0);
}
?>
$.ajax({
type: "GET",
url: "view/logintmp.php?username="+username+"&password="+password,
}).done(function( msg ) {
var retval = printmsgs(msg,'error_success_msgs');
if(retval==1){
window.location.href='./';
}
});

Ajax call to database not works

in my application I have to make an ajax call to php file.it works proper in all devices. but when I tried it on ipad mini it not calls the php, so that the functionality not works, I've seen so many question about this problem and edited my code like this.
jQuery.ajax({
type: "POST",
async: true,
cache: false,
url: "directory/phpfile.php",
data: data,
success: function(response) {
}
});
my old code is
jQuery.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
data: data,
success: function(response) {
}
});
and the problem still cant resolve . so please any one tell me how to resolve this.
Please use this code
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
<script type='text/javascript'>
$(document).ready(function startAjax() {
$.ajax({
type: "POST",
url: "test.php",
data: "name=name&location=location",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});

Ajax Get Request with JQuery Error

I'm trying to call a php script with a get request and using the data theaddress however the results are showing me the source of the page im calling.
The page im calling is here
Here is my ajax function that will get this page
$( document ).ready(function() {
var address = document.getElementById("address");
$.ajax({
url: '/r10database/checkSystem/ManorWPG.php',
type: 'GET',
data: 'theaddress='+address.value,
cache: false,
success: function(output)
{
alert('success, server says '+output);
}, error: function()
{
alert('Something went wrong, saving system failed');
}
});
});
$( document ).ready(function() {
var address = document.getElementById("address");
$.ajax({
url: '/r10database/checkSystem/ManorWPG.php',
type: 'GET',
data: 'theaddress='+address.value,
cache: false,
success: function(output)
{
alert('success, server says '+output);
}, error: function(error)
{
alert (error); // this is the change from the question
}
});
});
Put the dataType as json with a curly brace
data: {theaddress:address.value},
dataType:'json',
success: function(output)
{
alert('success, server says '+output);
}, error: function(xhr)
{
alert (xhr.status);
}
and get the data in ManorWPG.php as $_GET['theaddress']
** share the xhr.status if failed.

Categories