Cannot read ob_flush() trough ajax - javascript

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.

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

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

Unable to get response from php return in ajax request

I am trying to access the output from php code to jquery ajax. But I donot know why It is returning me whole page html including the result. can anybody please tell me about it. In firefox console Its show me response of page html including php result. But In jquery code console.log does not hit.
Here is jquery code
function getprofile()
{
$.ajax({
url: 'Userpage/get_profile',
//data: {'title': title}, change this to send js object
type: "post",
dataType: 'json',
data: {'userid': 1},
success: function(data) {
console.log(data);
}
});
}
My php code
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Userpage extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("session");
$this->load->model("Userpage_model");
$this->load->view('Userpage_view');
}
public function index()
{
}
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit;
}
}
?>
Please review the code and tell me where I am going wrong
Thanks
Use exit
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit; // use exit here
}
EDIT
PHP uses a special function called header() for setting properties of the page during rendering.
you need to return from your function, using exit is fine but it's not a good practice
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
return json_encode($data['comments']);
}
You are using CI. From this ajax call:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
}
});
you expect an ajax call is being made to get_profile action inside Userpage controller, that probably will return:
{
"comments": [
{ ... },
{ ... },
{ ... },
...
]
}
which will be logged in browser console.
But you get unexpected result, right?
I think, your ajax call results in error. To prove this, modify your ajax call:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// add this function to logs error
console.log(textStatus + ': ' + errorThrown);
}
});
Now, if the ajax call results in error, you can see the error in browser console. I am pretty sure you will get error: Not Found in browser console.
You are using CI, the URL will be something like:
http://<something>/index.php/site/index
In this page, if you make ajax call with url Userpage/get_profile, what the browser really does is make ajax call to:
http://<something>/index.php/site/index/Userpage/get_profile
instead of what you expect:
http://<something>/index.php/Userpage/get_profile
To solve this, you must change the value of url in your ajax call, to point the correct URL above.
By using CI, the absoulte URL above can be generated with the help of site_url() function:
site_url('Userpage/get_profile')
I usually print this URL somewhere in HTML, and retrieve it from javascript during ajax call.

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).

Header wont redirect when passedthrough ajax

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();
}

Categories

Resources