Sending Json to PHP Using Ajax

Sending JSON to PHP using ajax

Lose the contentType: "application/json; charset=utf-8",. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).

That should make what you have work.

Thing is, you don't need to use JSON.stringify or json_decode here at all. Just do:

data: {myData:postData},

Then in PHP:

$obj = $_POST['myData'];

Sending json to php server using jquery ajax - json error

I was able to get the json object and parse it on php side. Some variable might be named different, partly because some of it is pre-written code. Here are the steps I took.

Folder Structure

js/script.js
php/get_data.php
index.html

Index.html
a basic form.

<div id="feedback_panel" class="panel panel-default">
<form id="feedbackform" name="feedbackform" method="post">
<div class="form-group" id="email_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="email">E-mail:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="email@example.com" required>
<span class="help-block"> </span>
</div>
<div class="form-group" id="subject_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="subject">Subject:</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required>
<span class="help-block"> </span>
</div>
<div class="form-group" id="description_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="message">message:</label>
<textarea type="text" class="form-control" id="message" name="message" placeholder="message." required></textarea>
<span class="help-block"> </span>
</div>
<button type="submit" id="feedback_submit" class="btn btn-success">Submit</button>
</form>
</div>

script.js
upon submit, gather data and set it to an object and send to php via ajax.

$(function() {
// process the form
$('#feedbackform').submit(function(event) {

// get the form data - obj that will POSTED to get_data.php
var formData = {
'email' : $('#email').val(),
'subject' : $('#subject').val(),
'message' : $('#message').val()
};

// process the forum
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'php/get_data.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
if ( ! data.success) {
console.log(data);
} else {
console.log(data);
}

});

// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});

});

get_data.php
receives the data from script.js, do some validations, and then send and an e-mail.

<?php

$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data

// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array

$email;
$subject;
$message;


//check to see if the data exist, else write an error message,
function check_data(){
$user_inputs = array();

if (empty($_POST['email'])){
$errors['email'] = 'Email is required.';
return false;
}else{
$email = $_POST['email'];
array_push($user_inputs,$email);
}

if (empty($_POST['subject'])){
$errors['subject'] = 'subject is required.';
return false;
}else{
$subject = $_POST['subject'];
array_push($user_inputs,$subject);
}

if (empty($_POST['message'])){
$errors['message'] = 'message is required.';
return false;
}else{
$message = $_POST['message'];
array_push($user_inputs,$message);
}

return $user_inputs;
}

//getting array of data from check_data
$verify_data = check_data();


// return a response ===========================================================

// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {

// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
echo json_encode($data);
} else {
// show a message of success and provide a true success variable
$data['success'] = $verify_data;
$data['message'] = 'Success!';

//if everything is good, sent an email.
if($verify_data != false){
send_email($verify_data);
}
}

function send_email($info_data){
// person who it going
$to = 'Email, Some <some_email@mailinator.com>';

//subject of the email
$subject = $info_data[1];
$result = str_replace(' ', ' ', $info_data[2]);
$result = nl2br($result);
$result = wordwrap($result, 70, "\r\n");

//body of the email.
$message = "<html><body>";
$message .= "<p style = 'width: 400px;'>" . $result . "</p>";
$message .= "<br/>";
$message .= "</body></html>";
$headers = "From: Email, Some <some_email@mailinator.com>" . "\r\n" . 'Reply-To: '. $info_data[0] . "\r\n" ."X-Mailer: PHP/" . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8";


//sent mail: check to see if it was sent.
if(mail($to, $subject, $message, $headers)){
$data["went"] = "went";
$data['message'] = 'Success!';
}else{
$data["went"] = "didn't go";
$data['message'] = 'Sorry!';
}

// echo the log
echo json_encode($data);

}

?>

lot to cover, let me know if you any questions. I'll be happy to answer.

how to pass JSON data to php using ajax post

1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure.

As I understand you are debugging the code, so syslog can be not the best idea.
I would simply use the browser network console to see the content of requests and a simple php file like this to see the content of $_POST:

<?php
echo json_encode($_POST);

In more complex cases - use the actual debugger.

2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?

You are trying to use the json key in your $_POST, but you didn't instruct jQuery to add it, so you are receiving not what you expected.

There are few issues with your $.ajax call, here is the commented version:

$.ajax({
type: 'POST',
url: './json.php',
dataType: 'json', // Note: dataType is only important for the response
// jQuery now expects that your server code
// will return json

// here you need to add the 'json' key
data: {'json': JSON.stringify(data)},

// the success method has different order of parameters
//success: function(xhr, status, errorMessage) {
success: function(data, status, xhr) {
alert("response was "+data);
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
}
});

Now on the server you will have $_POST['json'] with serialized string and you can json_decode it.

Alternatively you can send the JSON data without serialization:

var data = {'test': 'abc'};

$.ajax({
type: 'POST',
url: './json.php',
// No 'JSON.stringify()', just send your data
data: data,
...
});

And on the server you will have $_POST['test'] with abc value (so you have your json already converted into array).

How to capture json data on php that is sent with ajax (no jquery)

To get an array, add the true argument to json_decode().
In your code:

$body = json_decode(file_get_contents("php://input"), true);
var_export($body);

To add the JSON data in $_POST, you can use this code.

In JS:

json = JSON.stringify(data);
var ajax = new XMLHttpRequest(), url = '../handler.php';
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
};
};
ajax.open('POST', url, true);
ajax.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
ajax.send('jsn='+json);

In PHP:

$arr = isset($_POST['jsn']) ? json_decode($_POST['jsn'], true) :[];
var_export($arr);

Source: https://coursesweb.net/ajax/json-from-javascript-php

Saving data into a text file sent as JSON with Ajax

You must know that in PHP json_decode generates an Array that you can't write into an text file.

So only remove the json_decode command.

Posting JSON with jquery ajax to PHP

Your code works if you remove dataType: 'json', just tested it.

$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});

Sending JSON to PHP via AJAX is failing

dataType only means that you expect a JSON response.

Try using contentType instead.

$.ajax({
type: 'POST',
contentType: "application/json",
url: 'json.php',
data: {
json: jsonObj
},
dataType: 'json'
});


Related Topics



Leave a reply



Submit