Currently I've been Ajaxing a route that renders a Twig template via a Controller and injecting it into the page - all is well.
return $this->render('MyBundle:Requests:results.html.twig', array('system' => $lc_system));
However, in my JavaScript, I would like to get some extra information returned... Specifically I want a count of the results, so I can check it against a JS variable. I could put it into the twig file and then get it in JS that way, but it feels horrible.
Is there any way to get any variables sent down with the Ajax response, or a best practice way to approach this.
Use echo in your PHP function instead of return.
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function() {
doSomething(data); //Data is output
}
});
In PHP:
<?php
$output = some_function();
echo $output;
?>
It's an argument passed to your success function.
The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation.
If you weren't returning actual page content in your response, I'd say to return a JSON response and call it good. But since you're already using your response body for some HTML, you have to come up with another way to return the info.
One approach I've used in the past is to add a custom HTTP header and return my "meta" values that way. First, set the header in your PHP (make sure this happens before any output):
header('X-MyCustomHeader: ' . $phpVar);
Then, you can get it in your jQuery success method like this:
success: function(result, status, xhr) {
var customHeader = xhr.getResponseHeader('X-MyCustomHeader'));
}
While you can technically name your custom header anything you want, see this post for best practice/naming convention ideas:
Custom HTTP headers : naming conventions
Related
I want to create a client-side and server-side check. These checks will look for empty names, invalid names, already taken names etc.
however my problem: my parameter is given the argument of the header, and therefore the user won't be redirected, it will only show code.
quick example:
$.ajax({
url: 'signup.php',
type: 'POST',
data: data,
success: function(response) {
window.location.href = response;
}
});
PHP code:
if(empty($loginName)) {
header('Location: index.php?loginName=empty');
exit();
}
So what I would like to have, but won't work (this is to give you an idea of what I am trying to do):
if(empty($loginName)) {
index.php?loginName=empty //and this should be the response argument
header('Location: index.php?loginName=empty');
exit();
}
My response parameter would have the argument of the header + the header content, so it will only generate html code. (I used console.log() to see what response held as argument). I can however take away the header tag and just use a string, my response will work then, but what I would like to have is the following: I would like to keep the header() function, but I want my response to redirect me correctly based on what the header() content is.
I already tried using a string and the header() function seperately, but this didn't work, unfortunately.
So expected result would be (if loginName were to be empty) that response holds a string with: index.php?loginName=empty, but without removing the header() function.
Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.
I have a php file with a lot of checkboxes on the left hand side. I extract the values via javscript and pass them into an array. Which works just fine. I would like to pass then this array via Ajax to PHP in order to mess around with the values and create SQL-statements out of them.
$(document).ready(function(e) {
$('#getSelectedValues').click(function() {
var chkBoxArray = [];
$('.graphselectors:checked').each(function() {
chkBoxArray.push($(this).val());
});
for (var i = 0; i < chkBoxArray.length; i++) {
console.log(i + " = " + chkBoxArray[i]);
}
$.ajax({
url: 'index.php', // (1)
type: 'POST',
dataType:'json',
data: chkBoxArray, //(2)
success: function(data){
console.log(data.length);
console.log(data);
}
});
});
});
Several questions:
(1) what file name do I need to add here? The origion or the target?
(2) I have numerous ways of this: serialization, with these brackets {}, and so on. How to get it done right?
An error that I get is the following:
Notice: Undefined index: data in graph.php
That makes me wondering a bit, because it clearly shows no data is being send.
var_dumps on $_POST and $_SERVER offer these results:
array(0) { }
array(0) { }
which is somewhat unsatisfying.
Where am I doing things wrong? The only puzzling aspect is the ajax, all other stuff is not much of an issue.
The site is supposed to work in the following way:
Page -> Checkbox(clicked) -> Button -> result (ajax) -> PHP fetches result -> SQL DB -> PHP gets DB result -> fetch result (ajax) -> jslibrary uses result for something.
1- You need to point your ajax to the script that will use the data you are sending. I would not recommend to point to index.php, since you'll need to add a if statement checking if there is data on $_POST that is exactly what your're expecting, otherwise it will return the same page that you're in (considering that you are in index.php and is making a request to index.php). A point to consider. Since it is a whole request and it's not a method call to actually return something to your page you need to echo things. That said, consider also to set header('Content-Type: application/json') then, since you're expecting dataType: 'json', echo json_encode($objectorarray);
2- Since you're sending a Javascript array to PHP, it can't interpret correctly the structure, that is why you should use JSON.stringify(chkBoxArray) before sending it. But just setting it on data attribute would send the number of checkboxes you selected as values to POST, so consider to data: {myCheckboxValues: JSON.stringify(chkBoxArray)}
In your PHP script, considering all the security measures to take, you can $foo = json_decode($_POST['myCheckboxValues']);
Well, of course you need to pass the target page as url in your ajax call. It can't guess which file should process the data.
As for the data property. You need to give your data a name.
data: {
something: "something"
}
Becomes: $_POST['something']. (value: something)
$.ajax({
url: 'target.php', // (1)
type: 'POST',
dataType:'json',
data: { data: chkBoxArray }, //(2) Now $_POST['data'] will work
success: function(data){
console.log(data.length);
console.log(data);
}
});
I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.
I have an HTML file referencing a PHP script to perform various functions. One of the ways the HTML file calls the PHP script is through an HTTP GET. The GET request should pass three parameters and return a list of all saved events as a JSON-encoded response.
So far, I have the following but I'm not sure how to pass the three arguments through the HTTP GET. Also, I'm not sure if I am returning the JSON-encoded response correctly:
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(events.json); }
GET requests are done through the URL... So if you want to pass three GET requests you would do...
http://www.domain.com/target.php?param1=whatever¶m2=whatever¶m3=whatever
target.php represents the PHP script file you want to send the information to. You can have as many variables as you want but just keep in mind that every other GET request has to be separated by an & symbol. The first param simply has to be started off with a ? symbol.
If you want to use Javascript, I would recommend using JQuery. You can do something like this
$.get('target.php?param1='+whatever+'¶m2='+whatever2, function(data) {
alert(data);
});
Or you can use window.location to send a link with the appropriate link above.
If you want to use AJAX specifically, here is a way of doing it with JQuery (there are ways with Javascript that I could update later if necessary:
$.ajax({
type: "GET",
url: "http://www.domain.com/target.php",
data: { param1 : "whatever", param2 : "whatever", param3 : "whatever" },
success: function(result){
//do something with result
}
})
If you want to access the variables, you can call $_GET['param1'] or $_REQUEST['param1'] to get access to them in PHP. Simply change the name in the brackets to the desired variable you want and store it in a variable.
If you want to access the params with Javascript... well the most efficient way is to go and decode the URL that was used and pull them out. See here
Hope this helps!
You can access the parameters from the URL via the $_GET superglobal in PHP.
For example, if your URL is http://example.com/test.php?param1=foo¶m2=bar, then you could access them in PHP like so:
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
See http://www.php.net/manual/en/reserved.variables.get.php for more details.
As for returning a valid JSON response, you can check out this answer. It uses PHP's header function.