Page not getting redirected php - php

I have passed some values from a page to another using ajax with request method post. But there is one condition that f some one is directly accessing the url, it should be redirected to some other page. Problem is that its not getting redirected (In else condition in img.php) . Can any one tell me what mistake I am committing?
Thanks in advance.
Code:-
imageupload.php:
document.getElementById("submit").addEventListener("click", function(event){
event.preventDefault();
saveImgfunc();
});
function saveImgfunc(){
var form = new FormData(document.getElementById('saveImg'));
var file = document.getElementById('imgVid').files[0];
if (file) {
form.append('imgVid', file);
}
$.ajax({
type : 'POST',
url : 'core/img.php',
data : form,
cache : false,
contentType : false,
processData : false
}).success(function(data){
document.getElementById('msg').innerHTML = data;
});
}
img.php:
<?php
require '../core.php';
$qry = new ProcessQuery('localhost', 'root', '', 'mkart');
$uid = 6;
if($_SERVER["REQUEST_METHOD"] == "POST"){
//Some code here
}
else{
header("Location : ../core.php");
}

See this post https://stackoverflow.com/a/21229246/682754
There's a good chance that you may have some whitespace before you use the header function? Perhaps in the form of a hidden error/warning.
Try the following at the top of your PHP code in img.php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
Would advise removing that once you've found your issue

It works for me removing the whitespace between Location and :
header("Location: ../core.php");

Error found. In the core.php thre is one code which stopping the further execution of code. Its specially coded for uid = 6. Thanks for your time.

Dont use header("Location : ../core.php"); some time it gives error or not working properly so use javascript redirection
like
?>
<script>window.location='../core.php';</script>
<?php

Related

PHP header() not redirecting even with output disabled [duplicate]

This question already has answers here:
Page redirect with successful Ajax request
(10 answers)
Redirect with PHP after ajax call
(5 answers)
Closed 2 years ago.
I have a button which I want to call a php script which does some stuff followed by a redirect to a new page based on that stuff. Relevant Code is:
HTML:
<button onclick="newTourney()">New Tournament</button><br>
and
<script>
function newTourney(){
var name = prompt("Tournament Name:");
$.ajax({
url: "new_tournament.php",
method: "POST",
data: {name: name}
});
}
</script>
new_tournament.php (including ob_...() and error reporting enabled to try to fix this):
<?php
use general\orm\UsbgfGenOrm;
use trn\interfaces\Usbgf\UsbgfUtil;
use trn\orm\DimEvent;
use trn\orm\DimTournament;
include_once __DIR__ . "\..\usbgf_bootstrap.php";
ob_start();
$club = UsbgfUtil::getOnlineCircuitClub();
$tournament = new DimTournament($club);
$event = new DimEvent($tournament);
error_reporting(E_ALL);
ini_set('display_errors', true);
if(isset($_POST["name"])){
$tournament->Name = $_POST["name"];
$event->Name = $_POST["name"];
}
$tourneyId = $tournament->getId();
ob_end_clean();
header("Location: edit_tourney.php?id=" . $tourneyId);
exit;
It simply isn't doing anything whatsoever when the button is pressed. I've tried printing the response from the ajax call like so:
$.ajax({
url: "new_tournament.php",
method: "POST",
data: {name: name},
complete: function(response){
console.log(response.responseText);
}
});
When I do this, it prints the entire html from the page I'm trying to redirect to (and any other echos) to the console, so its definitely accessing the correct files at least.
My best guess is that something about $.ajax doesn't allow for redirects or something like that? I'm not sure what to replace it with but I use a similar ajax call elsewhere to a script without a redirect and it works just fine.

Include php file via Ajax and display on page

I was wondering if there is any way to include a php file after an AJAX call and display that included file in my page as response.
For example this is an ajax call:
$('#id').change(function(){
var selected = $(this).val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "select="+selected,
success: function (data) {
$("#here").html(data);
}
});
});
And this is what i tried in php but i got not result displayed on my html:
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
include("include.php");
}
}
Is there any way to display my included file in my html?
I tried to change my success response from Ajax $("#here").html(data); to $("#here").load(data); but it returned the whole page.
Any suggestions will help.
UPDATE: Inside the include.php file exist a long html code and some class methods
PS. Please don't mentioned that script is not safe, I know is just an example script.
Thank you in advance
In order to get the success data you need to return the data which you want to be included. And remember php will not work in html except it is action call. You can have php file for this since it has the html support also.
Also you need to remember, before setting the success data to the element it's better to console the value and make sure you are getting the correct data.
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
return include("include.php");
}
}
you can set all your "include.php" html in buffers and then you need to echo your content into console.
<?php
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
ob_starts();
include("include.php");
$include = ob_get_contents();
echo $include;
}
}
?>

$.getJSON not returning any data

I am trying to test $.getJSON() on localhost, but no data is returned.
Please correct me if I am wrong.
PHP:
$person['name'] = !empty($_GET['name']) ? $_GET['name'] : 'name';
$person['age'] = !empty($_GET['age']) ? $_GET['age'] : '00';
return json_encode($person);
?>
HTML / jQuery:
<script>
$(document).ready(function(){
$('.start').click(function(){
$.getJSON('http://localhost/ewoe/server.php?name=natasha&age=22', alert(data.name));
})
}); //end ready
</script>
All files can be found in the same directory.
Although, the error I get after hitting the .start button is 'data not set'.
The problem is actually in the PHP output.
The reason is that PHP, being a server-side language does not output to the HTML the stuff with return. If you want to print them out you have to echo them.
Therefore return is not the answer, the answer is echo.
Your php should be:
<?php
$person['name'] = !empty($_GET['name']) ? $_GET['name'] : 'name';
$person['age'] = !empty($_GET['age']) ? $_GET['age'] : '00';
echo json_encode($person);
If you are getting errors on the No 'Access-Control-Allow-Origin' you should try giving a local path, not the full path:
$.getJSON('server.php?name=natasha&age=22', ...);
-
NOTE
Don't really know what you are doing there, but as a note, be carefull to possible manipulation of your script.
By doing this, someone can see the source of your file and send request to the server.php by going to www.yoursite/ewoe/server.php?name=....
Perhaps you should use the $_POST in the PHP and jQuery $.post requesting json format, like this:
$.post('server.php', {name : 'natasha', age: 22}, function(response) {
console.log(response.name)
}, 'json');
You should wrap alert into anonymous function:
$.getJSON('http://localhost/ewoe/server.php?name=natasha&age=22', function(data) {
alert(data.name);
});

Passing PHP variable with jQuery

I need an assistance on how to transfer this value $row[COMPONENT] in my class1.php into another page process_class.php with jQuery using post method.
i did this but it seems doesnt work ,
$('.cuttingCheckbox').change(function() {
if (this.checked) {
$.post('process_class.php',
{ comp : $($row[COMPONENT]).val(), comp_id : $($row[ID]).val() },
function(response) {
this.setAttribute("disabled", true), alert(comp,comp_id); });
}
});
Does anyone willing to help me ?
you can save that $row[COMPONENT] into session like this:
$_SESSION['row_component'] = $row[COMPONENT];
and in your next page, you just retrieve it:
$row = $_SESSION['row_component'];
As Jonast said (thanks dude), you should initiate the session first at the top of your php file: session_start();

CodeIgniter AJAX: POST not working, GET works fine

Fiddling inside CodeIgniter and trying to get a grip on it all as I've never worked with AJAX before.
For some reason, my AJAX is working perfectly when I use the GET method, but if I switch it over to the POST method, it stops working.
My JS:
$(document).ready(function(){
$('.love').click(function(event) {
$.ajax({
type: 'GET',
url: base_url + '/ajax/love_forum_post',
data: { post_id: 2, user_id: 1, ajax: 1 },
});
return false;
});
});
And my CONTROLLER:
function love_forum_post()
{
$post_id = $this->input->get('post_id');
$user_id = $this->input->get('user_id');
$is_ajax = $this->input->get('ajax');
if ($is_ajax)
{
$this->load->model('forums_model');
$this->forums_model->add_love($post_id, $user_id);
}
// If someone tries to access the AJAX function directly.
else
{
redirect('', 'location');
}
}
If I switch the type to 'POST' inside my JS and then catch it on the other end with $this->input->post() it doesn't work.
Any suggestions?
I have tested your code in 2 scenarios:
first - without csrf protection, and I see no reason for your code not to run properly.
To be able to test it easier, append $.ajax call with success response.
Something like this
success: function(response) {
alert(response);
}
And add response to your love_forum_post method.
echo print_r($this->input->post(), true);
This would give you clean view of what it going on in your method.
In my installation everything works just fine.
Second scenario is with csrf protection.
In this case add new param to your post object.
<?php if ($this->config->item('csrf_protection') === true) : ?>
post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>';
<?php endif ?>
This would make CI accept post from this url.
Hopefuly it would help.
Cheers
By any chance you have csrf_protection enabled?
If yes you need to send the token and the value key as post parameter along with post request.
Try to use this
$post_data = $_POST;
and print the post data using this
print_r($post_data);die();
and you can see there if you catch the post data;
Gudluck!!

Categories