javascript json to php variable - php

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

Related

Can't send data with POST method by jquery

I want to send some data to the file, and it get the file, but there no data
This is my .js code
var ids = [$(this).parent('.status-menu').prev('td').find('input').val()];
var status = $(this).find(":selected").text();
var changeStatusRKO = true;
$.ajax({
url: window.location.origin + '\\partsOfPages\\ajax\\changeStatus.php',
type: "POST",
data: {
'ids': ids,
'status': status,
'changeStatusRKO': changeStatusRKO,
},
success: function () {
console.log('Success');
},
fail: function () {
console.log('Error');
},
})
And this is my php, where I am sending the data
<?php
print_r($_POST);
if(isset($_POST["changeStatusRKO"]) OR isset($_POST["changeStatusRegistrationBusiness"]) OR isset($_POST["changeStatusServiceOneClick"])
OR isset($_POST["changeStatusAcquiring"]) OR isset($_POST["changeStatusCashDesk"])) {
$idItem = $_POST["idItem"]; //id строки в одной из пяти таблиц (`banks_to_requests_for_XXX`); массив
// echo "print_r: "; print_r($idItem); echo "<br>";
// echo "idItem[0]: " . $idItem[0] . "<br>";
if(!isset($idItem[0]))
...
But when I send it, there are no parameter in $_POST
Use 'method' instead of 'type'. Try this:
$.ajax({
url: window.location.origin + '\\partsOfPages\\ajax\\changeStatus.php',
method: "POST",
data: {
ids: ids,
status: status,
changeStatusRKO: changeStatusRKO,
},
success: function () {
console.log('Success');
},
fail: function () {
console.log('Error');
},
})
Also, you can use your browser's developer tools to see what's actually being passed to the server. In Chrome, you can go to Inspect > Network tab > Click on your request > Headers tab.
I solve this problem. I only need to change this part
url: window.location.origin + '\\partsOfPages\\ajax\\changeStatus.php',
to this
url: window.location.origin + '\\partsOfPages\\ajax\\changeStatus',
I removed .php in the end

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

Ajax in jquery, php isset cannot detect the value posted

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

Ajax success function parameter empty?

Im getting an empty success function parameter back (lewa).
But when I change 'lewa' to order (order.vnaam) it works. Could you point out what the problem is?
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'json-users.php',
dataType: 'json',
success: function(naam) {
$.each(naam, function(i, item) {
$('ul').append('<li>Voornaam: ' + item.voornaam + '<br>Achternaam: ' + item.achternaam + '</li>');
});
}
}); //end get data db
}); //end document ready function
function upload() {
var order = {
vnaam: $('.voornaam').val(),
anaam: $('.achternaam').val(),
};
$.ajax({
type: 'POST',
url: 'posttest.php',
/*dataType: 'json',*/
data: order,
success: function( lewa ) {
//When action is a success
$('ul').append('<li>Voornaam: ' + lewa.vnaam + '<br>Achternaam: ' + lewa.anaam + '</li>');
console.log(lewa);
console.log(order);
},
error: function() {
//When action is a failure
alert('error running function');
}
});
}
The following code is posttest.php
$voornaam = mysqli_real_escape_string($connect, $_POST["vnaam"]);
$achternaam = mysqli_real_escape_string($connect, $_POST["anaam"]);
$sql = "INSERT INTO users (voornaam, achternaam) VALUES ('".$voornaam."', '".$achternaam."')";
mysqli_query($connect, $sql);
The following code is json-users.php
$array_user = array();
while ( $data = mysqli_fetch_assoc($result) ) {
$array_user[] = $data;
}
echo json_encode($array_user);
Didnt return anything from posttest.php

How to get the values from a $.ajax using php

I'm trying to use $.ajax to send some values to a php page which then sends an email,
I can't figure out how to get the values from $.ajax in my php file,
any help would be appreciated,
$(function() {
$('form#email input[type=image]').click(function() {
var name = $('form#email #name').val();
var enq = $('form#email #enq').val();
var dataString = 'name=' + name + '&enq=' + enq;
$.ajax({
type:'POST',
url:'email.php',
data:dataString,
success:function() {
$('form#email').fadeOut();
}
});
$('form#email')[0].reset();
return false;
});
});
php file
if (isset($_POST['submit_x'])) {
$name = $_POST['name'];
$enq = $_POST['enq'];
$name = htmlentities($name);
$enq = htmlentities($enq);
//echo $name,$enq;
$to = 'amirkarimian#hotmail.co.uk';
//$to = 'tutor#inspiretuition.co.uk'
$subject = 'Enquiry';
$message = $enq;
mail($to,$subject,$message);
if(!mail) {
echo 'failed to send mail';
}
}
the email doesn't get sent.
if I dont use $.ajax and submit the form normally the email get sent.
thanks
You're checking for a variable you're not submitting, submit_x, you'll need to remove that outer if check. Also, it's better to let jQuery serialize your strings properly (what if there's a & in there?) like this:
$(function() {
$('#email input[type=image]').click(function() {
$.ajax({
type:'POST',
url:'email.php',
data: { name: $('#name').val(), enq: $('#enq').val() }
success:function() {
$('form#email').fadeOut();
}
});
$('#email')[0].reset();
return false;
});
});
Or if the <form> elements have proper name attributes (they should, for graceful degradation) , you can replace data: { name: $('#name').val(), enq: $('#enq').val() }
with data: $('#email').serialize().
try sending 'submit_x' to php :)
You can use a data map to define your data:
var name = $('form#email #name').val();
var enq = $('form#email #enq').val();
$.ajax({
type: 'POST',
url: 'email.php',
dataType: 'html',
data: {
submit_x : 1,
name : name,
enq : enq
},
success: function(html){
$('form#email').fadeOut();
},
error: function(e, xhr) { alert('__a Error: e: ' + e + ', xhr:' + xhr); }
});

Categories