Recreate URL using JavaScript - javascript

Browser Current URL is:
http://localhost/a_project/index.html
I have a Ajax code calling a PHP file who checks the login details and return a unique id if found in database else returns false. On Ajax success i want to create a URL and redirect the browser to that. I tried following code:
$.ajax({
url: 'site_api/user_login.php',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function(res) {
if (res > 0) {
var pathArray = window.location.pathname.split('/');
window.location = pathArray[1] + "/my%20page.html?id=" + res;
} else {
$('#login_error').html('Invalid Credentials. Please try again.');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
But it always result in following URL:
http://localhost/a_project/a_project/my%20page.html?id=20
Instead it should be routed to:
http://localhost/a_project/my%20page.html?id=20
I have a feeling that i am missing something but not sure what.

try this:
window.location = window.location.origin + '/a_project/my%20page.html?id=20' + res;

Why do you need to generate the URL?
As you site root is http://localhost/a_project/, the pages index.html and my page.html are in the same directory. You can use relative path.
Just use "my page.html?id=" + res
And I would strongly recommend NOT to have spaces in URL.
$.ajax({
url: 'site_api/user_login.php',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function(res) {
if (res > 0) {
location.href = "my%20page.html?id=" + res;
} else {
$('#login_error').html('Invalid Credentials. Please try again.');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});

Add A Base URL in the javascript then concatinate with the original Url
var baseUrl="http://example.com/";
$.ajax({
url: 'site_api/user_login.php',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function(res)
{
if(res > 0){
var pathArray = window.location.pathname.split( '/' );
window.location =baseUrl+ pathArray[1] + "/my%20page.html?id="+res; //changes Here
} else {
$('#login_error').html('Invalid Credentials. Please try again.');
}
},
error: function(xhr, ajaxOptions, thrownError)
{
alert (xhr.status);
}
});

Related

Parse json from php in jQuery

I have this code:
$.ajax({
url: '{{ route('frontend.validation') }}?sex=' + $(".sex").val() + '&date=' + $(".date").val() + '&hour=' + $(".hour").val()+ '&track=' + $(".track").val(),
type: 'get',
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
success: function (response) {
$.each(response, function (key, value) {
console.log(response);
})
}
});
In result I have:
{"status":"ok","message":"Twoja rezerwacja zosta\u0142a zrealizowana"}
in console I have:
[Log] {status: "ok", message: "Twoja rezerwacja została zrealizowana"}
(projekt1.test, line 284) [Log] {status: "ok", message: "Twoja
rezerwacja została zrealizowana"} (projekt1.test, line 284)
I need check my status.
If it's "ok" - then message I want show in alert box.
When status = "error" them I want show alert with "Sorry, we have error with yours reservation".
How can I make it?
u have already json object so you don't need to parse. Remove each method ,it uses keys count so you get alert two times .
success: function (response) {
if(response.status==="ok"){
alert("ok")
}
else if(response.status==="error"){
alert("error")
}
}
try this
$.ajax({
url: '{{ route('frontend.validation') }}?sex=' + $(".sex").val() + '&date=' + $(".date").val() + '&hour=' + $(".hour").val()+ '&track=' + $(".track").val(),
type: 'get',
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
success: function (response) {
$.each(response, function (key, value) {
var obj = JSON.parse( response );
console.log(obj['status'])
})
}
});
From Mozilla documentation
The JSON.parse() takes the string text input and returns the object corresponding to the given JSON text.
Use JSON.parse(response) and then read the index "status" of the object.
The question is already answered HERE LINK
$.ajax({
success: function(response){
$.each(response, function (key, value) {
if(response.status==="ok"){
alert("Twoja rezerwacja została zrealizowana");
}
else if(response.status==="error"){
alert("Sorry, we have error with yours reservation");
}
})
},
error: function(response) {
alert("Sorry, we have error with yours reservation");
}
});
return False;
....

jQuery Ajax raising TypeError

I'm having quite a hard time to figure this out. I would like to know if TypeError is caused by the second AJAX call (or the osmtogeojson.js)?
I made sure that my data in the first success function is not null by alerting it.
function sendQueryData(url, query){
url =url.replace('query' , query);
if (query === ""){
alert("City Input Required");
}else{
$.ajax({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
type: "POST",
url: "/search/pass/",
data: {
'query' : query
},
success: function(data){
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: url,
data: {
'feature': osmtogeojson(data)
},
success: function (data) {
window.location.href = url
}
});
}
});
}
}
This is the what the browser console outputs:
TypeError: e.elements is undefined
[Learn More]
osmtogeojson.js:4:2503
n http://localhost:8000/static/js/osmtogeojson.js:4:2503
u http://localhost:8000/static/js/osmtogeojson.js:4:14818
success http://localhost:8000/:235:36
i https://ajax.googleapis.com/ajax/libs/jquery/3.2.1
/jquery.min.js:2:28012
firewith https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:2:28783
A https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:4:14033
c/< https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:4:16323

Continuous ajax calls makes application crash

I have a html application which contains 4 ajax calls which runs continously every 2 seconds back to back. The objective is to read new and fresh data fron the db continuously and seamlessly.
function messagesreceived(){
var queryString = "XXXXXXXXX";
$.ajax({
url:queryString,
'Content-Type':'application/json',
method:'GET',
dataType:'json',
cache: false,
success:function(data){
displaymessages(data);
rendermessagesreceived();
},
complete: function(xhr,status){
setTimeout(messagesreceived,2000);
},
error: function(xhr,status){
if(xhr.status == 0){
footerText.setText("NETWORK DISCONNECTED");
}else{
footerText.setText("Something went wrong! Please reload the page!");
}
}
});
}
function loadreadings() {
var queryString = "XXXXXXX";
$.ajax({
url: queryString,
'Content-Type': 'application/json',
method: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
mapreadings(data);
plotreadings();
},
complete: function(xhr, status) {
setTimeout(loadreadings, 2000);
},
error: function(xhr, status) {
if (xhr.status == 0) {
footerText.setText("NETWORK DISCONNECTED");
} else {
footerText.setText("Something went wrong! Please reload the page!");
}
}
});
}
function loadreadings2() {
var queryString = "XXXXX";
$.ajax({
url: queryString,
'Content-Type': 'application/json',
method: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
initiate(data);
footerText.setText("");
},
complete: function(xhr, status) {
setTimeout(loadreadings2, 2000);
},
error: function(xhr, status) {
if (xhr.status == 0) {
footerText.setText("NETWORK DISCONNECTED");
} else {
footerText.setText("Something went wrong! Please reload the page!");
}
}
});
}
Its runs fine first 15/20 mins and then crashes. The below link is the screenshot of the error.
can anyone please suggest how to resolve this. Its a very critical issue that I have been facing from past 15 days. Googled for the solution but no luck.
Appreciate your time and help.
Thanks.

jQuery - failing to submit username password and causing 401 unauthorized

When i open using the Google chrome browser this url http://www.site.nl/a/b/c/d/e?niss=f, it first ask for username password:
Manually when i put the username password i get some data.
Now, using jQuery how can i submit that username password? following is not working, always after submit its failing with "401 unauthorized"
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic Username1:password1234"
},
data: '{ "test" }',
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
Please try following code
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
data: '{ "test" }',
beforeSend: function(xhr)
{
xhr.setRequestHeader('Authorization', make_base_auth("Username1", "password1234"));
},
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
function make_base_auth(user,password)
{
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
} // ends

jQuery does not work in IE11, but works in Chrome

I have problem with jQuery. When I upload image in Chrome it performs the AJAX successfully and I am able to update the page with the response data. But in IE 11 and Firefox it does not. The code:
$(".newfoto").on('submit', (function(e) {
$("#mailresult").html('<img src="themes/standart/iconss/spin1.gif" alt="loading..." /><p>Please, wait...</p>');
e.preventDefault();
$.ajax({
url: "dataok.php?act=foto",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#mailresult").html(data);
setTimeout(function() {
$("#mailresult").empty();
}, 2000);
var imgTag = '<img src="image.php?imgid=' + escape($('.myphoto').attr('id')) + '" />';
$('.myphoto').html(imgTag);
},
error: function() {}
});
}));
The correct way to prevent the form from submitting and reloading the page is to use a return false; at the end of the submit function. This will also replace e.preventDefault(); in your code.
Also, FormData is not supported on all browsers. See https://stackoverflow.com/a/2320097/584192. You may need to detect and workaround this.
$(".newfoto").on('submit', function(e) {
$("#mailresult").html('<img src="themes/standart/iconss/spin1.gif" alt="loading..." /><p>Please, wait...</p>');
$.ajax({
url: "dataok.php?act=foto",
type: "POST",
data: (typeof FormData === 'function') ? new FormData(this) : $(this).serialize(),
contentType: false,
cache: false,
processData: false,
success: function(data) {
// success
},
error: function(jqXHR, status, error) {
console.log(error);
}
});
return false;
});

Categories