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.
Related
I've a html form on a page. The form data is sent via AJAX to a PHP script. Within this PHP script, each of the $_POST's from the inputs are checked conditionally using a variety of if statements. If the condition doesn't meet a specific strlen / other criteria then I echo a message into the AJAX returndata and exit() the PHP script.
Assuming all conditions are met, at the bottom of my PHP script I have applied a url that is built from variables within the PHP script itself and concatenated inside, like so:
header("location: view_topic.php?tid='".$tid."'&page='".$page."'");
The issue:
Since I am generating the url within the PHP script, and am only able to generate it in there, I am having to either use PHP header("location: ...") as a redirect, or having to echo the url, which in turn sends it to the returndata, then use window.location(returndata) in my JavaScript/AJAX.
I've done some homework and have noticed a known issue with the header method, when set is being sent to the AJAX returndata. This means that the entire header location page is being displayed in a tiny invisible div where I display my errors for the above mentioned conditional error messages generated in the PHP script.
The question:
In the below code is my alternative method of setting the window.location(returndata).
Here I am echoing the actual url generated by my PHP variables, which sends it to the returndata. However when submitting the form I am returned to the same page, and the returndata is simply echo'd out from the PHP at the top.
Does anyone know how to prevent the header("location: ..."); from being sent to the AJAX returndata, or have any other solutions on the method below?
Thanks in advance,
Richie.
My AJAX:
$("#topic_form").submit(function(event){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'create_topic_parse.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata.indexOf("view_topic") != true){
$('#message').css("color", "red").html(returndata);
} else {
window.location(returndata);
}
}
});
return false;
});
instead of returning html, return json:
{"action": "display","html":"..."}
or
{"action":"redirect","location":"url"}
and change:
success: function (response) {
if(response.action == "display"){
$('#message').css("color", "red").html(response.html);
} else if (response.action == "redirect") {
window.location(response.location);
}
}
I think that, If I understand correctly. You want to use create_topic_parse.php, to generate a URL which you would then like to be redirected to.
Currently the page you want redirecting to, is displaying in a div on your existing page and not redirecting.
I think that in your PHP file, if you echo a meta refresh instead of a header() then this should get you the results you want.
echo "<meta http-equiv=\"refresh\" content=\"0;URL=view_topic.php?tid=".$tid."&page=".$page."\">";
These have always worked as part of the body for me.
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
I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}
I'm fairly new to the jQuery execute on the same page stuff. So far I have been passing only single values trough ajax which is working fine. Now, I need to pass an array which is created by checkboxes through ajax.
My form html, dynamically created by php:
<input type=checkbox class=box name=box[] value=".$row['DoosID']." />
My jQuery:
var BackorderDate = $("#BackorderDate").val();
var Box = $(".box").val();
if( (TerugleverDatum == "") ){
$("#backorderresult").html(" * Some Error .").fadeIn("Slow").fadeOut(3000);
} else {
$("#backorderresult").fadeOut();
$.ajax({
type :'POST',
url :'./backorder.php',
data : box : Box,
backorderdate: BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
}
My PHP:
$boxlist = json_encode($box);
foreach($boxlist as $boxvalue){
// Do something with every value
}
this gives me a javascript error on submit saying box is not defined.
change this:
data : box : Box, backorderdate: BackorderDate, // invalid way of sending
to this:
data : {box : Box, backorderdate: BackorderDate}, // valid way
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs.
More Info
Why don't you try enclosing all the data values in a open and close curly braze( { and } ) .
Else it will conflict with the syntax of $.ajax method.
I think it is causing the problem.
You are sending data value in wrongly manner -
The data property should always be a JavaScript object. It's properties are serialized into a regular query string (for GET requests), or a normal post body parameter string (for POST requests). This serialized string is then sent to the server, along with the AJAX request.
On the server you can read the properties of the data object as if they were sent as simple request parameters, via either GET or POST. Just like if the properties had been fields in a form.
Try this :
$.ajax({
type :'POST',
url :'./backorder.php',
data : 'box='+Box+'&backorderdate='+BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
For more information see jQuery Ajax
You might want to refer to the php file like this: url :'../backorder.php' (double dots). At least, that's how I do it always.
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.