Sending JSON to PHP using ajax, troubles with data - javascript

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

Related

Passing Javascript Variable to PHP File

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!

Sending POST data to PHP script - jQuery, AJAX & PHP

I seem to be struggling with sending POST data to my PHP script.
My AJAX sends data (an ID of a blog post) to my PHP script, which then finds the row that contains a matching ID from a database.
The script then sends back the title of the blog post and the content of the post in an array, which AJAX picks up and inserts into a form in the DOM.
I can successfully:
insert sample data (for example, if I simply store strings into the array I'm passing back to AJAX, it will successfully insert those strings into the form); and
insert the correct data from the database when a static ID is specified (for example, if I switch out $_POST['editpostid'] and specify the integer 5 instead, the query successfully finds the row with ID = 5 and AJAX inserts this data into the form).
Therefore, from my point of view, the problem is that the ID is never reaching the PHP script, or my script cannot see the ID inside the JSON object.
Please take a look at my code and let me know what you think. I'm new to all this, so I'd appreciate your feedback - if it fixes the problem or not.
Javascript/jQuery:
// When edit button is clicked
$('li.edit').click(function() {
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
alert(oldpostid); // Returns the correct postid, for example 5
var jsonObj = { 'postid': oldpostid };
alert(jsonObj); // Returns 'object Object'
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
data: { 'editpostid': jsonObj },
success: function() {
// Fetch post data back from script
$.getJSON('../scripts/fetchpost.php', function(data) {
alert(data.title); // Returns null
alert(data.content); // Returns null
// All of the below code works if the PHP script returns sample text,
// or if an ID is specified in the PHP script itself
var title = data.title;
var content = data.content;
// Insert data into editor
$('#titlehead').text(title);
$('#edittitle').val(title);
var editor = 'editpost-content';
tinymce.get(editor).setContent(content);
});
},
error: function( e ) {
console.log(e.message);
}
});
});
PHP:
<?php
// Specifies connection details
include('../scripts/config.php');
// Fetch data from AJAX
$postid = $_POST['editpostid']; // Where I think the problem lies. Returns null.
// Again, this works if I switch out $_POST with an integer, such as 5
// Find rows in database that match postid
$postedit_qry = mysqli_query( $dbconnect, "SELECT * FROM posts WHERE postid='$postid'" );
// Store results in an associative array
$row = mysqli_fetch_assoc( $postedit_qry );
// Split array into variables
$title = $row['title'];
$content = $row['content'];
// Organise data into an array for json
$postedit = array(
'title' => $title,
'content' => $content
);
// Return array as json object for ajax to pick up
echo json_encode( $postedit );
// Close connection
mysqli_close( $dbconnect );
?>
Update - Solution:
Fixed jQuery/Javascript:
// Snip
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
data: { "editpostid": oldpostid },
success: function(data) {
var title = data.title;
var content = data.content;
// Snip
The PHP script remains the same.
Many thanks for your help!
MrPupper
I think you missed the index 'postid' and need to replace this
$postid = $_POST['editpostid'];
with this line :
$postid = $_POST['editpostid']['postid'];
Or instead of sending
data: { 'editpostid': jsonObj },
send this
data: { 'editpostid': oldpostid },
Looking over your code, it seems like you are getting null because you are requesting the fetchpost.php script twice. Once when you contact the script via $.ajax(...); and once more when you call $.getJSON(...);. When you contact via $.getJSON(...);, though, you are not POSTing data and it seems like your script does not have a properly defined way to handle GET requests, so the script doesn't know how to react and it returns null information.
I would change the JavaScript/jQuery to the following:
// When edit button is clicked
$('li.edit').click(function() {
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
alert(oldpostid); // Returns the correct postid, for example 5
var jsonObj = { 'postid': oldpostid };
alert(jsonObj); // Returns 'object Object'
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
data: {'editpostid': jsonObj },
success: function(sData) {
var data = JSON.parse(sData);
alert(data.title); // Returns null
alert(data.content); // Returns null
// All of the below code works if the PHP script returns sample text,
// or if an ID is specified in the PHP script itself
var title = data.title;
var content = data.content;
// Insert data into editor
$('#titlehead').text(title);
$('#edittitle').val(title);
var editor = 'editpost-content';
tinymce.get(editor).setContent(content);
},
error: function( e ) {
console.log(e.message);
}
});
});
Additionally, PHP is going to be expecting an application/x-www-form-urlencoded value to be able to interact with $_POST[...]. As such, if you want to feed it JSON, then in your PHP, you will need to implement a solution such as: $postedData = json_decode(file_get_contents('php://input')); (See more about that in this answer; for more about json_decode, see the official PHP documentation for json_decode.)
Note: While outside of the scope of your question, and you may know this already, I find it important to point out that your MySQL is insecure and vulnerable to SQL injection due to just blindly trusting that the postId has not been tampered with. You need to sanitize it by saying $postid = $dbconnect->real_escape_string($postid); after you initialize $dbconnect and connect to the database, but before you put the $postid into your SQL query string.

Am I able to make an AJAX call to a specific function within a PHP file from a JS file

I have a Javascript function that pulls in the users latitude/longitude and stores it in an array for later use. What I'm trying to do is take the users latitude/longitude and run a distance comparison to several other latitude/longitudes which are stored in a database. What I'm trying to do, and I could be thinking about this all wrong, is make a call with AJAX within that Javascript, to a specific function within a PHP file (the function pulls just the latitude/longitude of each related store from the database). Normally, this should be easy, but there are multiple functions within the PHP file so I'm wondering if this can even be accomplished this way.
Thank you in advance for any help you can provide. I'm still new to all of this so your patience is appreciated.
This is the code I have so far (I'm brand new to AJAX so I don't have any AJAX code written yet):
function userPosition() {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
currentPos.push(lat, lng);
}, function(error) {
alert('Error occurred. Error code: ' + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from location provider)
// 3: timed out
});
};
Here's the code within the PHP file:
public function get_closest_location() {
$addresses = array();
$i = 0;
//Get primary address
$addresses[$i]['lat'] = $this->dealer_info['lat_1'];
$addresses[$i]['lng'] = $this->dealer_info['lng_1'];
//Get Dealer Addresses
global $wpdb;
$results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->gdp_dealers_addresses WHERE dealerId = %d", $this->dealer_info['dealer_id'] ), ARRAY_A );
foreach($results as $res){
$i++;
$addresses[$i]['lat'] = $res['lat'];
$addresses[$i]['lng'] = $res['lng'];
}
return $addresses;
}
The answer is Yes and No, so the solution is not totally straight forward
As you can only get AJAX to directly run a PHP script and not a function inside it, all you need to do is add some information to the POST data that you send to the PHP script to tell it what function within your PHP library you want to run.
So you add something like this to the posted variables
var params = {.........};
$.ajax({
method: "POST",
url: "some.php",
data: { toRun: 'userPosition', anyData: params }
})
.done(function( msg ) {
alert( msg );
});
Then in your PHP that is the first thing you test for
<?php
// check for existance of all required post variables
switch ($POST['toRun']) {
case : 'userPosition'
// get any other parameters out of POST array you may need
$params = array(.....);
userPosition();
break;
case : 'otherFunction'
...
...
default :
echo 'Huston we have a problem';
This is a basic outline and you will of course have to add some more code to look after passing back data, but this is the basic outline
}
Php essentially runs from top to bottom. Calling the file ftom the browser does just that.
If the file contains function definitions, but no calling code, nothing will be run.
To handle your problem, you need to:
Identify the function to be called
Check it is an allowed function, to avoid malichious code injection
Call the function
To do that, you can send the required function as a get parameter, check it against a whitelist, and call it:
//example.php
function somefunc(){}
function anotherfunc(){}
function privatefunc(){}
function onLoad(){
$func = isset($_GET['func']) ? $_GET['func'] : false;
$allowed = ['somefunc','anotherfunc'];
if(in_array($func, $allowed){
call_user_func($func);
}
}
//call onload function when script is executed
onLoad();
To call a function you would use the correct query string in your ajax request, eg /example.php?func=somefunc
I would recommend you pass a GET parameter to the php script. This would look as follows:
javascript:
$.post( "script.php?action=userPosition", { lat: "2.0123123", long: "2.0319239123" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
append this to your php file:
if (isset($_GET["action"]) && $_GET["action"] == "userPosition") {
echo get_closest_location($_POST["lat"], $_POST["long"]);
exit;
}
you would need to modify the arguments of the php function obviously, but then this would be all it takes.

Retrieving a JSON.parse() string from a server

I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.
I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.
With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.
The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.
I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.
-Javascript-
var calculateMpg = function () {
// These lines are commented out since the server will perform these checks
// if (!checkNumber("miles") || !checkNumber("gallons")) {
// return;
// }
var miles = $("#miles").val();
var gallons = $("#gallons").val();
console.log("ajax request issued.");
var result;
$.ajax({
url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons,
cache: false,
dataType: "text",
success: function(msg) {
console.log("ajax response received.");
// TODO: parse the JSON string returned from the server (see JSON.parse())
JSON.parse("result");
if (result.status === 'success') {
// TODO: get the mpg value returned from the server and display it to the user.
$("#mpg").val($_GET("result"));
console.log("JSON Working!");
}
else {
// TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php
$_GET[fail(id)];
// TODO: report the error to the user using invalidNumber() function.
alert("{status: 'failure', variable: <variable name>}");
}
}
});
};
$(document).ready( function () {
$("#miles").blur(function () {
checkNumber("miles");
});
$("#gallons").blur(function() {
checkNumber("gallons");
});
$("#calculate").click(calculateMpg);
$("#miles").focus();
});
-PHP-
<?php
if ($_GET) {
if ($_GET['action'] == 'calculateMPG') {
$miles = htmlspecialchars($_GET['miles']);
$gallons = htmlspecialchars($_GET['gallons']);
// validate miles
if (strlen($miles) == 0) {
fail("miles");
}
$miles_chars = str_split($miles);
for ($i=0; $i< count($miles_chars); $i++) {
if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
//error_log("miles_chars check failed at: " + $i);
fail("miles");
}
}
// validate gallons
if (strlen($gallons) == 0) {
fail("gallons");
}
$gallons_chars = str_split($gallons);
for ($i=0; $i< count($gallons_chars); $i++) {
if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
fail("gallons");
}
}
// validate $miles and $gallons calling $fail along the way
$result = $miles/$gallons;
if ($result) {
success($result);
} else {
fail("mpg");
}
exit ;
}
}
function fail($variable) {
die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
Edited Additional 1
I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.
Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?
A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.
The solution to the equation miles/gallons appears in the 'msg' output.
Thanks.
Edited Additional 2
This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.
The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.
Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.
-ECP03
JSON.parse() requires that you send it a valid JSON string.
"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.
You have two options:
Option 1: -- Parse the string returned.
Change JSON.parse("result"); to:
var result = JSON.parse( msg );
Option 2: -- Request JSON instead of plain text - no need to parse
Use $.getJSON() which is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:
var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
if (data.status == 'success') {
console.log('Success! Message:', data.message);
} else {
console.log('Failed :( Variable:', data.variable);
}
});
For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.
You need to use the result returned by the success function:
var result = JSON.parse(msg);
Then, you could do stuff like result.status.
When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.
JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result").
For example:
var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
console.log(obj[k])
}
This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.
JSON is essentially the right-hand side of an assignment expression.e.g.
var foo = 'bar';
^^^^^---this is json
var baz = 42;
^^---also json
var qux = ['a', 'b', 'c'];
^^^^^^^^^^^^^^^---even more json
var x = 1+2;
^^^---**NOT** json... it's an expression.
What you're doing is basically:
var x = parse;
^^^^^^---unknown/undefined variable: not JSON, it's an expression

Check return value when parsing json array in javascript

I'm a beginner in ajax and json so I'm sorry if this question is a bit stupid. I'm retrieving the data(city id and name) and put them in an array then use json_encode. Then I call the getCities function but I'm not sure if I'm getting the correct cities. I tried using document.write but there's no output. How can I know if I'm getting the correct ones? Thank you for your help.
Here's the getCities.php:
$json = array();
$query = "SELECT cityID, cityName FROM city";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$coord = array('id' => $row['cityID'],'city' => $row['cityName']);
array_push($json, $coord);
}
$jsonstring = json_encode($json);
And here's the javascript part:
function getCities(){
var string = $.ajax ({
url: "getCities.php",
dataType: 'json'
}).responseText;
return JSON.parse(string);
}
$(document).ready(function (){
var city = getCities();
while (city.length > 0) {
document.write(city.pop + "<br/>");
}
});
There are 2 easy ways to do this. First of all I use Google Chrome (or Firefox) to facilitate testing. Look at the docs and you will see that your $.ajax call will also accept a success function. You could put it in the ajax call under dataType like this:
var string = $.ajax ({
url: "getCities.php",
dataType: 'json',
success: function(data) {
console.log(data);
}
});
string.done();
Notice how I changed the end of the ajax call. It is now saying, when this call is done, call the success function. You can also put an error function in the ajax call if you want to have something print out in case of an error. The success function will then be called when the data returns. It will print in the console of your Chrome debugger. Google that term to find out how to show it, super easy stuff. You can also put a break point on the console.log function call (Google how to do that also) and you will be able to inspect the object that is returning from your ajax call.
Also, the console.log will not work in IE as far as I know.
Have fun.
function getCities(callback){
var string = $.ajax ({
url: "getCities.php",
dataType: 'json',
success:callback
});
}
$(document).ready(function (){
getCities(function(data){
console.log(data);
var city = JSON.parse(data);
if (city.length > 0) {
document.write(city.pop + "<br/>");
}
});
});
Ajax is asyn, you cannot use var city = getCities();. Because when you call that, ajax response has not arrived yet. You need to pass in a callback function, and when ajax response has arrived, call that function to get the response.

Categories