Passing Javascript Variable to PHP File - javascript

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!

Related

Pass data from jQuery Ajax to PHP and saving those values in Database

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')";

PHP script not getting called from ajax function

this is a noob question.
my javascript function(part of knockout.js model that I have defined):
self.loadData = function(){
alert("loadData got called");
$.ajax({
url: 'database_connection.php',
dataType: 'json',
success: function(data){ //json string of records returned from server
alert('success from server call');
},
error: function(){
alert('error from server call');
}
});
};
Contents of database_connection.php:
<?php
echo "this is called";
$db = new MySqli('localhost', 'username', 'password', 'database');
$activities = $db->query("SELECT * FROM MainActivity");
$activities_r = array();
while($row = $activities->fetch_array()){
$val = $row['mActivityID'];
$act = $row['Name'];
$activities_r[] = array('val'=>$val, 'act' => $act);
}
echo json_encode($activities_r);
?>
The php is correct, coz if I directly access this file through browser, it correctly displays the result from database table.
However, when executed through the loadData function, I get two alerts:
1. "loadData is called"
2. "error from server call"
the first line of database_connection.php is not being executed since I cant see the result of echo, so that means the script is not getting called.
Am I using the ajax function wrongly?
Your AJAX request contains:
dataType: "json"
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function
Use the following code to ensure the reponse is JSON format.. (PHP vsersion)
header('Content-Type: application/json');
Note : empty response is also considered invalid JSON; you could return {} or null which validate as JSON
you need to add headers in php file, because your data type is json in ajax call.
header('Content-Type: application/json');
echo json_encode($activities_r);
You need to set the type of your request and may be remove dataType. Also in the success callback it was one extra bracket. Check it :
self.loadData = function(){
alert("loadData got called");
$.ajax({
url: 'database_connection.php',
type : 'GET',
// dataType: 'json',
sucess: function(data){ //json string of records returned from server
alert('success from server call');
},
error: function(){
alert('error from server call');
}
});
};

Pass variable from Javascript to PHP using AJAX

I'm trying to pass in variables from a Javascript file to a PHP file.
From my js file:
dataQuery = {
range: [[range.lower, range.upper]],
detail: { id: detail.id }
};
$.ajax({
type: "POST",
async: true,
url: scope.fetchUrl,
data: { query: dataQuery }
})
.done(function( data ) {
alert("success!");
}
In my php file I have session variables because I need to do oauth authentication.
if (isset($_SESSION['accessToken']))
{
$companyId = "1234";
$rollupFreq = "1H";
$oauth->setToken(
$_SESSION['accessToken'],
$_SESSION['accessTokenSecret']);
$apiUrl = ($apiBaseUrl
. '&company_id=' . urlencode($companyId)
. '&rollup_frequency=' . urlencode($rollupFreq)
. '&start_datetime_utc=' . urlencode($range['lower'])
. '&end_datetime_utc=' . urlencode($range['upper'])
);
try
{
header('Content-Type: application/json');
$data = $oauth->fetch($apiUrl);
$responseInfo = $oauth->getLastResponse();
print_r($responseInfo);
if (isset($_GET['query']))
{
$range = $_GET['query'];
print_r($range);
}
}
}
Nothing appears when I try to print $range, and when I try to use values from $range in the url I get "Undefined variable: range in url"
Any help would be appreciated!
You're creating an AJAX request using POST:
$.ajax({
type: "POST",
//...
});
Yet in your PHP code, you use the $_GET variable:
$range = $_GET['query'];
Change $_GET to $_POST.
You're also using the $range variable (in urlencode($range['upper']) for example), but there's no code anywhere that actually declares, let alone initializes it. That's the cause of the "Undefined variable" notices you're seeing
Lastly, the data you're sending to PHP will look something like this:
$_POST['query']['range'] = array(
array(range.lower, range.upper)//whatever these values may be
);
So to get at the range.lower value, you'd have to write:
$_POST['query']['range'][0][0];
//for the upper:
$_POST['query']['range'][0][1];
That's just messy. see the docs: jQuery will correctly format your data for you, regardless of what you pass to $.ajax. I'd suggest the following:
dataQuery = {
range: {lower: range.lower, upper: range.upper},
detail: { id: detail.id }
};
$.ajax({
type: "POST",
//async: true, <== you can leave this out
url: scope.fetchUrl,
data: dataQuery
}).done(function( data ) {
alert("success!");
});
Then, in PHP, you can get at the values a bit more intuitively:
$upper = $_POST['range']['upper'];
//to get a range array:
$rage = range(
(int) $_POST['range']['lower'],//these values are strings so cast
(int) $_POST['range']['upper'] //to ints to get a numeric range
);
$detailId = $_POST['detail']['id'];

Best practice when changing PHP Data to JS Data via AJAX (especially arrays)

(Secondary title): ajax array recieved as json encoded PHP array not behaving as javascript array
For some reason, my PHP array gets sent over to JavaScript just fine, but when I try to access an individual key of the array, it doesn't return anything, or it returns some other value which doesn't correspond. I am of course using json_encode() in the corresponding PHP file (echoClientData.php):
$id = $_GET['selected_id'];
$id = str_replace("clientSel","",$id);
$getclientinfo = "SELECT * FROM `clients` WHERE `ClientID` = $id";
if ($result = $Database->query($getclientinfo))
{
$row = $result->fetch_row();
$output = $row;
}
echo json_encode($output);
This code works fine:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data;
$('#client-detail-box').html(test);
}
});
And returns an array into the #client-detail-box div, e.g.
["1566","","Adrian","Tiggert","","","","","","","","","","","","0000-00-00","0000-00-00","0.00","","0","","","102","Dimitri Papazov","2006-02-24","102","Dimitri Papazov","2006-02-24","1","0","0"]
However, when I do
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
}
It returns
5
You may need to do one of two things when returning JSON from PHP.
Either set your content type in PHP before echoing your output so that jQuery automatically parses it to a javascript object or array:
header('Content-type: application/json');
or specify that jQuery should treat the returned data as json:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
dataType: 'json',
success: function(data)
{
var test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
Be aware, that in your current PHP script, in the event that your query fails, you will be json_encodeing an undefined variable.
Also, your PHP code is entirely open to SQL injection. Make sure you sanitize your $id, either by casting it to (int) or by escaping it before sending it through in your query.
Have you tried using JSON.parse on the value you are getting back from PHP?
e.g.
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = JSON.parse(data); // should be "Tiggert"
$('#client-detail-box').html(test[3]);
}
});
That seems like it would be a fix.

Sending JSON to PHP using ajax, troubles with data

my javascript won't go into my Database.php file.
Anyone knows what's wrong?
I know there is another thread with this question but it just doesn't work for me.
I have this in javascript
var Score = 5;
//Score insert
var postData =
{
"Score":Score
}
$.ajax({
type: "POST",
dataType: "json",
url: "Database.php",
data: {myData:postData},
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
and this in php
function InsertScore(){
$table = "topscores";
if(isset($_POST['myData'])){
$obj = json_encode($_POST['myData']);
$stmt = $conn->prepare("INSERT INTO " + $table + " VALUES (?)");
$stmt->bind_param('s', $obj);
$stmt->execute();
}
else{
console.log("neen");
}
$result->close();
change this line
success: function InsertScore(data){
to this
success: function(data){
the success parameter of jquerys ajax method has to be a anonymous function (without a name) or one defined in javascript but definitely not a php function.
You should read up on variable scope, your $table variable is not defined in the scope of your function.
You also have an sql injection problem and should switch to prepared statements with bound variables.
You are trying to send an object to your PHP file instead of a JSON data type.
Try 2 use JSON2 to stringify your object like this :
var scoreINT = 9000;
var usernameSTRING = "testJSON"
var scoreOBJ = {score:scoreINT,username:usernameSTRING};
var jsonData = JSON.stringify(scoreOBJ);
this would give you the following result "{"score":9000,"username":"testJSON"}"
You would be able to send this with your AJAX if you change ( if you follow my variable names ofcourse )
data: {myData:postData}
to
data: {myData:jsonData}
This would already succesfully transfer your data to your PHP file.
regarding your error messages and undefined. the message "e.message" does not exist. so thats the "undefined" you are getting. no worries here.
I noticed the succes and error are called incorrectly. I've just deleted them because there is no need to.
Next. moving up to your PHP.
you would rather like to "DECODE" then to encode your encoded JSON.
you could use the following there :
$score = json_decode($_POST['json'],true);
the extra param true is so you are getting your data into an array ( link )
or you could leave the true so you are working with an object like you already are.
Greetings
ySomic

Categories