How to pass javascript variable to php using ajax - javascript

I am trying to pass a javascript variable which I get when a button is clicked to php and then run a mysql query. My code:
function ajaxCall(nodeID) {
$.ajax({
type: "POST",
url: "tree.php",
data: {activeNodeID : nodeID},
success: function(data) {
alert("Success!");
}
}
);
}
function onButtonClick(e, data) {
switch (data.name) {
case "add":
break;
case "edit":
break;
case "delete":
nodeid = data.context.id;
ajaxCall(nodeid);
//query
break;
}
}
<?php
if (isset($_POST['activeNodeID'])) {
$nodeid = $_POST['activeNodeID'];
}
else {
$nodeid = 0;
}
?>
I haven't done this before, so I am not sure why this doesn't work. Any suggestions?
EDIT: Maybe I haven't explained myself well enough. I realise that php is server side and javascript is client side. I have an org chart that is displayed using javascript based on all the info is saved in my db. What I need to do is: when one of the javascript buttons is clicked (edit, delete, add) get the ID of the active node and use it as variable in php to run query. For example, delete the row in the db. What's the best way to do it?

There's a bit of confusion here, the success value stores a callback that gets called when the Ajax call is successful. To give you a simple example, let's say you have an Ajax call like this:
function ajaxCall(nodeID) {
$.ajax({
type: "POST",
url: "tree.php",
data: {activeNodeID : nodeID},
success: function(data) {
console.log(data.my_message);
}
});
This calls a PHP page called tree.php. In this page you do some computation and then return a value, in this case as JSON. So the page looks like this (note that I'm keeping it simple, you should validate input values, always):
$v = $_REQUEST['activeNodeID'];
$to_return = "the value sent is: " . $v;
return json_encode(array('my_message' => $to_return));
This simple PHP page returns that string as a JSON. In your javascript, in the specified callback (that is success), you get data as an object that contains the PHP's $to_return value. What you have written does not really makes sense since PHP is a server language and cannot be processed from the browser like JavaScript.

Related

Sending an array/set via to PHP via $.ajax. PHP adding a number

Im trying to send an array to the PHP script:
usedAnswers = [1,2];
// funtion for displaying a question
displayQuestion = () => {
$.ajax({
url: "backend/retriveData.php",
data: {usedAnswers:usedAnswers} ,
type:"post",
success: function(response) {
console.log(response);
}
});
}
// inital display of question
displayQuestion();
Then when I want to access the array in the PHP script
<?php
echo print_r($_POST['usedAnswers']);
?>
I get the following problem on screen
Why is he adding an extra 1 ?
When I try to access the first element of the Array like this:
echo print_r($_POST['usedAnswers'][0]);
He console.logs me the number 11?
What am I doing wrong what is the correct way to send an Array via Ajax?
Is it also possible to send a set via Ajax?
so, based on your comments, it appears your question is really referring to how to send data through, rather than the odd output you're getting, which Jay has already answered for you.
as far as your code reads, what you're actually sending is this:
{[1, 2]:[1, 2]}
which is invalid JSON.
if you're trying to actually have a 'usedAnswers' key (which it looks like from your php), then you need to do this:
$.ajax({
url: "backend/retriveData.php",
data: {'usedAnswers':usedAnswers}, // <-- note the quotes around the key
type:"post",
success: function(response) {
console.log(response);
}
});
Because you are echoing the print_r() (which in and of itself is a type of echo) you're returning a value for the truthiness of the print_r(). Change the line to this
print_r($_POST['usedAnswers']);

is it normal, if I use php in javascript ajax for session inside condition? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I have a code using javascript ajax like this :
$.ajax({
type: "POST",
url: "<?= site_url('test/test'); ?>",
dataType: "JSON",
data: {
id: id,
name: name,
},
success: function(data){
var data = {
"id": id,
"name": name,
}
<?php if ($this->session->userdata('class') == 'employee') { ?>
console.log('a');
<?php } else { ?>
console.log('b');
<?php } ?>
}
})
can I use session inside ajax code?
You should separate out the code:
PHP-side:
<?php
# what ever other code there is
echo $this->session->userdata('class');
JS-side:
$.ajax({
type: 'POST',
url: '/path/to/phpfile.php',
dataType: 'JSON',
data: {id: id, name: name},
success: function(response)
{
var data = {
'id': id,
'name': name,
}
if (response == 'employee') {
console.log('a')
} else {
console.log('b')
}
}
})
Now we only check the response value instead of mixing languages in a way that has no benefit. We set the response valueto the session value and perform a normal JS conditoinal to console.log()
You can only use a PHP variable (such as Session) as something you embed into the code as a hard-coded value e.g. if you write var x = '<?php echo $_SESSION["x"]; ?>'; then you create a JS variable x which has has the value of the Session value when the script starts. Assuming the Sesion value in that example was "hello" then in the final JavaScript which your browser receives and executes, you will see the following line: var x = "hello"; as a hard-coded snippet.
This is because PHP executes on the server, and generates the HTML and JS which is then sent to the browser after the PHP stops executing.
What you can't do is just write PHP inline in the JavaScript the way you've done in your example, and expect it to do anything. That PHP will execute before your JavaScript, and the result / output of the PHP (if anything) will be embedded in the JavaScript (or used to control exactly what JavaScript is generated and sent to the browser).
If you need to interact with the server during the execution of JavaScript code, but without posting back the whole page, then you need to make an AJAX request, so it generates a new HTTP request to the server, which can execute a PHP script and then return the response back to JavaScript to process.
In the specific example in your question, since you are already making an AJAX request, which can return data from PHP to JavaScript, I suggest you simply include the required Session value in the response data, and then write some JavaScript to read that value and decide what to do.
Further reading: What is the difference between client-side and server-side programming?

How to update the client side javascript based on something on the server?

I've researched this, but it's hard to find something when you don't know the best way to do it or even how to begin. I don't have any code obviously, so i'll describe my issue and hopefully someone can point me to the correct way to solve this :
ok let's say I have a page with a javascript function called "myfunction1" that fires off every x seconds by using setinterval in js. What I want it to do is, (using AJAX perhaps?) when "myfunction1" is called, call a php script that will check something in the database. If a certain condition is TRUE, I want a specific function to be called in javascript on the client side. If FALSE, I want it to call a different function.
My intuition makes me think the way to do it is to have the ajax call the php checking script, then echo the proper javascript code based on if true or false. But how would I go about doing that? I know how to use ajax to change the .innerhtml of a tag, but can you use it in this way to rewrite inside a script tag?? My head's spinning, hope I made some sense and one of you can point me the right way
AJAX would probably be the simplest solution and can be used to evaluate returning script or you can manually validate/display the response from the XmlHttpRequest that the server processed.
For example when using jQuery.ajax You can change the dataType option to script.
Otherwise you can manually program the validation in the success callback, like below, using JSON.
javascript (jQuery)
jQuery(function($) {
'use strict';
var element = $('#myElement');
var ajax = null;
var ajaxTimeout = 0;
function myFunction1() {
if (null !== ajax) {
//prevent overlapping ajax requests
ajax.abort();
ajax = null;
}
ajax = $.ajax({
url: '/response.php',
method: 'post',
dataType: 'json',
success: function(data) {
//parse the server side response
if (data.result === true) {
trueFunction(data);
} else {
falseFunction(data);
}
ajax = null;
}
});
}
//custom functions for true or false and setInterval.
function trueFunction(data) {
element.html('Success: ' + data.value);
}
function falseFunction(data) {
element.html('Failed: ' + data.value);
}
ajaxTimeout = window.setInterval(myFunction1, 1000);
});
response.php
<?php
header('Content-Type: application/json');
$date = new \DateTime;
echo json_encode((object) [
'value' => 'Hello World ' . $date->format('Y-m-d h:i:s a'),
'result' => true
]);
exit;

php array request with AJAX

so I'm doing a basic assignment for uni, they asked us to use ajax and php to create a text input that validates the name and email plus a live search bar, all this without using db. So I have the html already set up, the .php with 3 different arrays with names, emails and news stored in and a main.js that already displays whatever you type in the text input in the console with the keyup event trigger. I just can't figure out a way to make an ajax request to compare what you type in to the info stored in the arrays.
In the arrays.php I have this :
*$classes = array('1' => 101, '2'=> 102, '3'=>103 );*
*$names = array('juan', 'tito', 'pedro', 'horacio', 'andres', 'cesar', 'nicolas');*
*$news = array('Title'=>array('El papa muere', 'Argentina gana el mundial', 'Fondos buitres cancelados' )'Noticia'=>array('noticia1', 'noticia2', 'noticia3')
);*
and in the main.js I have something like this:
$('#name').keyup(function(){
var name=$(this).val();
console.log(name);
that retrieves what I type in each text field. As far as I can remember, the prof wrote something like this to give us a hint:
$.ajax({
url: ' ',
type: ' ',
success:function(data){
}
}):
But I just can't figure it out so any help would be much appretiated!
The general idea is to pass the current value of the search box to your PHP script via ajax. Then in your PHP script, you would filter your options based on the current value passed to it and return a filtered response. The javascript would then take the filtered response and output it on the page.
People usually use JSON as a format for passing information between Javascript and PHP.
To give you a little better understanding what $.ajax does. It will make a request to your server and then process the results. The parameters specified do the following:
url: The URL to request
type: The format of the response (eg. text, xml, json, etc.)
success: A callback to be called when the response comes back from the response.
Also note that the A in AJAX stands for asynchronous. This is why you need to give the $.ajax function a callback. Due to the nature of HTTP, you make a request and the response can return right away or in 30 seconds or never. When the response returns the callback will execute. It is not linear. Therefore the callback can execute after code below the the $.ajax call depending on how long it takes for the response to come back.
Maybe take a look at the example below to give you a better idea of how to do this:
<?php
$names = array('juan', 'tito', 'pedro', 'horacio', 'andres', 'cesar', 'nicolas');
$result = array();
foreach($names as $name)
{
if (strpos($name, $_GET['name']) !== false)
{
$result[] = $name;
}
}
echo json_encode($result);
?>
And the javascript
$('#name').keyup(function() {
var name=$(this).val();
$.ajax({
url: '?name=' + name,
type: 'json',
success: function(data) {
console.log(data);
// add data to results
}
}):
});

jQuery AJAX and JSON Performance Query

I am storing some JSON data in a text file to query using jQuery Ajax in my page. Currently, my text file contains around 10 facets of data (which could contain an additional 30 facets of data). The JSON data contains a questions and answers to those questions.
In my JavaScript files, I have setup different functions to get specific bits of data.
For example:
function GetAnswer(questionName) {
var correctAnswer = null;
jQuery.ajax({
type: "GET",
url: "../content/questions.txt",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
async: false,
success: function (result) {
$.each(result, function (i, q) {
if (q.questionID == questionName) {
correctAnswer = q.correctAnswer;
return false;
}
});
},
error: function () { },
complete: function () { }
});
return correctAnswer ;
}
As you can see from my code-snippet, I am looping through my JSON to get the data I need. I have other functions coded in a similar fashion to get the question type, question name etc.
What I am finding is that I am calling these functions one after another to get the data I need. I think the way I am querying my JSON data is not good from a performance point-of-view since I am looping through the whole of my JSON dataset until I find a match.
Is there a better way to query my JSON data?
NOTE: I am having to use a text file to store questions due to restrictions of the technology I am using (SCORM 1.2).
Looping through your JSON object is relatively quick. What is slow (comparatively) is loading in that text file each time (though it may be cached).
Either way, I would suggest loading in the JSON either the first time the user initiates a question/answer situation, or just load it in on page load (you can do it asynchronously) and store it for later use.
Example of the latter:
jQuery(document).ready(function(){
var questions = '';
jQuery.ajax({
type: "GET",
url: "../content/questions.txt",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
async: false,
success: function (result) {
questions = result;
},
error: function () { },
complete: function () { }
});
function GetAnswer(questionName) {
var correctAnswer = null;
$.each(questions, function (i, q) {
if (q.questionID == questionName) {
correctAnswer = q.correctAnswer;
return false;
}
});
return correctAnswer ;
}
});
The problem is that you have async set to false. This is bad. This halts the browser while it waits for your requests, and will cause the performance to feel very laggy.
Why not change the structure of your Q&A object to include an id for each question, and make the id an attribute in the object? Then you could pass the id to GetAnswer() and just have it go directly to the right question by referencing the correct attribute? The object could look like this:
{"myQuiz" :
"Q1" :
{ "q" : "What color was George Washington's white horse?",
"a" : "White"
},
"Q2" :
{ "q" : "In what city would you find the Leaning Tower of Pisa?",
"a" : "Pisa"
}
}
If this is assigned to result, and an id of Q2 was passed to GetAnswer(id), you could easily return result.myQuiz[id].a;
As an alternative, if the order of the questions is consistent, you could use an object that contains an array of q and a pairs, and refer to them by index rather than id.
Why not move the logic to a server-side script like PHP that can take in POST parameters and perform the queries against the JSON set and return only the record(s) you wish to receive. Or, if you are intent on keeping this in all js, you could simply store the JSON (as long as it is non-sensitive data) in a local variable and query against it locally.
You could make somekind of mechanism on the server to load data. Then you could send parameters like QuestionName and filter data. This will lower payload sent on the wire.

Categories