Receive Json post and convert it to PHP variable - php

i'm trying to convert/retrieve Json Post to php variable.
i have this payment.php script
<script>
$(document).ready(function(){
$("#send").click(function(){
var aksi='';
var jdata= JSON.stringify({
"code":"02",
"accountNo":"5503722012345678",
"amount":200,
"transDate":"20190109161439",
"traceNo":"1234567890",
"signature":"08CA625868C1E6FFC00D89EA7B668BD7"
});
$.ajax({
url:"receive.php",
type:"POST",
data:jdata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(resp){
// Check the values in console
console.log(resp);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
});
</script>
and on receive.php i have this code:
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
echo 'Request method must be POST!';
exit;
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
echo 'Content type must be: application/json';
exit;
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(!is_array($decoded)){
echo 'Received content contained invalid JSON!';
exit;
}
//Sample php variable
$code = $decoded['code'];
echo $code;
but i don't get anything on console, whether it error message or the value of $code, it only blank.
what are wrong in my code, can you help me?

Try with this code, I have removed the datatype from request code.
var aksi='';
var jdata= JSON.stringify({
"code":"02",
"accountNo":"5503722012345678",
"amount":200,
"transDate":"20190109161439",
"traceNo":"1234567890",
"signature":"08CA625868C1E6FFC00D89EA7B668BD7"
});
$.ajax({
url:"http://localhost/stackoverflow.php",
type:"POST",
data:jdata,
contentType: "application/json",
success:function(resp){
// Check the values in console
console.log("kk");
},
failure: function(errMsg) {
alert(errMsg);
}
});
I am also putting the code in script tag please check this also
<script>
$(document).ready(function(){
$("#send").click(function(){
var aksi='';
var jdata= JSON.stringify({
"code":"02",
"accountNo":"5503722012345678",
"amount":200,
"transDate":"20190109161439",
"traceNo":"1234567890",
"signature":"08CA625868C1E6FFC00D89EA7B668BD7"
});
$.ajax({
url:"http://localhost/stackoverflow.php",
type:"POST",
data:jdata,
contentType: "application/json",
success:function(resp){
// Check the values in console
console.log("kk");
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
});
</script>

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/

correct JSON format from Jquery to PHP

I'm working on a project coding PHP-AJAX-Jquery and JSON and need to send the information of a form that has three input fields to a php file that will store the info of the three fields in the database.
my problem is that I need(I have because of project spec) to use Jquery-AJAX and JSON and I think I'm passing in a malformed JSON string to the PHP file, this is the js that is supposed to handle the call:
$(document).ready(function(){
$('#ID_formulario').on('submit',function(e) {
e.preventDefault();
var nombre = $('input#ID_nombre');
var email = $('input#ID_email');
if(validaForm(nombre, email)){
var url = $(this).attr('action');
var data = $(this).serializeArray();
var type = $(this).attr('method');
alert(data);
$.ajax({
url:url,
data:data,
type:type,
cache: false,
contentType: "application/x-www-form-urlencoded",
dataType: 'json',
beforeSend: function () {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="imagen.gif" align="absmiddle"> <span class="loading">Realizando peticion...</span>');
},
error: function(){
alert("error peticiĆ³n ajax");
},
success: function(datos){
$('#result').empty().html(respuesta). fadeIn('slow').delay(5000).fadeOut();
$('#ID_formulario')[0].reset();
$('input#ID_nombre').focus();
$("#flash").hide();
//$("#display").after(html);
//$("#result").append(data);
}
});
}
});
});
my questions are: how to send the info of the three fields in a valid JSON format to the php file? is there any jquery function that helps? or is serializeArray() enough?
It's okay to use success: function(datos) or should I replace it to .done(function)) ?
thanks in advance.
You dont need to send anything as JSON to PHP. Just send it with type: POST and read it in PHP. Then return it as JSON to read in Javascript. You just read the $_POST in PHP. I believe you've mistaken your project specs and you need to RETURN data from PHP as JSON.
This is one of my projects:
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "product"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(data) {
$(".the-return").html(
// Read returned JSON. Exammple
"<div class='data-row'><strong>TYPE</strong> " + data["title"]+ "</div>";
);
}
});
return false;
});
});
In PHP you take the POST and read data.
response.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 "product": sendValues();
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';
}
// Do everything with $_POST's here
function sendValues(){
$return = $_POST;
$return["title"] = 'Something';
$return["json"] = json_encode($return);
echo json_encode($return); // Return JSON formatted data to Javascript.
}

jQuery AJAX call returns results before page headers resulting in parseerror

I am trying to create a simple AJAX call using JSON, but I keep getting a parse error on the result and when I check the resultText it shows the source code of the entire page, with the JSON response showing a success above the page headers.
Here is my AJAX call, where #class is a select box with values.
$("#class").change( function () {
if($('#class').val().length > 0){
$.ajax({
type: "GET",
url: "http://192.168.0.9/ajax",
data: 'class_id=' + $("#class").val(),
datatype: 'json',
async: 'true',
beforeSend: function() {
alert("Before send!");
},
success: function(result){
if (result.status){
$('#result').html(result);
} else {
alert('request unsuccessful!');
}
},
complete: function() {
alert("Complete!");
},
error: function (request,error) {
alert('A jQuery error has occurred. Status: ' + error +':'+ request.responseText);
$("#result").html(request.responseText);
}
});
} else {
alert('Please make a selection');
}
return false;
});
This is my PHP function that returns the result
$result = array();
$result['status'] = "success";
$result['message'] = "Types";
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($result);
Finally, this is the response I am getting in my error alert:
A jQuery error has occurred status:parseerror
{"status":"success", "message":"Types"}<!DOCTYPE html>
<html>
...rest of my page from where the request was sent
I am hoping this is a simple error and someone can tell me what I am doing wrong?
Perhaps your parameter should be pass in JSON format:
data: "{'class_id':'" + $("#class").val() + "'}",
Try to remove datatype:'json' from the Javascript and header("Content-Type: application/json; charset=utf-8", true); it should be recognize itself

Jquery ajax POST response is null

I have a js script that does an ajax request and posts the data to a php script, this script with then echo something back depending if it works or not.
here is the JS
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 6000);
});
here is the php:
if(isset($_POST["json"]))
{
$json = json_decode($_POST["json"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
So basically, i thought the response in the `success: function(response)' method would be populated with either "IT WORKED!!!" or "NOT POSTED" depending on the if statement in the php. Now everything seem to work because the js script manages to go into the success statement but prints this to the console:
Response was null
I need to be able to get the return from the server in order to update the screen.
Any ideas what I'm doing wrong?
Try:
if(isset($_POST["markets"]))
{
$json = json_decode($_POST["markets"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
use this in your php file
if(isset($_POST["markets"]))
{
}
instead of
if(isset($_POST["json"]))
{
.
.
.
.
}
Obiously the if(isset($_POST["json"])) statement is not invoked, so neither of both echos is executed.
The fact that the function specified in .ajax success is invoked, only tells you that the http connection to the url was successful, it does not indicate successful processing of the data.
You are using "success:" wrong.
Try this instead.
$.post("signals.php", { markets: post_data }).done(function(data) {
/* This will return either "IT WORKED!!!!" or "NOT POSTED" */
alert("The response is: " + data);
});
Also have a look at the jQuery documentation.
http://api.jquery.com/jQuery.post/
Look, You send data in market variable not in json. Please change on single.php code by this.
$json_data = array();
if(isset($_POST["markets"]))
{
// $json = json_decode($_POST["markets"]);
$json = ($_POST["markets"]);
if(!empty($json))
echo "IT WORKED!!!!";
else
echo "NOT POSTED";
}
And change on your ajax function
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'post',
// contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
},6000);
});
You have to you change you $.ajax call with
//below post_data array require quotes for keys like 'market_number' and update with your required data
post_data = [ {'market_number':1, 'name':'name1'},
{'market_number':2, 'name':'name2'}];
//console.log(post_data);
$.ajax({
url: "yourfile.php",
type:'post',
async: true,
data:{'markets':post_data},
dataType:'json',
success: function(data){
console.log(data);
},
});
and you php file will be
<?php
if(isset($_POST['markets']))
{
echo "It worked!!!";
}
else
{
echo "It doesn't worked!!!";
}
//if you want to work with json then below will help you
//$data = json_encode($_POST['markets']);
//print_r($data);
?>
in your php file check the $_POST:
echo(json_encode($_POST));
which will tell if your data has been posted or not and the data structure in $_POST.
I have used the following code to covert the posted data to associative array:
$post_data = json_decode(json_encode($_POST), true);

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

Categories