Send json from javascript to php - javascript

I have a page where users do some stuff and on selecting next, I want to redirect them to a php file, called "Step2.php" along with some JSON information.
I built my json string and it looks like this:
[{"name":"IMG_20130726_182336.jpg","size":2280709,"type":"image/jpeg","width":null,"height":null,"lastModified":1374852216000,"fileExtension":"jpg","orientation":1,"displayed":true,"attributes":[{"title":"Name: ","value":"IMG_20130726_182336.jpg"},{"title":"Date: ","value":"no date"}]}]
Now, I sent it trough jquery POST like this:
jsonData = JSON.stringify(serializableAttributes);
console.log(jsonData);
$.ajax({
type: 'POST',
url: 'Step2.php',
data: {"jsonData" : jsonData},
success: function(msg) {
console.log("Json Sent! " +msg);
window.location("")
},
error: function(request,msg){
console.log("Error : " + msg);
}
});
Question: Why I can`t receive anything in my Step2.php file? Am I wrongly redirect user to that page?
Code in the Step2.php files looks like this:
if(isset($_POST["jsonData"])) {
$json = $_POST["jsonData"];
var_dump(json_decode($json, true));
} else {
echo "NO";
}
It always shows NO.

Ok so I think you misunderstand how AJAX works. You ajax request sends the json to you php and should then respond to it with the appropriate return, in your case a var_dump.
This won't hold the json in the php at all and if you go and request the php file without the POST request you won't get anything else but the output "NO" as there is no POST data you are sending.
If you do want to send a json to you php you do what you are doing now and listen to the request responds which you can see in your inspector. I am not clear on what you ultimately want to do with the data so I don't know if this is the right way.

You can't do it like this. That's not how AJAX and POST work.
If you're simply going to Step2.php, try sending it to the page as part of the URL.
Instead of your AJAX function, simply do:
var jsonData = [YOUR DATA];
window.location.href="Step2.php?json="+jsonData
Or if PHP created the JSON string, you could store it as a SESSION variable.
EDIT: To venture a bit further on the SESSION variable route...
Have your AJAX script as it is now, but make a new PHP file. In this example we'll call it foo.php. Have your foo.php file setup like so:
session_start();
if($_POST){
if(isset($_POST['jsonData'])){
$json = $_POST['jsonData'];
$_SESSION['jsonData'] = $json;
//CREATE A JSON RESPONSE INIDCATING SUCCESS
echo '{ "success" : 1 }';
}
}
Your SUCCESS function of the AJAX call could analyze the response for the success code. If it's "1" redirect to the Step2.php page.
Just make sure that you're calling session_start() at the top of each page.

You can post JSON to PHP
jsonData = JSON.stringify(serializableAttributes);
console.log(jsonData);
$.post("Step2.php", { json: jsonData }, function(msg) {
console.log("image name = " + msg);
});
PHP, you simply parse:
if(isset($_POST['json'])){
$json = $_POST['json'];
$data = json_decode($json);
$image = $data[0];
echo $image->name;
$atributes = $image->attributes;
foreach($atributes as $atrribute){
//echo 'title '.$atribute->title;
}
}

Try this code in my work:
<?php
if(isset($_POST["jsonData"])) {
$json = $_POST["jsonData"];
$json = str_replace('\\', '', $json);
var_dump(json_decode($json, true));
print_r($json);
} else {
echo "NO";
}
?>

Related

Try to use the getJSON function but it's not returning anything

This is my getJSON:
$(function () {
var neededData;
$.getJSON('/ajax/connected-devices-data.php', function(jsonData) {
neededData = jsonData;
console.log(neededData);
});
});
And this is my php:
use NET2GRID\Data\CurrentlyConnectedDevices;
require_once __DIR__ . "/../vendor/autoload.php";
header('Content-type: application/json; charset=utf-8');
$cd = new CurrentlyConnectedDevices();
$data = $cd->getConnectedDevicesFromDatabase();
print json_encode($data);
When I look at my site where I run this the console remains empty but according to what I'm used to there should be a json object there.
This is the jsonresponse I get from the php code when I run it individually:
{"SUCCESS":[[1493642582000,912],[1493718591000,909]],"PING_NOT_RECEIVED":[[1493642582000,631],[1493718591000,635]],"TCP_CNX_FAILED":[[1493642582000,7],[1493718591000,7]]}
What am I doing wrong in this code?
Try following AJAX code..
$.ajax({
method: "GET",
url: "/ajax/connected-devices-data.php"
}).done(function( response ) {
alert( "Response received: " + response );
});
--- UPDATE ---
Above code was not the solution of the question asked. It was the error on the web server which has not configured properly with PHP.

Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);

Save to server side file from PHP via Javascript

I am trying to save a json string from a javascript file to a local file on the server using PHP, however, my json file is not being modified at all.
Here is my Javascript:
function saveToFile(data){
jsonString = JSON.stringify(data);
$.ajax({
url: 'php/save.php',
data : jsonString,
type: 'POST'
});
}
Note that jsonString is a valid variable, and i can log it correctly into the console.
Here is my PHP:
<?php
$data = $_POST['jsonString'];
$f = fopen("../website-contents.json", "w") or die("fopen failed");
fwrite($f, $data) or die("fwrite failed");
fclose($f);
?>
Note that even tests trying to save "Hello World" to "test.txt" don't work, or through errors.
Finally, here is my folder structure:
Here is your solution.
Js code
function saveToFile(data){
jsonString = JSON.stringify(data);
$.ajax({
url: 'php/save.php',
data : {'jsonString':jsonString},
type: 'POST'
});
}
php code.
$data = $_POST['jsonString'];
//set mode of file to writable.
chmod("../website-contents.json",0777);
$f = fopen("../website-contents.json", "w+") or die("fopen failed");
fwrite($f, $data);
fclose($f);
I agree with the comments pointing out you must have a permission problem. However, it will not work after you have corrected this problem either. You have
$data = $_POST['jsonString'];
but where do you set a key called jsonString? Use
function saveToFile(data){
var jsonString = JSON.stringify(data);
$.post("php/save.php", {
jsonString: jsonString
})
}
instead.

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

Passing session variable through AJAX to PHP file

My goal is to pass $userId variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users.
Im having a bit of trouble getting the variable data to go to the ajax statement. What am i doing wrong?
<?php
session_start();
if(isset($_SESSION['userid'])) {
$userId = mysql_real_escape_string($_SESSION['userid']);
echo $userId;
echo ' (irrelevant code)...
//button that loads form via ajax...
Add URL
(irrelevant code)... ';
}
AJAX code:
function showAdd(str) {
$('#response').html('Processing Request. Please wait a moment...');
var userId = str;
alert (userId);
$.ajax({
type: "POST",
url: "addUrlForm.php",
data: "userId=" + str,
success: function(msg) {
$('#response').empty();
$('#content01').html(msg).show();
},
error: function () {
alert('error');
}
});
};
EDIT: I took your suggestion (thank-you) and it some-what helped. Now the alert is returning "$userId" variable as a string. How do I make it be recognised as a variable containing the session data, not as a string? I tried "showAdd($userId)" but console is telling me $userId is not defined?.
Since you're sending the userId as a parameter to the showAdd() function you should change your code to:
function showAdd(str) {
var userId = str;
// ...
}
or simply rename the parameter to userId:
function showAdd(userId) {
// use userId here
]
To make you above code send the correct userId and not the string $userId to the function you should wrap your output string in double quotes or output it directly:
echo 'Add URL';
or:
echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";
I do not understand why would you use $(this) when the userid is already present and is passed as function parameter.
Change this:
var userId = $(this).attr('userId');
To:
var userId = str;

Categories