jQuery -> AJAX -> PHP - php

I've been searching and searching, but unfortunately I can't find any answers that relates to my problem.
I'm having trouble to read data that I've sent through jQuery (ajax) in my PHP script.
jQuery:
$('.sendOrder').click(function(){
if (validateForm() == true) {
(function($){
var convertTableToJson = function()
{
var rows = [];
$('table#productOverview tr').each(function(i, n){
var $row = $(n);
rows.push ({
productId: $row.find('td:eq(0)').text(),
product: $row.find('td:eq(1)').text(),
size: $row.find('td:eq(2)').text(),
price: $row.find('td:eq(3)').text(),
quantity: $row.find('td:eq(4)').text(),
});
});
var orderObj = [];
orderObj.push({
name: $("#customerName").val(),
email: $("#customerEmail").val(),
phone: $("#customerPhone").val(),
order: rows
});
return orderObj;
console.log(orderObj);
}
$(function(){
request = $.ajax({
url: 'shop/sendData.php',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(convertTableToJson()),
success: function(ret) {
console.log(ret);
}
});
When I'm looking at Chrome it seems to be sent correctly with json:
[
{
"name":"Kristian",
"email":"kristian#example.com",
"phone":"12345678",
"order":[
{
"productId":"Prod #",
"product":"Produkt",
"size":"Str",
"price":"Pris",
"quantity":"Antall"
},
{
"productId":"09",
"product":"Bokser",
"size":"2 meter (249kr)",
"price":"249,- eks mva",
"quantity":"1 stk"
},
{
"productId":"09",
"product":"Bokser",
"size":"2 meter (249kr)",
"price":"249,- eks mva",
"quantity":"1 stk"
}
]
}
]
In my sendData.php I've got it pretty plain:
<?PHP header('Content-Type: application/json');
echo json_encode($_POST);
The return I'm getting are:
[]
What am I doing wrong? What have I forgotten?

$_POST expects an identifier. In your AJAX you'll have to supply one, for example:
request = $.ajax({
url: 'shop/sendData.php',
type: 'POST',
dataType: 'json',
// note the change here, adding 'json' as the name or identifier
data: { json: JSON.stringify(convertTableToJson())},
success: function(ret) {
console.log(ret);
}
});
Then you should be able to see the JSON string in $_POST['json']

Solved by using file_get_contents("php://input") instead of post.
I.e
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params)) {
$decoded_params = json_decode($json_params);
echo $decoded_params[0]->name;
}
Returned "Kristian"

Related

How to send json to php via ajax?

I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/

Sending an array from jquery to PHP and back

I have a list of options (categories) of projects that the user can see. By selecting the categories, the div below should update with the lists of projects matching said categories.
Despite using the following answer, almost verbatim, Send array with Ajax to PHP script, I am still unable to retrieve any results, and yet no errors show up either.
The jquery:
// filter for projects
var $checkboxes = $("input:checkbox");
function getProjectFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
$checkboxes.on("change", function(){
var opts = getProjectFilterOptions();
//alert(opts);
var categories = JSON.stringify(opts);
$.ajax({
url: "/web/plugins/projcat.php",
type: "POST",
dataType: "json",
data: {data : categories},
cache: false,
success: function(data) {
$('#projects').html(data);
//alert(data);
}
});
});
the php (still in testing, so not filled out):
<?php
if(isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
print_r($data);
}
?>
Where is the error?
Try this:
JS
...
// dataType: "json", // remove that; you're not sending back JSON string
data: {categories : categories},
cache: false,
...
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
// .. process the $data
print_r($data);
return;
}
?>
Your desired array is in $_POST['data'] and not in $_POST['projcats']. Change data: {data : categories}, to data: { projcats: categories }, to use $_POST['projcats'].

PHP does not receive my JSON sent by jQuery AJAX

I have a problem that puzzles me. I have an ajax function that sends a json object, and I see the JSON parsed in the F12 Chrome Headers, and I receive the success alert.
$(document).ready(function() {
var test = {'bob':'foo','paul':'dog'};
$.ajax({
url: "test.php",
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(test),
success: function(data) {
alert("Bien: " + data);
},
failure: function(errMsg) {
alert("Mal: " + errMsg);
}
});
});
But in my PHP page I cannot see any POST, anything. I can see that my post is received but anything else:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "post"; //Result 'post'
}
foreach( $_POST as $stuff ) {
echo $stuff; //Nothing at all
}
print_r(json_decode($_POST["data"], true)); // Undefined index: data
In the same code I use
$.post( "test.php", { data: { name: "John", time: "2pm" } } );
and works, then is something related with the code, but I cannot really see waht is it.
Thank you for your help!
try this instead
$results = json_decode(file_get_contents('php://input'));
echo $results->bob //Result foo

ajax not properly parsing the value returned by php

I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});

kendo grid request null when update and sent type is create

I am using the Kendo UI Grid. Basically, what I want to do is bind the grid on remote data which are sent on json format and be able to edit it.
The Grid receive the data and display it as I want. However, when I want to edit a cell, the request received in the php file is null, and the type sent is "create" while I would like it to be an "update".
Here is the code used:
-the javascript contains the grid declaration
$(document).ready(function() {
var dataSource = new kendo.data.DataSource({
batch: true,
transport: {
read: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=read"
},
update: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=update"
},
create: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=create"
},
destroy: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=destroy"
}
},
schema: {
data: function(result) {
return result.Result || result.data;
},
model: {
id: "bbmindex",
fields: {
totalvente: {type: "number"}
}
},
total: function(result) {
return result.totalData || result.PageSize || result.length || 0;
}
}
});
var param = {
columns: [
{
field: "naturetravaux", title: "nature travaux"
},
{
field: "totalvente", title: "total vente"
}
],
selectable: 'multiplerows',
editable: true,
toolbar: ["create", "save", "cancel", "destroy"],
dataSource: dataSource
};
$("#grid").kendoGrid(param);
});
-the php script send the data to the dataSource
<?php
header('Content-Type: application/json');
$request = json_decode(file_get_contents('php://input'));
$type = $_GET['type'];
$result = null;
if ($type == 'create') {
some code
} else if ($type == 'read') {
some code which send the data
} else if ($type == 'update') {
some code
}
echo json_encode($result);
?>
any idea about what is wrong here?
Any help would be much appreciated,
thank you in Advance
Martin
If your server receives a create is because the idof the edited record is 0, null or undefined. Please check that you get from the server a field called bbmindex and is not 0
You expect the request to be posted as JSON however the Kendo DataSource doesn't do that by default. You need to use the parameterMap option and make it return JSON:
parameterMap: function(data, type) {
return kendo.stringify(data);
}

Categories