Ajax in jquery, php isset cannot detect the value posted - php

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

Related

How to fix undefined POST index from AJAX?

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();
?>

javascript json to php variable

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

ajax not sendind data to php

I have a function that is supossed to send data to a php file..although i get an alert that shows the correct ID and a success message, when trying to echo it out in my process.php, nothing is showed..the function is in adopt.php, the file that refers to process.php:
<script type="text/javascript">
$(function(){
$('#loginform').submit(function(e){
return false;
});
<?php
$q = pg_query($conn, "SELECT * FROM caini_donati");
while($res = pg_fetch_assoc($q)){ ?>
$('#<?php echo $res['id_caine']; ?>').leanModal({ top: 110, overlay: 0.45, closeButton: ".hidemodal" });
$("#<?php echo $res['id_caine']?>").click(function(event) {
var id_caine = event.currentTarget.id;
alert(id_caine);
$.ajax({
type: 'POST',
url: 'process.php',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: { id_caine : id_caine},
success: function(data){
alert("succes"),
console.log(data);
}, error: function(xhr, ajaxOptions, thrownError) {alert ("Error:" + xhr.responseText + " - " + thrownError );}
});
});
<?php } ?>
});
</script>
in process.php i have:
<?php
$var = $_POST['id_caine'];
echo "tr1: ".$_POST['id_caine'];
echo "try: ".$var;
?>
Does anyone know what I'm doing wrong? In process.php i want to run an update query based on the 'id_caine' variable..Any ideea is apreciated..Not important but I have altmost no knowledge about ajax.
RiggsFolly is correct, you are missing the javascript html tags, i have tweaked your code to show you where they should be. Also i corrected the success method so that you actually had a variable to work with. You defined rs as the parameter but then tried to use "data" instead.
<?php
$q = pg_query($conn, "SELECT * FROM caini_donati");
while($res = pg_fetch_assoc($q)){ ?>
<script type="text/javascript">
$('#<?php echo $res['id_caine']; ?>').leanModal({ top: 110, overlay: 0.45, closeButton: ".hidemodal" });
$("#<?php echo $res['id_caine']?>").click(function(event) {
var id_caine = event.currentTarget.id;
alert(id_caine);
$.ajax({
url: 'process.php',
type: 'POST',
data: { id_caine : id_caine},
dataType: 'html',
success: function(data){
alert("succes"),
console.log(data);
}, error: function(xhr, ajaxOptions, thrownError) {alert ("Error:" + xhr.responseText + " - " + thrownError );}
});
});
</script>
<?php } ?>

ajax - check if a username exists + return message if it does

im trying to check if a username a user wants is already taken without having to send the form, basically onBlur of the username field.
I'm having some trouble and have a few questions.
I have my input field plus js:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#username').on('blur', checkdb);
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: 'desiredUsername='+desiredUsername,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
});
</script>
<input type="text" name="username" id="username">
and my check-db.php file:
$mysqli = mysqli_connect("localhost","connection info");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$desiredUsername = $_POST['desiredUsername'];
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = '?' ");
$stmt->bind_param('s', $desiredUsername);
$stmt->execute();
firstly: im getting an error from my php code, 'number of variables doesnt match number of parameters in prepared statement', which im a bit confused about? I have 1 variable and 1 peramater, don't i?
then, once this is actually working, how do I send a message/ variable back to the input page? so if the username is taken I can say so, or if its available say so?
thanks!
On the server size (PHP in your case), simply echo the things you want to pass to the client side (Javascript) like this :
echo json_encode($datas); //can be array or whatever
Then on the Client side :
$.ajax({
method: 'POST',
dataType:'json',
data: {'username' : desiredUsername}, //then getting $_POST['username']
success: function(datas) {
console.log(datas); //Your previous data from the server side
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus);
}
});
try
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: {
desiredUsername: desiredUsername
},
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
You have an error when sending the data, you should send a JS Object as data, like this:
data: { desiredUsername: desiredUsername },

Receive PHP parameters with jQuery ajax post

I am sending data via jQuery's .ajax method to my PHP file. Both files are on the same domain. The file making the post looks like this..
$('#pdf').click(function() {
var proj_name = $('#proj_name').text();
var date = $('#date').text();
var req_comp_date = $('#req_comp_date').text();
var status = $('#status').text();
var secondUserID = $('#secondUserID').text();
var postData = {
"proj_name" : proj_name,
"date" : date,
"req_comp_date" : req_comp_date,
"status" : status,
"secondUserID" : secondUserID,
};
console.log(postData);
$.ajax({
type: "POST",
url: "test.php",
data: postData,
success: function(){
alert(proj_name + ' ' + status);
window.open("test.php");
}
});
});
And the PHP file getting the post data is...
//request parameters
$proj_name = $_POST['proj_name'];
$date = $_POST['date'];
$req_comp_date = $_POST['req_comp_date'];
$status = $_POST['status'];
$secondUserId = $_POST['secondUserId'];
echo 'postData: ' . var_dump($_POST);
if ($_POST)){
echo $proj_name;
echo $date;
echo $req_comp_date;
echo $status;
echo $secondUserId;
} else {
echo 'problem';
}
In my firebug console, I can see that the parameters posted with .ajax, but I cannot get the post via PHP. Can anyone help me out please? Thank you.
Add the error callback to your to your $.ajax call to debug if the request is failing.
$.ajax({
type: "POST",
url: "test.php",
data: postData,
success: function(){
alert(proj_name + ' ' + status);
window.open("test.php");
},
// Alert status code and error if fail
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
Update
Change this:
if ($_POST)){
echo $proj_name;
echo $date;
echo $req_comp_date;
echo $status;
echo $secondUserId;
} else {
echo 'problem';
}
To this:
if ($_POST)){
// Make a array with the values
$vals = array(
'proj_name' => $proj_name,
'date' => $date,
'req_comp_date' => $req_comp_date,
'status' => $status,
'secondUserId' => $secondUserid
);
// Now we want to JSON encode these values to send them to $.ajax success.
echo json_encode($vals);
exit; // to make sure you arn't getting nothing else
} else {
// so you can access the error message in jQuery
echo json_encode(array('errror' => TRUE, 'message' => 'a problem occured'));
exit;
}
Now in your jQuery .success callback:
success: function(data){ // Our returned data from PHP is stored in "data" as a JSON Object
alert(data.req_comp_date); // access your returned vars like this.
// data.date; // is your posted date.. etc
alert(data.proj_name + ' ' + data.status);
window.open("test.php");
// You can also get your error message like so..
if(data.error) // if its true, we have a error, so display it.
alert('ERROR: ' + data.message);
},
You dont really have to do this next bit (jquery does a good job of determining the data type returned), but its nice to have it in the code to understand what is being returned.
$.ajax({ ...
type: "POST",
url: "test.php",
data: postData,
dataType: "json" // <-- Add this to tell jquery, we are being returned a JSON object.
.... });

Categories