I'm sending an ajax "POST" in my php file. But the problem is the index of the POST is undefined.
This is my sample code in ajax.
$(".add-percentage").click(function(){
var percentage_id = $(this).data('landing_id-percentage');
$.ajax({
url: 'ajax/readPercentage.php',
type: 'POST',
data: { percentage_id : percentage_id },
success: function(data) {
alert(data);
},
error: function(request, status, error){
alert("Error!! "+error);
}
});
});
My php code having an undefined index POST..
if(isset($_POST['percentage_id'])){
$percentage_id = $_POST['percentage_id'];
$query = mysqli_query($conn, "SELECT * FROM percentage WHERE percentage.percentage_id = '$percentage_id'");
}else{
echo "Index is not properly set!";
}
I hope someone can help me. Thanks in advance.
if($_SERVER['REQUEST_METHOD']=="POST"){
$data = file_get_contents('php://input');
print_r($data); // for testing purpose.
/*
$query = mysqli_query($conn, "SELECT * FROM percentage WHERE percentage.percentage_id = $data[0]['pecentage_id']");
*/
}else{
echo "Index is not properly set!";
}
Please use this code for ajax
$(".add-percentage").click(function(){
var percentage_id = $(this).data('landing_id-percentage');
$.ajax({
url: 'ajax/readPercentage.php',
type: 'POST',
dataType: 'json',
data: { percentage_id : percentage_id },
success: function(data) {
alert(data.status);
},
error: function(request, status, error){
alert("Error!! "+error);
}
});
});
<?php
$result_array= array();
if(isset($_POST['percentage_id'])){
$percentage_id = $_POST['percentage_id'];
$select_query = "SELECT * FROM percentage WHERE percentage.percentage_id =".$percentage_id;
$query = mysqli_query($conn,$select_query);
$result_array['status'] = 'success';
$result_array['success_msg'] = 'Data get successfully';
}else{
//echo "Index is not properly set!";
$result_array['status'] = 'failure';
$result_array['error_msg'] = 'Index is not properly set!';
}
echo json_encode($result_array);
die();
?>
Related
I am passing some json to a php file but the variables in the php remain empty im sure it is some small syntax error but i am unable to find what is causing this, any help will be greatly appreciated.
JAVASCRIPT
if(score >= 100)
{
console.log("HERE WE GO");
$.ajax({
type: "POST",
url: "FAKENAME.php",
data: { "data": "{ \"id\": " + id + ", \"quiz\": \"" + getDateTime() + "\"}" },
}).done(function (data) {
console.log(JSON.stringify(data) + "This is the data on .done");
//alert( data );
})
.fail(function () {
console.log("error");
//alert( "error" );
})
.always(function (data) {
console.log("finished");
console.log(JSON.stringify(data));
//alert( "finished" );
});
}
PHP
$data = json_decode($_POST['data']);
$sql = $conn->prepare("SELECT * FROM FAKEDATABASETABLENAME WHERE id = :id");//no error
$sql->bindParam(':id', $data->id);
//$sql->bindParam(':quiz', $data->quiz);
$sql->execute(); //syntax error
if(!empty($data->id))
{
$qry = $conn->prepare("UPDATE FAKEDATABASETABLENAME SET Quiz = '2018-06-27 14:44:49' WHERE id = 000007"); //no error and result
$qry->bindParam(':id', $data->id);
$qry->bindParam(':quiz', $data->quiz);
$qry->execute();
}
else
{
$mailto = "FAKEEMAIL.com" ; //Recipent of the email
$from = "From: PHP_DEBUG";
$subject = "PHP_DEBUG";
$data = json_decode($_POST['data']);
$content = "id is: " . $data->id. " plaese note. quiz is: " . $data->quiz. " please note.";
mail($mailto, $subject, $content, $from);
}
if(score >= 100)
{
var params = JSON.stringify({id: id, quiz: getDateTime()})
$.ajax({
type: "POST",
url: "FAKENAME.php",
dataType: "json",
data: {data: params}
}).done(function (data) {
console.log(JSON.stringify(data) + "This is the data on .done");
}).fail(function () {
console.log("error");
//alert( "error" );
}).always(function (data) {
console.log("finished");
console.log(JSON.stringify(data));
//alert( "finished" );
});
}
You can simplify your code like this
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}
$('#target').html('sending..');
$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
Please add full url of your php page then you have to check print_r($_POST) like that
I am asking for help with my code. I am trying to get values then send it to php script through ajax by jquery. I can get the values but I don't know what's wrong with it. Your help is appreciated :)
Ajax:
$(".Qty").submit(function(e){
data_form = parseInt($(this).find(".buyQty").val());
id = parseInt($(this).attr('name'));
console.log("id :", id, "Quantity: ", data_form);
$(this).find(".addCart").val('Adding...');
$.ajax({
url: "php/cart_process.php",
type: "POST",
data: {'id': id, 'qty': data_form},
success: function(data){
$("#cart-info").html(data.items);
$(".Qty").find(".addCart").val('Add to Cart');
alert("Item added to Cart!");
if($(".shopping-cart-box").css("display") == "block"){
$(".cart-box").trigger( "click" );
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
e.preventDefault();
});
php:
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];
echo "<script>console.log('id received: " .$id. "' );</script>";
}
?>
Your php script isn't returning a JSON object like your JS expects.
Your JS expects data to be a JSON object and you are trying to get the value in the index items. E.G data.items
Try this.
PHP
<?php
if(isset($_POST['id'])){
$output = array();
$id = $_POST['id'];
$output['items'] = "<p>id received: {$id} </p>";
echo json_encode($output);
}
?>
JQuery
$(".Qty").submit(function(e){
data_form = parseInt($(this).find(".buyQty").val());
id = parseInt($(this).attr('name'));
console.log("id :", id, "Quantity: ", data_form);
$(this).find(".addCart").val('Adding...');
$.ajax({
url: "php/cart_process.php",
type: "POST",
data: {'id': id, 'qty': data_form},
success: function(data){
console.log('raw data:');
console.log(data);
$("#cart-info").html(data.items);
$(".Qty").find(".addCart").val('Add to Cart');
alert("Item added to Cart!");
if($(".shopping-cart-box").css("display") == "block"){
$(".cart-box").trigger( "click" );
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
e.preventDefault();
});
I am trying to login with ajax. The script is working well and I am getting logged in but I am not getting redirected to the dashboard.php file. Codes are given below. Please try to help me out.
Ajax call
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
};
$.ajax({
type: "POST",
url: "login-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$('#loading-image').show();
},
complete: function(){
$('#loading-image').hide();
},
success: function(html){
$('.message').html(html).fadeIn(500);
}
});
return false;
});
});
</script>
login-process.php
<?php
include'config/db.php';
$msg = null;
$date = date('Y-m-d H:i:s');
$uname = (!empty($_POST['username']))?$_POST['username']:null;
$pass = (!empty($_POST['password']))?$_POST['password']:null;
if($_POST){
$stmt = "SELECT * FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':uname', $uname);
$stmt->execute();
$checklgn = $stmt->rowCount();
$fetch = $stmt->fetch();
if($checklgn > 0){
if(password_verify($pass, $fetch['mem_pass'])){
session_start();
$_SESSION['sanlogin'] = $fetch['mem_id'];
$msg = "<div class='message-success'>Access Granted! Please wait...</div>";
$go_login = header("refresh:2; url=dashboard.php");
}else{
$msg = "<div class='message-error'>Password mismatch. Please try again!</div>";
}
}else{
$msg = "<div class='message-error'>User not found. Please try again!</div>";
}
}
echo $msg;
echo $go_login;
?>
If you use AJAX to log in, you must use javascript to redirect. Redirecting PHP will only result in the AJAX call being redirected which doesn't produce the desired result.
In your success clause of the ajax request you can add window.location.replace("dashboard.php");
In you ajax success:
use window.location.href="/uri/to/redirect";
setTimeout(function(){
window.location.href="/uri/to/redirect";
},2000);
You cannot use header PHP function in this situation.
You should redirect in your $.ajax function like this:
1) You should return JSON in your login-process.php:
...
$result = array();
if($_POST){
$stmt = "SELECT * FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':uname', $uname);
$stmt->execute();
$checklgn = $stmt->rowCount();
$fetch = $stmt->fetch();
if($checklgn > 0){
if(password_verify($pass, $fetch['mem_pass'])){
session_start();
$_SESSION['sanlogin'] = $fetch['mem_id'];
$result = array(
'msg' => "<div class='message-success'>Access Granted! Please wait...</div>",
'redirect' => 'dashboard.php',
);
}else{
$result = array(
'msg' => "<div class='message-error'>Password mismatch. Please try again!</div>",
);
}
}else{
$result = array(
'msg' => "<div class='message-error'>User not found. Please try again!</div>",
);
}
}
echo json_encode($result);
exit;
2) You should add parameter dataType into your $.ajax call and process attribute redirect of the server answer (if this attribute exists):
$(document).ready(function () {
$("#submit").click(function () {
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
};
$.ajax({
dataType: 'json', // <-- set expected dataType here
type: "POST",
url: "login-process.php",
data: dataString,
cache: true,
beforeSend: function () {
$('#loading-image').show();
},
complete: function () {
$('#loading-image').hide();
},
success: function (data) {
$('.message').html(data.message).fadeIn(500);
// if we have attribute "redirect" in answer
if(typeof data.redirect !== 'undefined'){
// redirect here after 2 seconds
setTimeout(function(){
document.location.href = data.redirect;
},2000);
}
}
});
return false;
});
});
I can't get each data from PHP file, i'm always having AJAX failure, i tried many things, and looked for some pages for this problem but i can't find any solution, this is where i came last.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="someclass"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
e.preventDefault();
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$jsondata1 = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
echo json_encode($jsondata1);
}
mysqli_close($con);
I think there is no need to share HTML file, but if you want i can share with you.
Thank You!
You are overriding the array value in the loop and echo $jsondata1, so you are sending many different arrays with the echo inside the loop, try this code:
$jsondata1 = array();
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
echo json_encode($jsondata1);
e.preventDefault(); is a problem. e is not defined and if it was the default action would have already occurred by the time the success function was called. Try
$('a[class="someclass"]').click(function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
You need to encode the complete response.
when you echo each encoded it will not work.
Do something like
$jsonArray = array();
while(){
array_push($jsonArray, array($row['data1'], $row['data2']);
}
echo json_encode($jsonArray);
You're calling json_encode multiple times when what you need to be doing is assigning those intermediate variables to an array and encode that array using json encode for the return.
PHP:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
$jsondata1 = [];
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
mysqli_close($con);
die(json_encode($jsondata1));
JavaScript:
$(document).ready(function () {
var doc = $(document);
doc.on('click', 'a.someclass', function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
I was wondering if I can return an error callback back to my jquery from my php page that I created, which will then display an alert based upon the actions that happen in my php page. I tried creating a header with a 404 error but that didn't seem to work.
Sample JQuery Code:
$(document).ready(function()
{
var messageid= '12233122abdbc';
var url = 'https://mail.google.com/mail/u/0/#all/' + messageid;
var encodedurl = encodeURIComponent(url);
var emailSubject = 'Testing123';
var fromName = 'email#emailtest.com';
var dataValues = "subject=" + emailSubject + "&url=" + encodedurl + "&from=" + fromName + "&messageID=" + messageid;
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function() {
alert('ERROR - MessageID Duplicate')
}
});
return false;
});
});
Sample PHP Code aka somepage.php:
<?php
include_once('test1.php');
include_once('test2.php');
if(isset($_GET['subject']))
{
$subject=$_GET['subject'];
}
else
{
$subject="";
}
if(isset($_GET['url']))
{
$url=$_GET['url'];
}
else
{
$url="";
}
if(isset($_GET['from']))
{
$from=$_GET['from'];
}
else
{
$from="";
}
if(isset($_GET['messageID']))
{
$messageID = $_GET['messageID'];
}
else
{
$messageID="";
}
$stoqbq = new test2($from, $messageID);
$msgID = new stoqbq->getMessageID();
if($msgID = $messageID)
{
header("HTTP/1.0 404 Not Found");
exit;
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
}
?>
-EDIT-
If you get the invalid label message when using json this is what I did to fix this problem:
Server Side PHP Code Part-
if($msgID == $messageID)
{
$response["success"] = "Error: Message Already In Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new SendToQuickbase($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
$response["success"] = "Success: Sent To Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
Client Side JQuery Part-
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
cache: false,
contentType: "application/json",
dataType: "json",
url: "http://somepage.php?&callback=?",
success: function(response){
alert(response.success);
}
});
return false;
});
You can a return a JSON response from your PHP with a success boolean.
if($msgID = $messageID)
{
echo json_encode(array('success' => false));
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
echo json_encode(array('success' => true));
}
and in your Javascript:
$.ajax({
type: 'GET',
dataType: 'json',
data: dataValues,
url: 'http://somepage.php',
success: function(response){
if(response.success) {
alert('Success');
}
else {
alert('Failure');
}
}
});
There is an accepted q/a with the same thing: How to get the jQuery $.ajax error response text?
Basically you need to grab the response message from the error callback function:
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});