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);
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.
I was wondering if you could help. I am attempting to pass a variable to a PHP file, then run a SQL query, using that variable, then pass back the result as a variable to the javascript. Currently, I have successfully received the PHP back to the javascript using Ajax, but not able to sending the ServiceName to the PHP File. It is essential that the files stay separate. Also just to clarify I have replaced certain sections for privacy, however, they are correct and working in the code. I have also used a $_GET method already, however, I could only get the javascript to access a new window and not return the PHP variable.
My current code is as follows:
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
// Declare the value of the new Service name and save it in the variable A.
a = sender.getValue();
{
// if it equals a new variable.
if (sender.getValue() == a) {
// Place it within the URL, in order for it to be processed in the php code.
window.location.href = "http://IP/development/Query01.php?service=" + a;
// Attempted code
// echo jason_encode(a);
// $.ajax({var service = a;
// $.post('http://IP/development/Query01.php', {variable: service});
// }
//use AJAX to retrieve the results, this does work if the service name is hard coded into the PHP.
$.ajax({
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data) { // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
}
}
}
<?php
$serverName = "SeverIP"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"DatabaseName", "UID"=>"Username", "PWD"=>"Password
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$service = $_GET['service'];
if ($conn)
{
//echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = ("SELECT DefaultContact2 FROM tblServices WHERE ServiceName = '$service'");
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$dC2 = $row['DefaultContact2'];
}
echo json_encode ($dC2);
sqlsrv_free_stmt( $stmt);
?>
Any help would be greatly appreciated.
You could send data using your Ajax request like so.
$.ajax({
url: "http://IP/development/Query01.php",
method: "POST" // send as POST, you could also use GET or PUT,
data: { name: "John", location: "Boston" }
dataType: "json",
success: function(data) {
editors['Contact2'].setValue(data);
}
});
Then in PHP access the sent data:
<?php
print_r($_POST);
/*
[
"name" => "John",
"location" => "Boston"
]
*/
?>
You cannot pass the javascript's variable to php on same page.
You can do this with ajax call with POST or GET method, and then you can send the manipulated data back to you browser and store it in your javascript's object or variable.
You can do it in a single Ajax call.
Remove from your code this line:
window.location.href = "http://IP/development/Query01.php?service=" + a;
And modify a bit the Ajax call
$.ajax({
type: 'GET'
data : {
service: sender.getValue();
},
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
I put the same variable name for the Get in the Ajax call. But I don't know if your query01.php should accept to do now both actions in the same call.
Thank you guys for your help. Just thought it would be useful, if I posted of what I went with in the end, regardless of whether it is the right way, it certainly done the job.
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
{
// Variable Declaration
serviceName = sender.getValue();
{
// Use JQuery.Ajax to send a variable to the php file, and return the result.
$.ajax({
// Access the PHP file and save the serviceName variable in the URL, to allow the $_GET..
// method to access the javascript variable to apply it within the SQL Query.
url: "http://ServerName/development/DefaultContact1.php?service=" + serviceName,
// retrieve the result, using json.
dataType: "json", // the return type data is jsonn
success: function(data)// <--- (data) is in json format
{
// pre-fill the contact1 field with the result of the PHP file.
editors['Contact1'].setValue(data);
}
// End of Ajax Query
});
// End of function to prefill Contact1 field.
Thank again for your responses!
I want to send JS variables using Ajax, to a PHP page so that I could save those variable in the Database. However, it isn't working as I expected.
My JS code:
var a= payment;
var b= count_days;
var c= <?php echo $teacher_id; ?>;
var jsonString1 = JSON.stringify(a);
var jsonString2= JSON.stringify(b);
var jsonString3= JSON.stringify(c);
$.ajax({
type: "POST",
url: "student_searching_availibility.php",
data: {
data1 : jsonString1,
data2:jsonString2,
data3:jsonString3
},
cache: false,
success: function() {
alert('success');
}
});
Now my PHP
$data1 = json_decode($_POST['data1']);
$data2 = json_decode($_POST['data2']);
$data3 = json_decode($_POST['data3']);
include "db.php";
$sql2= "INSERT INTO availibility_status_date(student_id,teacher_id,status) VALUES ('$data1','$data2','$data3')";
if(!mysqli_query($con,$sql2)){
die("error". mysqli_connect_error());
}
I have searched almost all such queries here but still could not solve the problem.
JSON is javascrip object notation you cannot JSON.stringify a variable, it has to be an object. Try this.
var data = {}; //defines that data is a javascript object
//assign your values to there respective indexes
data['a'] = payment;
data['b'] = count_days;
data['c'] = <?php echo $teahcer_id; ?>
//since data is now a object you can json.stringify it
var jsonData = JSON.stringify(data);
//make ajax request with json data
$.ajax({
type: "POST",
url: "student_searching_availibility.php",
data: { data:jsonData },
cache: false,
success: function()
{
alert('success');
}
});
On your PHP, remember that json_decode() expects second parameter the $assoc parameter as a boolean, its default is false which means that if you only specity the json string to be decoded then it will return you data in an object form, for associative array pass true as second parameter.
$data = json_decode($_POST['data']); //$data is now an object
$data->a; //your payment
$data->b; //your count_days
$data = json_decode($_POST['data'],true); //$data is now an associative array
$data[a]; //your payment
$data[c]; //your count_days
when you were inserting into sql $data1, $data2 you were actually trying to store objects into your table, here mysqli_query should have returned false and your code died thus you are not getting any error.
So your sql insert values depending upon your json_decode($_POST['data'], true or false) use either $data->a or $data[a] i.e,
"INSERT INTO availibility_status_date(student_id,teacher_id,status) VALUES ('$data[a]','$data[b]','$data[c]')";
OR
"INSERT INTO availibility_status_date(student_id,teacher_id,status) VALUES ('$data->a','$data->b','$data->c')";
I'm kinda lost in how to fix a problem of mine. I've got a little code on PHP that's passing data(errors, page(id, name, title etc) trough an array and that array has been set with parseJSON. If I alert the response I will get an array with the correct value. But my problem is, that the response is always different hence it are PHP variables that change.
I've tried something like responseText.pageid or responseText.error[1], but that can't work because it can be different. And I don't know if I need to call it responseText.pageid because in the array it's $pageid or something different...
So alerting responseText is giving me a good result, but separating it won't unfortunately work.
My JS code:
// Variables
var content_page = $('#content-page').val();
var content_url = 'action=chose&page='+content_page;
/* Starting AJAX post form */
$.ajax({
type: 'POST',
dataType: "JSON",
url: 'handlers/content.handler.php',
data: content_url,
success: function(responseText)
{
var obj = $.parseJSON(responseText);
console.dir(obj.error);
if(obj.error[1] > -1)
{
noty({ text: 'U hebt geen pagina gekozen!' });
}
else if(obj.error[2] > -1)
{
noty({ text: 'De gekozen pagina bestaat niet!' });
}
else if(obj.error[100] > -1)
{
noty({ text: 'Uw pagina wordt opgehaald...' });
}
}
});
return false;
});
My PHP code:
// Storing the variables.
$stringPage = trim($_POST['page']);
$error = array();
$bolean = false;
// Prepared statement.
$stmt = $mysqli->prepare('SELECT id,name,title,text FROM pages WHERE name = ?');
$stmt->bind_param('s', $stringPage);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($pageID, $pageName, $pageTitle, $pageText);
$stmt->fetch();
$intPage = $stmt->num_rows();
$stmt->close();
# Controle
if(empty($stringPage))
{
$error[] = 1;
$bolean = false;
}
if($intPage == 0)
{
$error[] = 2;
$bolean = true;
}
if($bolean == false)
{
$error[] = 100;
}
header('Content-Type: application/json');
$aVariables = array('error' => $error, 'id' => $pageID, 'name' => $pageName, 'title' => $pageTitle, 'text' => $pageText);
echo json_encode($aVariables, JSON_FORCE_OBJECT);
I've Googled and came to the conclusion that I need to make a variable out of the parseJSON but then I get no result unfortunately. My current result(http://prntscr.com/72c39h) is working but separating it with responseText.home isn't working.
Thank you in advance, and my apologies for the bad grammar and language!
There is no need to var obj = $.parseJSON(responseText);, this responseText is already in json format. If you want to access error then just refer it by simply responseText.error or 'alert(responseText.error);' and there is also no need to set header('Content-Type: application/json');
When calling JQuery's parseJSON() you have to both call it properly, e.g. $.parseJSON(), and store it in a variable, e.g. var obj = $.parseJSON(responseText);, as per the documentation.
I have a JS script of:
function addTasteingNote(userID,beerID)
{
//get values
var note = $('#note1').val();
var ajaxSettings = {
type: "POST",
url: "a.php",
data: "u="+userID+"&b="+beerID+"&n="+note,
success: function(data){
} ,
error: function(xhr, status, error) { alert("error: " + error); }
};
$.ajax(ajaxSettings);
return false;
}
and the php script to add to the db is:
<?php
error_log("starting code");
require_once('connect.inc.php');
$u = $_GET['uID'];
$b = $_GET['bID'];
$n = $_GET['n'];
//do some checks etc
$db = new myConnectDB();
error_log("Successfully created DB");
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ($u, '$b', '$n')";
error_log($query3);
$result = $db->query($query3);
?>
The problem is that the error log shows nothing being put into the query:
[01-Nov-2013 23:40:29] Successfully created DB
[01-Nov-2013 23:40:29] INSERT INTO x (userID,beerID,note) VALUES (, '', '')
I have put alerts in the success of the ajax call, so I know that values are being passed through...
You need to give data like
var ajaxSettings = {
type: "POST",
url: "a.php",
data: {u:userID,b:beerID,n:note},
success: function(data){
}
data wont be and Query string,And since you are posting the values through ajax you need to get them via POST only like
$u = $_POST['u'];
$b = $_POST['b'];
$n = $_POST['n'];
And your query should be like
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ('".$u."', '".$b."', '".$n."')";
And Better to use escape strings with your POST variables to prevent from SQL injection.
You are using post method so, you need to get data using $_POST or $_REQUEST instead of $_GET
$u = $_REQUEST['u'];
$b = $_REQUEST['b'];
$n = $_REQUEST['n'];