How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.
JavaScript code:
$.ajax({
method:"POST",
url:'php.php',
data:"",
dataType:'json',
success:function(data){
var y1=data;
console.log(data.name);
}
});
PHP code:
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//assign vars after formatting to avoid a wrong login with correct
//username and password
$username = trim($_POST["user"]);
$customer_array = array();
$customer1 = array(
'name' => '3',
'city' => 'Houston'
);
$customer_array[] = $customer1;
$customer2 = array(
'name' => '2',
'city' => 'Boston'
);
$customer_array[] = $customer2;
$customer3 = array(
'name' => "1",
'city' => "Bossier City"
);
echo json_encode($customer_array);
}
I am just going to summarize my comments into an answer, first I would just turn off the json return for trouble shooting. You can parse the json after fact anyway:
$.ajax({
// Do "type" here
type:"POST",
url:'php.php',
// Send something to check in the script
// This is optional, but I like to do it...
data: {
"action":"get_name_city"
},
success:function(data){
// Do a try, just incase your parse fails
try {
// Parse the json here
var getJson = JSON.parse(data);
console.log(getJson);
console.log(data);
}
catch(Exception) {
// Show any errors that might get thrown
console.log(Exception.message);
}
}
});
PHP:
# Check the action is set and is named
if(isset($_POST["action"]) && $_POST["action"] == "get_name_city") {
$username = trim($_POST["user"]);
$customer_array = array();
$customer1 = array(
'name' => '3',
'city' => 'Houston'
);
$customer2 = array(
'name' => '2',
'city' => 'Boston'
);
$customer3 = array(
'name' => "1",
'city' => "Bossier City"
);
$customer_array[] = $customer1;
$customer_array[] = $customer2;
$customer_array[] = $customer3;
# Just die here
die(json_encode($customer_array));
}
# Die with error so there is some feedback to your ajax
die(json_encode(array('error'=>'No data was sent.')));
As has been mentioned, there are multiple options for passing the data from PHP:
add the Content-Type header with value application/json before sending the return from json_encode() to echo():
header('Content-Type: application/json');
echo json_encode($customer_array);
Parse the return from the PHP using JSON.parse()
success:function(data){
var y1=data;
var data = JSON.parse(data);
So pick one of those approaches. One might argue that the first is more semantically correct, since JSON data is being sent.
Additionally, the success callback of the AJAX request is attempting to access the property name of the data returned. However, the data returned should be an array of objects, each which has a property name. One approach to logging the name of each property is to use Array.forEach() and send the name of each element in the array to console.log().
data.forEach(function(dataItem) {
console.log(dataItem.name);
});
See a demonstration of this in this phpfiddle.
You where almost there. Your AJAX requests accepts JSON but your PHP does not output JSON (it does but not in the correct way), you'll have to set the appropriate Content-Type header:
header('Content-Type: application/json');
echo json_encode($customer_array);
Your AJAX request should now be able to use the properly formatted JSON as the data variable (and console.log it).
Related
I have some PHP and JavaScript that works by PHP updating a MySQL database, and then outputting the updated code back onto the page without a hard refresh using the JavaScript fetch() method. This code works, but there is a part I don't understand — why is it when the json_encode() PHP method is used, which converts the data to a JSON string, when it is then used in the JavaScript it is automatically being converted into a JavaScript object without JSON.parse() being used?
In the Javascript when I use JSON.parse() it understandly throws an error, because the data isn't a string (which initially caused some confusion), when I console log the json variable being used in the JavaScript it does indeed return a JavaScript object where I can access its properties and methods etc.
There is no other JSON or json_encode() being used on the page (or indeed the site).
Also in the PHP script it echoes the JSON with echo json_encode($board_row); when the data is fetched from the database, before any HTML content is outputted. When I try and echo this in the HTML to see the value of json_encode($board_row); it just outputs the word false. I don't understand what is going on there either?
If I manually add a simply array into the HTML such as $arr = array('a' => 1, 'b' => "hello", 'c' => null); and then echo that in the HTML with echo json_encode($arr); as excepted it outputs a JSON string.
If someone could kindly explain why this is happening, that would be wonderful.
PHP
if (isset($_POST['submit-board-name'])) {
$create_board_name = $_POST['create-board-name'];
try {
// insert into database
$createBoardSQL = "
INSERT INTO boards (board_name, user_id)
VALUES (:board_name, :user_id )
";
$bstmt = $connection->prepare($createBoardSQL);
$bstmt->execute([
':board_name' => $create_board_name,
':user_id' => $db_id
]);
// ----- fetch as JSON
if(isset($_POST['json_response'])) {
$board_stmt = $connection->prepare("
SELECT * FROM `boards` WHERE `user_id` = :user_id
AND `board_name` = :board_name
ORDER BY `board_id` DESC");
$board_stmt -> execute([
':user_id' => $db_id,
':board_name' => $create_board_name
]);
$board_row = $board_stmt->fetch();
header('Content-type: application/json');
echo json_encode($board_row);
exit;
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
JavaScript
let boardModuleForm = document.querySelector('.board-module-form');
// URL details
let myURL = new URL(window.location.href),
pagePath = myURL.pathname;
if (boardModuleForm) {
boardModuleForm.addEventListener('submit', function (e) {
if (e.submitter && e.submitter.classList.contains('js-fetch-button')) {
e.preventDefault();
var formData = new FormData(this);
formData.set(e.submitter.name, e.submitter.value);
formData.set('json_response', 'yes');
fetch (pagePath, {
method: 'post',
body: formData
})
.then(function(response) {
if (response.status === 200) {
response.json().then(function(json){
const newBoardName = json.board_name,
boardId = json.board_id;
const newButton = `
<button name="board-name" type="submit">
<span>${newBoardName}</span>
<span style="margin:0" class="add-icon flex">+</span>
</button>
<input class="board-id-value" type="hidden" value="${boardId}">
`
// add new button from above onto page
document.querySelector('.board-list').insertAdjacentHTML('afterbegin', newButton);
});
}
})
.catch(function(error) {
console.error(error);
})
}
})
}
In the handler for your fetch response, you call response.json().then(...). This is already doing the JSON parsing for you without needing to call JSON.parse manually.
So i have this code that posts to a php file,
var values = {
'socketid': data.socketid,
'id': memberid.value
};
console.log(values);
$.ajax({
url: "continue.php",
type: "POST",
data: values,
});
but i am unsure how to get each seperate value from the php file continue.php, do i ruse $_REQUEST or something, im just not sure if i have to parse or anything, could i get an example on how i can do this
Since you are using POST method just:
$socketid = $_POST['socketid'];
$id = $_POST['id'];
$_REQUEST is to check both $_GET and $_POST at the same time but it is not necessay in your code
$_POST should work fine since your request is of type POST
Your continue.php will get values in the following way:
<?php
$socket_id=$_POST['socketid'];
id=$_POST['id'];
?>
For simple post use $.post() it's a shorthand for $.ajax() for POST request.
var values = {
'socketid': data.socketid,
'id': memberid.value
};
$.post('continue.php', values, function (response) {
var res = JSON.parse(response);
if (res.results == true) {
console.log('Data updated');
}else {
console.log('Data not updated');
}
})
In your PHP
<?php
$socket_id = $_POST['socketid'];
$id = $_POST['id'];
// here update your data/ use
// then send response to javascript
// echo json_encode(['results' => true]); for success
// echo json_encode(['results' => true]); for fail
This is response of ajax
Array
(
[0] => Array
(
[name] => Shoaib
[description] => Shoaib is a frontend developer
)
[1] => Array
(
[name] => jawad
[description] => jawad is a teacher
)
)
above shown in console.log() how can handle in javascript
To use the response ( multi-dimensional array ) from your php script in javascript you would use json_encode
$arr=array();
$arr[]=array('name'=>'shaoaib');
$json=json_encode( $arr );
header('Content-Type: application/json' );
echo $json;
RamRaider has provided php end
so I will just focus on jquery part.
Your ajax part should be something like this
$.post(url, function(retObj){
var data = JSON.parse(retObj);
$.each(data, function(idx, val){
console.log(val.name, val.description)
})
})
You have to use the function json_encode() this is just like a translator for the client about wha a answer is receiving from the server. The opossite is json_decode() to send information from client to server.
Like this is how works:
I sent to the server a data object using ajax
$.ajax({
url : "ajax.php",
type : "POST",
dataType : "json",
data : {"name" : "abipositas", "arr" : { "1" : "one", "2" : "two" } },
success : function(data) {
alert(data["id_2"][2]);
alert(data["id_3"]);
alert(data["id_4"]);
},
});
In the success of the ajax I just take the answer already interpreted from the server. And like this should be your server side:
<?php
if( $_POST ) {
$arr['id_1'] = 'herbert';
$arr['id_2'] = array( 0, 1, 7, 3 );
$arr['id_3'] = $_POST['name'];
$arr['id_4'] = $_POST['arr']['1'];
echo json_encode($arr);
}
Because I sent a object using $_POST I can ask if the $_POST information arrive correct. I don't care which specifically I ask for the package ($_POST) in general. Is like if you received a package by your post and you are not at home, then you go to pick up in the next post office, you don't ask for the shoes in the package, you ask for your package. At home you open and use from the content what you need. Then you translate this message and send a answer back to the person that send you this package (the client using json_encode())
I'm picking errors from php file using ajax and i face few troubles. Like in php file i take errors into $email_error and $password_error so i want to return error reports to ajax and assign $email_error to id = "email_errors" and $password_error to id = "password_errors". Maybe someone could explain how i specify what variables i want to return and what id should it take .I will leave some commented code below. Thanks!
php
<?php
if (isset($_POST['email']) && isset($_POST['password1']) && isset($_POST['password2'])) {
$email = trim ($_POST['email']);
$password1 = trim ($_POST['password1']);
$password2 = trim ($_POST['password2']);
}
$email_error = 'No errors<br>';
$password_error = 'No errors<br>';
if (empty($email))
$email_error = ('Pleas fill in email field<br>');
if ($email == 'example')
$email_error =('There already is user with this email<br>');
if (empty($password1))
$password_error = ('Please fill in password fields<br>');
if (empty($password2))
$password_error = ('Please fill in password fields<br>');
$email_error; //this variable must be returned to ajax and assigned to id "email_errors"
$password_error; //this variable must be returned to ajax and assigned to id "password_errors"
?>
javascript
$(document).ready(function () {
$('#push_button').click(function() {
$.post('php.php',
{
email : $('#email').val(), // i take these variables to php
password1 : $('#password1').val(),
password1 : $('#password2').val()
} ,
function ( data ) { //what do i return here?
$('#email_errors').val(data); //how to assign $emaill_error to #email_errors
$('#password_errors').val(data); //how to assign $password_error to #password_errors
}
)
})
})
to return value simply echo the variable with json_encode()
e.g.
$return_array = new array();
$return_array['email_error'] = $email_error;
$return_array['password_errors'] = $password_errors;
echo json_encode($return_array);
in the javascript function (data){}:
function ( data ) { //what do i return here?
$('#email_errors').val(data['email_error']); //how to assign $emaill_error to #email_errors
$('#password_errors').val(data['password_errors']); //how to assign $password_error to #password_errors
}
If you want to return several variables to ajax, you would have to return some json
PHP :
// .. your php code
$ret = array("email_error" => $email_error, "password_error" => $password_error);
echo json_encode($ret);
Be careful, json_encode needs PHP >= 5.2
JS :
$.ajax({
url: "php.php",
type: "POST",
dataType: "json", // The type of data that you're expecting back from the server
data: {
email: $("#email").val(),
password1: $("#password1").val(),
password2: $("#password2").val() // careful, you had "password1" as variable name 2 times
},
success: function(obj) {
// obj is your php array, transformed into a js object
// you may want to use .html() instead of .val() since your errors are strings with html tags - depends if #email_errors / #password_errors are inputs or divs
$("#email_errors").html(obj.email_error);
$("#password_errors").html(obj.password_error);
}
});
In PHP, the following will return nothing:
$email_error;
$password_error;
Your not echo'ing the values or anything. If you want to pass two different values, I'd return a JSON object like so (in PHP):
echo json_encode(array(
'email_error' => $email_error,
'password_error' => $password_error
));
And then in JavaScript, your data should now be a JavaScript object, as jQuery should parse the JSON object and understand it as an object. So you'll be able to do like this in JavaScript:
$('#email_errors').val(data.email_error);
$('#password_errors').val(data.password_error);
If you don't want to use an array, you could create a new object and then pass that object to json_encode.
$obj = new stdClass;
$obj->email_error = $email_error;
$obj->password_error = $password_error;
echo json_encode($obj);
I am using an ajax post to submit data for validation and storing in a database. If the data fails server-side validation error messages are then json encoded and sent back like this:
$errorArray = array();
if (!empty($nameErr)) {
$errorArray["nameErr"] = $nameErr;
}
if (!empty($emailErr)) {
$errorArray["emailErr"] = $emailErr;
}
if (!empty($phoneErr)) {
$errorArray["phoneErr"] = $phoneErr;
}
if (!empty($commentErr)) {
$errorArray["commentErr"] = $commentErr;
}
$data = json_encode($errorArray);
echo $data;
Then in the success callback of my ajax post I will displayt these errors, my question is how do I access these messages that are sent in the json encode function?
I have tried
error.response['nameErr']
and
error.response('errorArray["nameErr"])
but neither seem to work?
I think what you want is to have a header declaration in your PHP so that returning text is read as json.
In this case, you also need to set your ajax data type as json so it is prepared to receive json.
The success function of your ajax request simply does an if statement and if data.Error is false, you've got a problem and you can go ahead and read the data.ErrorMessage you yourself have recorded server side.
JavaScript:
var requestObject = { Property1 = "Hi" };
$.ajax({
url: myUrl,
method: "post",
data: requestObject,
dataType: "json",
success: function( data )
{
if( data.Error )
{
HandleError( data.ErrorMessage );
}
else
{
// Do stuff with data.Response
}
}
error: function( e )
{
alert( JSON.stringify( e ) ); // This usually relates to server side errors, 404 not founds etc... so this function will not magically know that your validation failed... Although you could perhaps throw a PHP fatal error...
}
});
PHP:
if( $_POST[ "Property1" ] != "sausage" )
{
header('Content-Type: application/json'); // This line will make your ajax be okay with the json response
$response = array(
"Error" => TRUE,
"ErrorMessage" => array( "Hey that doesn't equal sausage" ),
"Response" => false
);
echo json_encode( $response );
}
In your case, have an array of errors and fill them up as bits are not correctly passed... for example:
$errors = array();
if( /* condition */ )
$errors[] = "Error message 1";
if( /* condition */ )
$errors[] = "Error message 2";
if( count( $errors ) > 0 )
$response = array(
"Error" => TRUE,
"ErrorMessage" => $errors,
"Response" => false // Nothing to send back because there were errors
);
echo json_encode( $response );
P.S
If you're having issues getting the error messages or response you desire. Don't forget to check out the network tab in your favourite Developer Toolbar... Mines IE11 so here's an example of that:
I think, you mean to parse json in javascript.
For that you need to do:
JSON.parse('json');
Or
If you are using jquery, you can also do:
$.parseJSON('json');
Both will return you objects parsed from JSON.
This is a simple json all:
$.getJSON("serverpage.php", { form_data })
.done(function (data) {
console.log(data);
});
})
.fail(function (jqxhr, textStatus, error) {
console.log(error);
});