Header wont redirect when passedthrough ajax - javascript

Not sure if this is possible but I have a page that submits a form with AJAX and if it meets certain conditions it should automatically take the user to another page. NOTHING is outputted before the header tag its just a bunch of conditions.
Problem: Header redirect not working...
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
header("Location: http://localhost/manage/card.php?id=$id");

Headers can only be modified before any body is sent to the browser (hence the names header/body). Since you have AJAX sent to the browser, you can't modify the headers any more. However, you can have the add.php script called via AJAX return the $id parameter. Then that parameter can be used in JavaScript to redirect the page: window.location = 'http://localhost/manage/card.php?id=' + id.
More info on PHP header(): http://www.php.net/manual/en/function.header.php
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
window.location = 'http://localhost/manage/card.php?id=' + data;
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
echo $id;
exit;

You indicate in the question that under certain conditions, you want a redirect.
To do that, you would want to alter your javascript to contain an if condition, and to watch for certain responses.
I would recommend modifying your responses to be json, so that you can pass back different information (such as a success status, as well as a redirect url, or other information you might want).
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
var response = $.parseJSON(data);
if (response.redirect) {
window.location = response.redirect_url;
} else {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
}
});
});
As for your add.php file, you'll want to change this to be something more like so:
$json = array(
'redirect' => 0,
'url' => '',
}
if (...condition for redirect...) {
$row = mysqli_fetch_array($result);
$id = $row['id'];
$json['redirect'] = 1;
$json['redirect_url'] = "Location: http://localhost/manage/card.php?id=$id";
}
echo json_encode($json);
die();

You seem to have a miss understanding of how AJAX works. Introduction to Ajax.
The reason why your redirect appears not to working is because an Ajax call doesn't directly affect your browser. It's a behind the scenes call.
To get the data out from the AJAX call you need to do something with the returned data.
success: function (data) {
$("input").val('Company Name');
$("form").hide();
//You need to do something with data here.
$("#myDiv").html(data); //This would update a div with the id myDiv with the response from the ajax call.
getInfo();
}

Related

Cannot read ob_flush() trough ajax

I have a code where I make an AJAX request at a certain file whenever I click a button, the request is as follows:
$("#syncDNS").click(function(){
$('#status').html("");
$('#status').addClass('loading');
function updateProgress(){
$.ajax({
type: 'POST',
url: 'index.php',
success: function(data){
$('#status').html(data);
}
});
}
$.ajax({
url: 'index.php?action=sync',
success: function (response) {
clearInterval(loop);
$('#status').removeClass('loading');
if(response){
$('#status').addClass('alert alert-warning').html("<h4>Aviso</h4>" + response);
}else{
$('#status').addClass('alert alert-success').html("<h4>Sucesso</h4>" + "DNS sincronizado com sucesso!");
}
}
});
updateProgress();
var loop = setInterval(function () {
updateProgress();
}, 1000);
});
In the code I make the request, and while I wait for it's success I keep running in a loop another function to update the progress of the first one.
And in my index.php file I have:
require_once(CONTROLLER_PATH . "ControleAutodns.php");
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
...
case 'sync':
$controller = ControleAutodns::getInstance();
$return = $controller->syncDNS();
exit($return);
break;
...
}
In the index I include my control file and call the PHP function, this php function is a loop, where I add some entries to a database:
public function syncDNS(){
...
foreach($result as $row) {
$current ++;
echo($current);
...
}
...
return $string;
}
The thing is, the requests are working as intended and the PHP function is also doing it's job, I just can't listen to the echo's in the syncDNS function, why is that? I also tried using ob_start(), ob_flush(), flush(), but nothing worked.
As I understand, the control file is included in the index, so anything echoed in there should be available trough an AJAX POST request.

Codeigniter - Page redirect not working after submitting button

I'm trying to insert and update data in my database using ajax to my controller. Now my data is inserting and updating precisely after I click the button. But my data on my view page is not updating. I need to refresh again the page to update my view and the success message to display
PS: It's firing sometimes, and sometimes not, Can't understand the behaviour
Below is my JS file for ajax
$('#triger').click(function(){
var btn_value = $('#triger').val();
var tenant_id = $('#tenant_id').val();
var calldisp_id = $('#calldisp_id').val();
var disposition_name = $('#disposition_name').val();
var disposition_code = $('#disposition_code').val();
var email = $.map($("#tags span"), function(elem, index){
return $(elem).text();
});
var myJsonString = JSON.stringify(email);
//alert(myJsonString);
if(btn_value == 'Create'){
$.ajax({
url:"<?php echo base_url();?>admin/call_disposition/create_email_dispo_dre",
method:"POST",
data:{email:myJsonString,
disposition_name:disposition_name,
disposition_code:disposition_code,
tenant_id:tenant_id},
dataType: 'json',
success:function(data){
},
});
}
else if(btn_value == 'Update'){
$.ajax({
url:"<?php echo base_url();?>admin/call_disposition/update_email_dispo_dre",
method:"POST",
data:{email:myJsonString,
disposition_name:disposition_name,
disposition_code:disposition_code,
calldisp_id:calldisp_id,
tenant_id:tenant_id},
dataType: 'json',
success:function(data){
},
});
}
});
Below is my Controller
public function create_email_dispo_dre($id){
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->update($id);
} else {
$data = array(
'tenant_id' => $this->input->post('tenant_id',TRUE),
'disposition_code' => $this->input->post('disposition_code',TRUE),
'disposition_name' => $this->input->post('disposition_name',TRUE),
'email' => $this->input->post('email',TRUE)
);
$this->calldisp_model->insert($data);
$this->session->set_flashdata('message', 'admin_faqs_success');
redirect('admin/call_disposition/update/'.$id);
}
}
In the ajax request for update:
In the success section:
success:function(data){
},
you need to call a page reload:
window.location.reload();
so your code becomes:
success:function(data){
window.location.reload();
},
In controller
you have to add
echo json_encode(array('success'=>'1')); instead of redirect('admin/call_disposition/update/'.$id); because you used datatype "json";
and change success function an ajax request Like
success:function(data){
if(data.success=='1'){
window.location.reload();
}
}
In codeigniter when you execute an Ajax call you can't redirect from the controller function. If you want to seemlessly update the page after clicking #trigger you have to echo the result in your controller
echo json_encode($html_you_want_to_display);
and then in your ajax success clause you need to update the div with the result from the echo by setting the innerHtml to the result. Hope this helps

Delete post using $.ajax

I am new to $.ajax and don't know so much and i have following button to delete user post by article ID
<button type="button" onclick="submitdata();">Delete</button>
When click this button then following $.ajax process running.
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
var datastring='post_id='+post_id;
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:datastring,
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
And delete.php is
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_GET['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
This code not working post not deleted. Please how do I do?
You likely want to not only match the "GET" you use in your PHP but also add the ID to the button
<button class="del" type="button"
data-id="<?php echo $userIdRow['post_id']; ?>">Delete</button>
using $.get which matches your PHP OR use $.ajax({ "type":"DELETE"
$(function() {
$(".del").on("click", function() {
$.get("delete.php",{"post_id":$(this).data("id")},
function(html) {
alert(html);
}
);
});
});
NOTE: Please clean the var
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Using ajax DELETE with error handling
$(function() {
$(".del").on("click", function() {
$.ajax({
url: "delete.php",
method: "DELETE", // use "GET" if server does not handle DELETE
data: { "post_id": $(this).data("id") },
dataType: "html"
}).done(function( msg ) {
$( "#log" ).html( msg );
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
In the PHP you can do
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$id = $_REQUEST["post_id"] ....
}
since you're sending a post request with ajax so you should use a $_POST iin your script and not a $_GET
here is how it sould be
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_POST['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
for the JS code
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:{"post_id":post_id},
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
here i've supposed thqt the give you the real id post you're looking for !!
The reason is pretty simple. You should change your request type to GET/DELETE instead of POST. In PHP you expect GET request but in AJAX you send POST request
Change:
type:"POST",
url:"delete.php",
data:datastring,
to
type:"DELETE",
url:"delete.php?" + datastring,
in PHP
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
$id = $_REQUEST["post_id"];
// perform delete
}
DELETE is actually the only valid method to delete objects. POST should create an object and GET should retrieve it. It may be confusing at first time but it's good practicet specially used in REST APIs. The other one would be UNLINK if you wanted to remove relationship between objects.
Follow #roberts advise and also:
You should have a way to handle errors eg.
to your ajax code add this:
error:function(e){
alert(e.statusText)// if you like alerts
console.log(e.statusText)// If you like console
}
You should also check your error logs. Assuming you use apache2 and linux
execute this in terminal:
tail -f /var/log/apache2/error.log
This gives you a very elaborate way to code. You also eliminate the problem of trial and error.

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Check all possible AJAX responses

I have an AJAX function which POST data to a PHP handler. I echo back either "success" or "failure" from PHP to determine if it was completed as intended. Unfortunately I am not used to JS/AJAX and have trouble finding documentation that answers my questions.
Do I need to JSON encode the response? I only check for .done() in my AJAX function, should I also check success and failed? My code inside of .done() which is just an alert box isn't working, despite the functionality in the PHP handler running without issue.
JS/AJAX:
<script type="text/javascript">
function powerSignal(device, signal)
{
var cfm = confirm("Do you wish to ___ the server?");
if (cfm==true)
{
$.ajax({ type: "POST", url: "https://domain.net/modules/power_functions.php", data: { device: device, 'power_signal': signal }}).done(function(result)
{
alert("success!");
});
}
}
</script>
PHP:
if ( isset($_POST["device"]) && isset($_POST["power_signal"]) )
{
$deviceid = $_POST["device"];
$signal = $_POST["power_signal"];
//API: Get Device Inventory
$url = 'http://domain.net/dp/api/set_device_power_status';
$fields = array('deviceid' => urlencode($deviceid), 'power_signal' => urlencode($signal));
$result = curl_get($url, $fields);
$json = json_decode($result);
$status = $json->{'status'};
if ($status == "success")
{
echo "success";
}
echo "failed";
}
the content of the result variable will be what the server sends back, you'll have to test it :
$.ajax({ type: "POST", url: "https://domain.net/modules/power_functions.php", data: { device: device, 'power_signal': signal }}).done(function(result)
{
if(result=='success'){
alert("success!");
}else{
alert("failure!");
});
To answer the comment below, here is how I do in my current project with a simple get request :
$.get( "/getResult/"+data, function( results ) {
$('.popin_content').html('<p>Vos documents ont bien été créés :</p><br/><ul><li>Plan PDF</li><li>Devis PDF</li></ul>');
});

Categories

Resources