So basically what I'm doing is auto filling a textbox using AJAX to grab information from a PHP script that calls a C function.
This is what I've found in theory: (Assuming receiving only one value)
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response) {
$('#v1').val(response);
});
}, 5000);
});
Now, if this works, which I believe it will. If I receive an array of values, then the input inside of function cannot be response, correct? So what would I have to change it to make it an array?
Just to be clear, my PHP script is using echo to output its information. I'd rather output in such a more "standard" manner as in V1 = 120, V2 = 120, etc. but PHP is new to me and that I am currently researching. Thank you.
EDIT:
Just to make it clearer
Would something like this work?
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
$('#v1').val(response[0]);
$('#v2').val(response[1]);
$('#v3').val(response[2]);
});
}, 5000);
});
Since you echo on PHP side, the response just can be a string.
But if that string if formed as a valid JSON, you will be able to use it like you wish.
So on PHP side, make sure the json format is valid:
$array = [120,340,800];
echo json_encode($array);
Then in JS... You received a string... You have to parse it to make it an array.
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
var responseArray = JSON.parse(response);
$('#v1').val(responseArray[0]);
$('#v2').val(responseArray[1]);
$('#v3').val(responseArray[2]);
});
}, 5000);
});
Per the OP update, you could try something like this to map each item of the array up to its corresponding text box you could do.
$.post(ajaxurl, NULL, function (response) {
for (var i = 0; i < response.length; i++) {
$("#v" + (i + 1)).val(response[i]);
}
});
This would map each index of the array returned from the JSON endpoint, to a corresponding text box.
If the JSON being returned from your endpoint is a valid JSON array, your response variable should already be an array!
Send your array as json:
echo json_encode(array($value1, $value2, $value3));
JS
$.post(ajaxurl, NULL, function (response) {
// selectors in same index order as response array
$('#v1, #v2, #v3').val(function(i){
return response[i];
});
},'json');
The easiest way (for me) to communicate between javascript and PHP is JSON.
So your PHP script have to generate an answer in this format.
PHP code
// At the top of your PHP script add this
// that will tell to your browser to read the response as JSON
header('Content-Type : application/json', true);
// Do your logic to generate a PHP array
echo json_encode($yourArray);
HTML code
<div class="someClass"></div>
Javascript code
var container = $('.someClass');
$.post(ajaxurl, NULL, function (response) {
console.log(response); // for debuging
for (let i = 0; i <= response.length; i++) {
let myItem = response[i];
container.append('<p>' + item + '</p>');
}
});
It's cleanest to generate dynamically the p elements because you don't know how many results your PHP file will return you.
I'm not sure of the javascript code, you maybe will received a json string that you have to transform to a Javascript Array
Before link you javascript to php script, try some call with postman (or others http client) to ensure that your 'webservice' is working as excepted
Related
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.
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
I am working on a project that uses a function I called AjaxRequest which handles all AJAX requests I make. I have no problems in making the request however getting the request back is the issue and placing it where I want it on my page is becoming stressful.
HTML BIT
<body onLoad="calling();">
<div id="status">Status: </div>
</body>
JAVASCRIPT BIT
function calling() {
var answer = ajaxRequest("testing", "test.php", "test=test");
document.getElementById("status").innerHTML += answer[1];
document.getElementById("status").innerHTML += " " + answer[3];
}
function ajaxRequest(app, location, credentials) {
var extras = "";
if(credentials === "" || credentials) {
extras = "&" + credentials;
}
var ajax = ajaxObj("POST", location);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var obj = JSON.parse(ajax.responseText);
var arrayObj = [];
for(var i in obj) { arrayObj.push([i, obj[i]]); }
return arrayObj;
}
}
ajax.send("app=" + app + extras);
}
there are two other functions running: ajaxObj and ajaxReturn but I excluded those because they is not the problem. Furthermore, I am trying to make ajaxRequest an efficient function that could be used by more than one application without having to rewrite all the code in more than one location. All error handling acquires before the actual use of ajaxRequest.
PHP BIT
<?php
if($_POST['app'] == "testing") {
$hey = array('success' => 1, 'message' => 'Successful');
echo json_encode($hey);
exit();
}
?>
I'm using calling as a javascript function that does all error handling, this is just basic for the whole of my project however I try to get the JSON from php and convert it to array and the issue is returning the array into calling. I try to display the information on the page yet nothing works.
I am not looking to use any JQuery for my project so I would like to exclude the use of it for this piece of code.
If you want, you could set the header before sending back the json.
header('Content-Type: application/json');
Usually you don't need it, but it will tell your javascript that it's json, and the array will be transform in a javascript object. It work with Jquery, but I assume it'll work without too
I have application.php page where json array is echoed with php. On the client i want to get the json array with $.getJSON() on button click when form is submitted(submitHandler). The problem is that if I run alert() or console.log() in $.getJSON() nothing happens(i only see GET execution in console).
Code:
$.getJSON('../views/application.php', function(data) {
alert('alert1');
if(data) {
document.write(data.resp);
alert('alert2');
}
else {
alert('error');
}
});
GET http://localhost/app/views/application.php
you can use var temp in your script and store your data inside that variable.
var x;
<script type="text/javascript">
x='<?php echo $comparisonResult; ?>';
</script>
Sounds like a use case for sessionStorage or cookies.
Use sessionstorage if you don't need to support IE7.
I think the best way is to return the needed server data in the response of your first post request, just like this :
$.post( "/first.php", function( serverData ) {
var param = serverData.something;
...
$.post( "/second.php", param, function( data ) {
...
});
});
If you are using the two request in two different pages, you can store serverData in localStorage.
Edit after your clarification:
If you need to get data before ajax post when you click on a button, you can do this way :
$("#second-button").click(function() {
$.getJSON("/data.php", function (serverData) {
var param = serverData.something;
$.post("/second.php", param, function(data) {
...
});
}
});
Edit 2
For some reason (wrong url, invalid json, and so on) your $.getJSON fail.
Try this for debug:
$.getJSON("/data.php", function (serverData) {
console.log(serverData);
}).fail(function(j, t, e) {
console.error(e);
});
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