i want to post a json object to php.
var user = {username:"test", password:"test", name:"test",
email:"test#hotmail.com"};
var str_json = JSON.stringify(user);
$.ajax({
url: '/register_API.php',
type: 'post',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log('success');
},
data: user
});
}
In php i want to insert it into mysql:
$data = file_get_contents('php://input');
$json = json_decode($data,true);
$username = $json['username'];
$password = $json["password"];
$email = $json['email'];
$insertSql = "INSERT INTO users (username, password, email)
VALUES ('$username', '$password', '$email');";
The $data string contains: username=test&password=test&name=test&email=test%40hotmail.com, but i can't get the variable by decoding...
Thanks in advance!
Change data: user to data: str_json and then
change $data = file_get_contents('php://input');
to $data = $_POST['data']
You're not sending a JSON string, you're sending a Javascript object which jQuery is translating to a set of parameters in the outgoing POST request. Your data will be available to PHP in $_POST - no need to decode it first.
Look for it like this:
$username = $_POST['username'];
$password = $_POST["password"];
$email = $_POST['email'];
I think you want to send raw JSON as text and have that be in the post body and not treated as an encoded form.
In this case I think your PHP code is right. Send the stringified JSON as you are, but set the data type to dataType: "text".
I think you will be able to read it with
$data = file_get_contents('php://input');
I think you can use
//works like explode, but splits your data where finds "=" and "&" too.
$output = preg_split( "/ (=|&) /", $data);
This will return an array of your data. where:
$output[0]="Username";
$output[1]="test";
This can be useful if you have fixed data.
Related
I need help of some advanced users of PHP, JSON, AJAX and jQuery. I need to use json_encode in foreach loop between two if statemnts, so I'm reading a lot on google and I was find somewhere that $jsonData=[]; need be declared before first if statement, but in this case when a form is submitted var_dump of jsonData return empty array or empty object if I add echo json_encode($jsonData, JSON_FORCE_OBJECT); Also, without JS file form is submitted correctly and all data is inserted into the database as well. However, this is my JSON returned when I comment JS file when a form is submitted: {"0":{"response":"success","content":"Hvala Vam Testing! Va\u0161a poruka je uspje\u0161no poslata vlasniku objekta Brod Ivana! Odgovor \u0107ete dobiti ubrzo!"}} or if I use just echo json_encode($jsonData) I get seguent JSON [{"response":"success","content":"Hvala Vam John Doe! Va\u0161a poruka je uspje\u0161no poslata vlasniku objekta Brod Ivana! Odgovor \u0107ete dobiti ubrzo!"}] However on https://jsonlint.com/ all twoo JSON it's valid JSON, but I can not figure out how to process it in jQuery for get this data on web page.
Hier it's PHP file with part of json_encode
$query_m = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query_m);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute();
$emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
$jsonData=[];
if(is_array($emails_other) && count($emails_other) > 0){
foreach ($emails_other as $email_other){
//var_dump($email_other['email_address']);
$mailOwner->addAddress($email_other['email_address']);
$body_other = "<p>Poštovani {$email_other['owner_name']}, <br>" . "Upravo ste primili poruku sa sajta <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Detalji Vaše poruke se nalaze ispod:</p><p><strong>Od: </strong>" . ucwords($fname) . "<br><strong>Telefon: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Poruka: </strong>" . $userMessage . "<br><br><strong>Napomena: </strong>Molimo Vas da na ovu poruku ne odgovarate. Vaš odgovor pošaljite na: " . strtoupper($userMail) . "</p>";
$mailOwner->Body = $body_other;
try {
$mailOwner->send();
$mailOwner = "INSERT INTO visitneum.contact_owner (fname, tel, userMail, userMessage, email_address_id) VALUES (:fname, :tel, :userMail, :userMessage, :email_address_id)";
$stmt = $pdo->prepare($mailOwner);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);
$rez['response']="success";
$rez['content']="Hvala Vam ".ucwords($fname)."! Vaša poruka je uspješno poslata vlasniku objekta {$email_other['owner_property']}! Odgovor ćete dobiti ubrzo!";
$jsonData[] = $rez;
}//end try mail send
catch (Exception $e) {
$rez['response'] = "error";
$rez['content'] = "Došlo je do greške! Pokušajte ponovo..." . $mailOwner->ErrorInfo;
$jsonData[] = $rez;
}
}//end foreach for email addresses (man owners of other properties(restaurants, ships etc.))
}//end if for array of emails
//echo str_replace("[]", "{}", json_encode($jsonData));
echo json_encode($jsonData);
//var_dump($jsonData);
And this is part of my JS file after submitHandler
submitHandler: function (form) {
//Your code for AJAX starts
var formData = jQuery("#contactOwner").serialize();
console.log(formData);
jQuery.ajax({
url: '/inc/Form_process.php',
type: 'post',
data: formData,
dataType: 'json',
//async: true,
cache: false,
success: function (rez) {
jQuery("#responseOwner").text(rez[0].content);
console.log(rez[0].response);
console.log(rez[0].content);
}, error: function (rez) {
jQuery("#responseOwner").text("An error occurred");
console.log(rez[1].response);
console.log(rez[1].content);
}
}); //Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} //submitHandler
I hope that somebody understand why json_encode return just empty array or empty object with JSON_FORCE_OBJECT, so thanks in advance for any kind of your help. Any help will be highly appreciated.
You really should include the actual JSON in your question; without it we are working blind, but I can guess what the problem is. You are not constructing your JSON properly when there are multiple records. When you have a single recipient, your JSON might look like this:
{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
That is fine, and perfectly valid JSON – and there is no issue having an empty string as a value. The problem arises when you have more than one record, when it will append them immediately after the first:
{"readyState":4,"responseText":"","status":200,"statusText":"OK"}{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
This is not valid JSON.
I suggest you accumulate your JSON responses inside the loop and then output them afterwards, in the correct format. Something like:
$jsonData = [];
foreach ($emails_room_f as $email_room_f){
//set your content in $data as you are now, then:
$jsonData[] = $data;
}
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($jsonData);
This way you will end up with data like this:
[
{"readyState":4,"responseText":"","status":200,"statusText":"OK"},
{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
]
Which is valid JSON. It will also work if there is no data as it will return an empty array, which is also valid JSON.
Separately from this, I am extremely suspicious of you having a utf8ize function – that is a sign you're doing other UTF-8 stuff wrong, but that's a subject for another question.
I'm working on a project where i can select an image (simple file select) and send it via JSON to a PHP MySQL insert page.
Upload page looks like this:
if (input.files && input.files[0]) {
var FR = new FileReader();
FR.onload = function(e) {
$('#img').attr("src", e.target.result);
var Naam = $('input[type=file]').val();
$('#base').text(e.target.result);
var Foto = e.target.result;
var Barcode = $('#barcode').val();
obj['Barcode'] = Barcode;
obj['Naam'] = Naam;
obj['Foto'] = Foto;
//execute ajax send
$.ajax({
url : 'insert.php',
type : 'POST',
data : obj,
dataType : 'json',
success : function(msg) {
alert("msg");
}
});
//$.post("insert.php", obj, function (data) {}, "json");
//alert("msg");
};
FR.readAsDataURL(input.files[0]);
and my PHP page:
$Barcode = $_POST["Barcode"];
$Naam = $_POST["Naam"];
$Name = preg_replace('/^.+[\\\\\\/]/', '', $Naam);
$Foto = base64_decode($_POST["Foto"]);
$query = "INSERT INTO voorraad_foto (barbody, location, foto) VALUES ('$Barcode','$Name','{$Foto}')";
$results = mysqli_query($db,$query);
And my table field is a BLOB.
But when it execute this, everything works fine except that it doesn't insert it as a blob, but pure string
I've tried with removing the
preg_replace('#data:image/[^;]+;base64,#', '', $Foto)
but doesn't make any difference, same when trying to add headers, but nothing..
What am i doing wrong, or is there something obvious that i'm not getting?
Thx.
I solved it in some kind of way:
I wrote a function that gets the Base64 string, decodes it and writes it to a Temp file.
Then i read that file again and upload that to my databse.
When success, delete the file.
It may not be the most effecient way, but it works!
function WriteToImageAndGetData($base64_string, $File) {
//Write to file
$ifp = fopen($File, "wb");
$data = explode(',', $base64_string); //Split Base64 string
fwrite($ifp, base64_decode($data[1])); //Decode Base64 string
fclose($ifp);
//Read from file
$fp = fopen($File, 'r');
$data = fread($fp, filesize($File)); //Read file contents
$data = addslashes($data);
fclose($fp);
return $data;
}
JQuery
function save() {
imageData = $(".sigPad").signaturePad().getSignatureImage();
consumeData = $('#consume').val();
$.ajax({
type: "POST",
url: "",
data: {'signatureasimage' : imageData, 'consume' : consumeData },
dataType: 'json',
cache: false,
success: function(response){
alert(response.msg);
/*var imageUrl = response['signature_image'];
d = new Date();
$(".signatureImage").attr("src",imageUrl);
if (response.status == true) {
window.location.href = "<?php echo ROOT_URL.'esignup/attendees_list.php?icode='.$icode;?>";
}*/
},
error: function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
};
PHP
$data = array();
$confirmationData = array();
$data['attendee_id'] = $attendeeId;
$data['is_consume_the_provided_meal'] = $_POST['consume'];
$data['signature_image'] = $destination;
$data['confirmed'] = 1;
if($confirmedAttendee){
$sql = "SELECT * FROM `".TBL_ATTENDEE_CONFIRMATION."` WHERE `attendee_id` = '.$attendeeId.'";
$confirmationData = selectFrom($sql);
update_array('tbl_attendee_confirmation', $data, array('attendee_id' => $attendeeId));
$confirmationData = selectFrom($sql);
}else{
var_dump("it went through insert array");
insert_array('tbl_attendee_confirmation', $data);
}
$data = array();
$data['msg']="Testing, testing.";
echo json_encode($data);
Jquery ajax does post request with data imageData and consumeData. imageData and consumeData are strings. Copying to file works and the data updates the table. The problem is I get parsererror when I want to get imageUrl so I can update the sigImage with the new image source. I commented the part where I replace the image src with new imageURL. Does anyone know the issue?
Error shows up as "alert('Error.\nParsing JSON Request failed.');" from code. Error still shows up with test code.
Try doing this in your PHP:
echo json_encode($data, JSON_FORCE_OBJECT);
I don't completely understand it, but in my experience if you are returning an array you've built in PHP to be parsed using the ECMAScript JSON object, you need to use the JSON_FORCE_OBJECT constant to ensure that it returns a JSON object instead of a JSON array.
json_encode constants
You also could try outputting the header for JSON before echoing your JSON encoded array, gimme a sec.
header('Content-Type: application/json');
Also here
I have the following code..
if (config.sendResultsURL !== null)
{
console.log("Send Results");
var collate =[];
for (r=0;r<userAnswers.length;r++)
{
collate.push('{"questionNumber'+parseInt(r+1)+ '"' + ': [{"UserAnswer":"'+userAnswers[r]+'", "actualAnswer":"'+answers[r]+'"}]}');
}
$.ajax({
type: 'POST',
url: config.sendResultsURL,
data: '[' + collate.join(",") + ']',
complete: function()
{
console.log("Results sent");
}
});
}
Using Firebug I get this from the console.
[{"questionNumber1": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber2": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber3": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber4": [{"UserAnswer":"3", "actualAnswer":"1"}]},{"questionNumber5": [{"UserAnswer":"3", "actualAnswer":"1"}]}]
From here the script sends data to emailData.php which reads...
$json = json_decode($_POST, TRUE);
$body = "$json";
$to = "myemail#email.com";
$email = 'Diesel John';
$subject = 'Results';
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// Send the email:
$sendMail = mail($to, $subject, $body, $headers);
Now I do get the email however it is blank.
My question is how do I pass the data to emailData.php and from there access it?
Create an object that you want to pass to PHP
Use JSON.stringify() to make a JSON string for that object.
Pass it to PHP script using POST or GET and with a name.
Depending on your request capture it from $_GET['name'] OR $_POST['name'].
Apply json_decode in php to get the JSON as native object.
In your case you can just pass userAnswers[r] and answers[r]. Array sequence are preserved.
In for loop use,
collate.push({"UserAnswer":userAnswers[r], "actualAnswer":answers[r]});
In ajax request use,
data: {"data" : JSON.stringify(collate)}
In the PHP end,
$json = json_decode($_POST['data'], TRUE); // the result will be an array.
json_decode converting string to object.
just do bellow code and check the values.
print_r($json)
Directly assign json object to string this is very bad.
If you decode your json, you will have a hash and not a string. If you want to be mailed the same as what you printed on the console, simply do this:
$body = $_POST['data'];
Another option would be to parse json into a php hash and var_dump that:
$json = json_decode($_POST['data'], TRUE);
$body = var_export($json, TRUE);
Using below JavaScript code
var collate =[], key, value;
for (r=0;r<userAnswers.length;r++) {
key = questionNumber + parseInt(r+1);
value = { "UserAnswer": userAnswers[r], "actualAnswer": answers[r] };
collate.push({ key : value });
}
$.post( config.sendResultsURL, { data: collate }, function(data) {
console.log("Results sent");
});
And do this in PHP
$data = json_decode( $_POST['data'], true );
and you will have all your data with array.
$jsonData = file_get_contents('php://input');
$json = json_decode($jsonData, 1);
mail('email', 'subject', print_r($json, 1));
i am stuck with this for quiet sometime now.
all i am trying to do is send a json text to php, process it and send a response bacl..
here is the data i am sending as my textarea value..
**asdasd #$**&**%^*( AAAA SADQWEASD /// '' \\\ '' l; "" **
below is the json sent to php (got it from console):
data={"Text":"asdasd #$&%^*( AAAA SADQWEASD /// '' \\\\\\ '' l; \"\" "}
i am using jquery ajax function as below:
function ajaxfunc(data, path){
$.ajax({
type: "POST",
url: path,
data: 'data='+data,
success: function(response){
}
});
}
in php, i am doing this.
$res = json_decode(stripslashes(escapeJsonString($_POST['feed'])), true);
function escapeJsonString($value) {
# list from www.json.org: (\b backspace, \f formfeed)
$search = array("\n", "\r", "\u", "\t", "\f", "\b", "/", '"');
$replace = array("\\n", "\\r", "\\u", "\\t", "\\f", "\\b", "\/", "\"");
$result = str_replace($search, $replace, $value);
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
echo $res["Text"];
issue is : & .. is not getting parsed at php and hence the response is null..
i also wanted to make sure, the new line characters are detected.. basically i am expecting "WYSIWYG" using json.. json_encode and json_decode
Based on the comment about just wanting to send form inputs to the server, use serialize() in the following way:
$.ajax({
type: "POST",
url: path,
data: $('form').serialize(),
success: function(response){
}
);
If all you want to do is access the form inputs on the server through the $_POST array then converting to JSON on the client is a waste of effort. serialize() should work perfectly for you.
But if you really want to use a JSON then use the JSON-js lib by Douglas Crockford here. Note that there is a lot of other info on this topic: Serializing to JSON in jQuery. Example below:
$.ajax({
type: "POST",
url: path,
data: 'data='+( JSON.stringify(data) ),
success: function(response){
}
);
if you want to send a data in JSON format, you can try this
data = {"Text":"asdasd #$&%^*( AAAA SADQWEASD /// '' \\\\\\ '' l; \"\" "};
data = JSON.stringify(data);
then send with your jquery.ajax or jquery.post