Can't post variable to PHP using AJAX - javascript

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

Related

AJAX success and failure reporting

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 */ }
}

JavaScript jQuery AJAX POST data error

I am trying to send a post param. to request.php but it returns that the post param. are empty.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
$.ajax({
url: "request.php",
type: "POST",
data: "{key:'123', action:'getorders'}",
contentType: "multipart/form-data",
complete: alert("complete"),
success: function(data) {
alert(data);
},
error: alert("error")
});
remove " " from this data as data:{key:'123', action:'getorders'}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$.ajax({
url:"request.php",
type:"POST",
data:{key:'123', action:'getorders'},
contentType:"multipart/form-data",
complete:alert("complete"),
success:function(data) {
alert(data);
},
error:alert("error")
});
</script>
You must use FormData for multipart/form-data ,and also need additional option in ajax ..
var request = new FormData();
request.append('key',123);
request.append('action','getorders');
$.ajax({
url: "request.php",
type: "POST",
data: request,
processData : false,
contentType: false,
success: function(data) {
alert(data);
}
});
This will help you. You don't want a string, you really want a JS map of key value pairs.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$.ajax({
url:"request.php",
type:"POST",
data:{key:'123', action:'getorders'},
contentType:"multipart/form-data",
complete:alert("complete"),
success:function(data) {
alert(data);
},
error:function(){
alert("error");
});
</script>
This should work like a champ ,
construct object as below and stringify it as JSON.stringify(newObject) then there will be no chance of error
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var newObject= new Object();
newObject.key= '123';
newObject.action='getorders'
$.ajax({
url:"request.php",
type:"POST",
data:JSON.stringify(newObject),
contentType:"multipart/form-data",
complete:alert("complete"),
success:function(data) {
alert(data);
},
error:function(){
alert("error");
});
</script>
Try this:
data: JSON.stringify({key: '123', action: 'getorders'}),
contentType: "application/json"

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");
}
}
});

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

Categories