Make page refresh if successful login with ajax/jquery - javascript

Ajax code
$("#login_btn").click(function() {
var url = "core/login.php";
$.ajax({
type: "POST",
url: url,
data: $("#sr").serialize(),
success: function(data) {
var responseData = jQuery.parseJSON(data);
$('.oops').html('<div class="error">'+responseData.oops+'</div>');
alert(responseData.good);
if(responseData.good === 1) {
alert(good)
location.reload();
}
}
});
});
Php code if everything passes
else {
$_SESSION['id'] = $login;
$good = 1;
exit();
}
How come it's not freshing the page with location.reload? Should I be using .done .try?

Dont refresh, the whole idea of using ajax is that you dont need to.
You can set your sessions in the ajax php script and pull new content based on the change in session.
That being said, you are missing a ';' at
alert(good);

Related

Cross-Domain Ajax POST request with php proxy

First of all, I have already read this answer, which is to do the Cross-Domain Ajax GET request with php proxy. But what I need is a Ajax POST request.
So in my project, long time ago. Someone wrote this php file and together the ajax call in JavaScript, those are mean to solve the cross origin problem and which works really good! So I never think about to understand this, because I basiclly just need to change the url in the JavaScript and don't need to understand how this Ajax call works together with php.
PHP:
<?php
$nix="";
$type=$_GET['requrl'];
if ($_GET['requrl'] != $nix) {
$file = file_get_contents($_GET['requrl']);
}
elseif ($_POST['requrl'] != $nix) {
$file = file_get_contents($_POST['requrl'], false, $_POST['data']);
}
else {
$file = "false type";
}
echo $file;
?>
JavaScript:
var url = "https://XXXXXXXXXXXXXX";
url = encodeURI(url);
var useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
var ajaxProperties = {
type: 'GET',
data: data,
url: ajaxUrl,
cache: false
};
res = jQuery.ajax(ajaxProperties).done(function(res) {
// do something with the result here
})
So what I need to do is just take the same ajax GET request (copy and paste in JS) and just replace the url every time ==> job done!
Now, the first time I need to do a ajax POST request to send a xml file to the server, the server will do some calculate on it and give me a response.
I tested first with the POSTMAN and everything works fine, but when I switch to my real project. I become the Cross origin problem. So I think If I could do something to the already existing php and js, so I can solve the cross origin problem.
I tried this in my JavaScript but I got only the "false type" as antwort
function sendWPSRequest(xml) {
var url = "https://XXX.XXX.XXX.XXX:XXXX/wps";
useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url, data: xml} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
$.ajax({
type: "POST",
url: ajaxUrl,
dataType: "text",
contentType: "application/xml",
data: data,
success:function (response) {
console.log('POST success: ', response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("POST", textStatus, errorThrown);
}
});
}
Can someone help me a little bit to understand what the php is doing here and what should I do to modify the php and JS.

Not receiving data from ajax to php

I want to send data from javascript to another php page where I want to display it. I found that I need to use Ajax to pass the data to php so I tried myself.
My file where is the javascript:
$('#button').on('click', function () {
$.jstree.reference('#albero').select_all();
var selectedElmsIds = [];
var selectedElmsIds = $('#albero').jstree("get_selected", true);
var i = 0;
$.each(selectedElmsIds, function() {
var nomenodo = $('#albero').jstree('get_selected', true)[i].text;
//var idnodo = selectedElmsIds.push(this.id);
var livellonodo = $('#albero').jstree('get_selected', true)[i].parents.length;
//console.log("ID nodo: " + selectedElmsIds.push(this.id) + " Nome nodo: " + $('#albero').jstree('get_selected', true)[i].text);
//console.log("Livello: " + $('#albero').jstree('get_selected', true)[i].parents.length);
i++;
$.ajax({
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo
},
success: function(data)
{
$("#content").html(data);
}
});
});
});
I want to send the data to another php page which consists of:
<?php echo $_POST["namenodo"]; ?>
But when I try to go to the page there's no data displayed.
This is a very basic mistake I think every beginner (including me) does while posting a data using ajax to another php page.
Your ajax code is actually posting the data to lamiadownline.php (if you are using the variables correctly) but you can't get that data by simply using echo.
Ajax post method post data to your php page (lamiadownline.php) but when you want to echo the same data on the receiver page (lamiadownline.php), you are actually reloading the lamiadownline.php page again which makes the $_POST["namenodo"] value null.
Hope this will help.
First of all you won't be able to see what you have post by browsing to that page.
Secondly, is this
<?php echo $_POST["namenodo"]; ?>
in the current page?
Otherwise, specify the url
$.ajax({
url: "lamiadownline.php",
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo},
success: function(data) {
$("#content").html(data);
}
});
//try this
$.ajax({
type: "POST",
url:"Your_php_page.php"
data: { namenodo: nomenodo levelnodo: livellonodo},
success: function(data)
{
$("#content").html(data);
}
});

Ajax change php variable

I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});

Returning html as ajax response

I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download the file. Chrome console shows
Resource interpreted as Document but transferred with MIME type application/text/HTML
has me confused because I use the same code in another page and it works fine.
This is my Jquery script
$("#addpaymentform").submit(function (event) {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
data: formdata,
url: baseurl + 'sales/add_payment',
success: function (data, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
$('#paymets').html();
$('#payments').html(data);
$('#addpaymentform').each(function() { this.reset() });
}
if (ct.indexOf('json') > -1) {
$("#Mynavbar").notify(
data,
{position: "bottom center"}
);
$('#addpaymentform').each(function() { this.reset() });
}
}
});
event.preventDefault(); // this will prevent from submitting the form.
});
and this is my controller
function add_payment()
{
$this->form_validation->set_rules('fpay', 'Type of payment', 'trim|required|alpha');
$this->form_validation->set_rules('payment', 'Payment', 'trim|numeric');
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
header('Content-type: application/json');
echo json_encode(validation_errors());
} else {
$fpay = filter_var($this->input->post('fpay'), FILTER_SANITIZE_STRING);
$payment = filter_var($this->input->post('payment'), FILTER_SANITIZE_STRING);
if(isset($_SESSION['payments'][$fpay]))
{
$temp = $_SESSION['payments'][$fpay] + $payment;
$_SESSION['payments'][$fpay] = $temp;
header('Content-type: application/html');
echo $this->_loadpaymentcontent();
}
}
}
function _loadpaymentcontent() {
$this->load->view('payment_content');
}
Hope someone can point me in the right direction I've been stuck on this for 2 days.
Thanks everyone.
I had the same problem and i successfully solved it by putting an exit; after the value which is returned to the ajax call in the controller method.
In your case it will be:
echo $this->_loadpaymentcontent();
exit;
What exit does here is it limits the returned value to the value which should be returned to the ajax call and exits before the html is appended to the returned value.
This is what is obvious per the effect it produces.
Yo need to set up your AJAX.
$.ajax({
type : 'POST',
url : baseurl + 'sales/add_payment',
dataType : 'html', // Will set the return type of the response as AJAX.
... Keep rest of the code same.

redirect page using ajax & jquery (php)

i want to redirect from page a to page profile and in between there is a post session on them. in this case let's say the data is variable $name in string. so far my code is like this on page a
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
//the ajax script
$.ajax({
type: 'POST',
url: 'b.php',
data: 'result='+$name,
success: function() {
window.location.href = "profile.php"; // replace
}
});
});
and on page b the code is:
<?php echo $_POST['result']?>
the outcome should be the value from result in which determined on page a.
but so there is an error message saying unidentified index. so where am i doing wrong?
Could it be, that your data parameter is wrong?
I have my ajax calls as folowing:
jQuery.ajax({
type: "POST",
url: "b.php",
data: {
result: $name
},
success: function() {
window.location.href = "profile.php"; // replace
}
});
It is a new request after the redirect. In order to access the result you need to sotre it in som kind of session or pass it again.
You can pass it like this, then it will be in $_GET
success: function(data) {
window.location.href = "profile.php?result="+data; // replace
}

Categories