So another problem here. I think this problem is not hard to solve. But I do not have a lot of experiences with Ajax yet.
My problem is I want to redirect after success. For better imagination, I attach only if statement from login code here.
if ($row['odd_zam'] == 1) {
$_SESSION['name'][0] = $row['skratka_titul']." ".$row['meno_zam']." ".$row['priezvisko_zam']." ".$row['skratka_titul'];
$_SESSION['name'][2] = 1; // 1 = otk
$_SESSION['name'][3] = $row['prava_zam'];
$n = header('Location: otk/index-test.php');
echo $n;
}
if ($row['odd_zam'] == 2) {
$_SESSION['name'][0] = $row['skratka_titul']." ".$row['meno_zam']." ".$row['priezvisko_zam']." ".$row['skratka_titul'];
$_SESSION['name'][2] = 2; // 2 = eir
$_SESSION['name'][3] = $row['prava_zam'];
$n = header('Location: eir/index.php');
echo $n;
}
if ($row['prava_zam'] == 3) {
$_SESSION['name'][0] = $row['skratka_titul']." ".$row['meno_zam']." ".$row['priezvisko_zam']." ".$row['skratka_titul'];
$_SESSION['name'][2] = 3; // 3 = spravca
$_SESSION['name'][3] = $row['prava_zam'];
$n = header('Location: zam/index.php');
echo $n;
}
And in my ajax code i do this:
success: function(data){
window.location.href = data;
}
But a problem is this code logs me but it do not redirect me.
I tried window.location.href = data.n; but this do not work.
Inside the successs function you can reload the same page by using location.reload(); Javascript function.
success: function(data){
location.reload();
}
If however you want to reload to a different page then mention the page address like so :
success: function(data){
window.location.href = 'path to reload file';
}
You have a bit of confusion here.
header is used to send a raw HTTP header.
Additionally, it does not return a value, so your $n will always be null.
You have to change your code:
if ($row['odd_zam'] == 1) {
$_SESSION['name'][0] = $row['skratka_titul']." ".$row['meno_zam']." ".$row['priezvisko_zam']." ".$row['skratka_titul'];
$_SESSION['name'][2] = 1; // 1 = otk
$_SESSION['name'][3] = $row['prava_zam'];
$n = "otk/index-test.php";
echo $n;
}
if ($row['odd_zam'] == 2) {
$_SESSION['name'][0] = $row['skratka_titul']." ".$row['meno_zam']." ".$row['priezvisko_zam']." ".$row['skratka_titul'];
$_SESSION['name'][2] = 2; // 2 = eir
$_SESSION['name'][3] = $row['prava_zam'];
$n = "eir/index.php";
echo $n;
}
if ($row['prava_zam'] == 3) {
$_SESSION['name'][0] = $row['skratka_titul']." ".$row['meno_zam']." ".$row['priezvisko_zam']." ".$row['skratka_titul'];
$_SESSION['name'][2] = 3; // 3 = spravca
$_SESSION['name'][3] = $row['prava_zam'];
$n = "zam/index.php";
echo $n;
}
In this way you can do this:
success: function(data){
window.location.href = data;
}
try this
success:function(data) {
window.location.href = 'url?param=' + data
}
Related
I wrote different code (at least twice) where Ajax is supposed to change an innerHTML-value by a database call (GET). While the first requests succedes in a 100 % of the time (changing a value in the database) the next commands that extracts the new Information to update the HTML-file fails in about 20-30 % of the time, receiving the wrong response from the xerver (an old value).
I tried tracking the error but can't find it since it only appears sometimes after a call. The following code is just the relevant part of my problem.
<p>I like <b><span id="numCom"><?php echo liked_comments(); ?></span></b> comments.</p>
// Each comment has a likeComment and CountComments function that triggers the Ajax:
let likeIcon = document.getElementsByClassName("like-icon");
for(let i = 0; i < likeIcon.length; i++){
likeIcon[i].addEventListener("click", likeComment);
likeIcon[i].addEventListener("click", countComments);
}
function likeComment(){
let child = this.children[0];
let mainID = this.parentElement.parentElement.id;
url = "ajax/like_comment.php";
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function(){
if(this.status == 200){
let result = this.responseText;
if(result == "t"){
child.classList.remove("red-text");
} else if (result == "f") {
child.classList.add("red-text");
}
}
}
xhr.send("com_id=" + mainID);
}
function countComments(){
let numCom = document.getElementById("numCom");
let xhr = new XMLHttpRequest();
let url = "ajax/count_liked_comments.php";
xhr.open("GET", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onload = function(){
if(this.status == 200){
numCom.innerHTML = this.responseText;
}
}
xhr.onerror = function(){
console.log("Error");
};
xhr.send();
}
// In the php-files these functions are executed:
function like_comment($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
if($l == 0){
// UPDATE TO 1
$query = "UPDATE comments SET liked = 1 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
} else if($l == 1) {
// UPDATE TO 0
$query = "UPDATE comments SET liked = 0 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
}
}
function is_liked($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
return $l;
}
function liked_comments(){
global $db;
$query = "SELECT comment_id FROM comments WHERE liked = 1";
$result = mysqli_query($db, $query);
return mysqli_num_rows($result);
}
The code ist just a demonstration and not really neccessary to understand the problem. In another project. I change the value of a table row via Ajax and afterwards want to update the result. This only happens in about 70 to 80% of the time. All the other times and old value is returned
When I try to parse a reponseText using JSON.parse I get this error:
Uncaught SyntaxError: Unexpected token < in JSON at position 0 at
JSON.parse () at XMLHttpRequest.xhr.onreadystatechange
(index.js:75)
Any time i run the code below.
javascript/ajax code
function calculateMeasurements() {
clearResult();
clearErrors();
var form = document.getElementById("measurement-form");
var action = form.getAttribute("action");
// gather form data
var form_data = new FormData(form);
for ([key, value] of form_data.entries()) {
console.log(key + ': ' + value);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', action, true);
// do not set content-type with FormData
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
var json = JSON.parse(result);
if (json.hasOwnProperty('errors') && json.errors.length > 0) {
displayErrors(form, json.errors);
} else {
postResult(json.volume);
}
}
};
xhr.send(form_data);
}
var button = document.getElementById("ajax-submit");
button.addEventListener("click", calculateMeasurements);
})();
process.php
<?php
function is_ajax_request(){
return $_SERVER["HTTP_X_REQUESTED_WITH"] && $_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest";
}
$length = isset($_POST['length']) ? (int) $_POST['length'] : '';
$width = isset($_POST['width']) ? (int) $_POST['width'] : '';
$height = isset($_POST['height']) ? (int) $_POST['height'] : '';
$errors = [];
if(empty($length)){$errors[] = "length";}
if(empty($width)){$errors[] = "width";}
if(empty($height)){$errors[] = "height";}
if(!empty($errors)){
$result_array = array('errors' => $errors);
echo json.encode($result_array);
exit;
}
$volume = $length * $width * $height;
if(is_ajax_request()) {
echo json.encode(array('volume' => $volume));
} else {
exit;
}
?>
I noticed this error anytime I use the JSON.parse on result variable gotten from the ajax response.
i dont think their is anything wrong with your javascript code. please try using the php function properly. it should like this
echo json_encode(array('volume' => $volume));
echo json_encode($result_array);
AND NOT :
echo json.encode(array('volume' => $volume)); // json.encode as you have used in your code is wrong.
echo json.encode($result_array) // json.encode as you have used in your code is wrong.
it should work properly once this change is made
Ajax
<script type="text/javascript">
var stopTime =0;
var scoreCheck = function ()
{
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/checkScoreRoundOne',
success:function(output){
if(output !='Instruction'){
console.log(output);
clearTimeout(scoreCheck);
}
else
console.log(output);
stopTime = setTimeout(scoreCheck, 1000);
}
});
}
stopTime = setTimeout(scoreCheck,1000);
</script>
Controller
public function checkScoreRoundOne(){
$id = $this->session->userdata('userID');
$battleID = $this->lawmodel->getBattle($id);
foreach($battleID as $row){
$Rscore = $row->requestedScore;
$Cscore = $row->challengerScore;
if($Cscore == '1'){
$rID = $this->lawmodel->getID($row->challengerID);
foreach($rID as $row){
echo $row->username."Got the correct answer";
}
}
else if($Rscore == '1'){
$cID =$this->lawmodel->getID($row->requestedID);
foreach($cID as $row){
echo $row->username."Got the correct answer";
}
}
else
echo "Instruction";
}
}
Im confused in the code above
In ajax, why when the output !='Instruction' it will display "Instruction" and when the output == 'Instruction' it will display $row->username got the correct answer.
And how can i stop the setTimeout when the Cscore == 1 or Rscore ==1?
I think cleartimeout will not just stop the setTimeout..
Plss help...Im new in ajax..
Im using codeigniter
About the clearTimeout:
clearTimeout(stopTime);
I have code to calculate distance place to another place using google distance matrix API, but for free its limited just 100 elements per query. So I make code for solve the problem using looping code such as for elements , My code is PHP, javascript , and I parse latitude and longitude data from MySql. Anyone know some error of my code below ? because It don't appear anything if I click calculate button. Actualy I have modifie the code from this URL https://google-developers.appspot.com/maps/documentation/javascript/examples/distance-matrix , And this is my Code :
function hitung (){
service = new google.maps.DistanceMatrixService();
for (m = 0 ; m < l-80 ; m++ ){
asal = originarray[m];
for (n = 0 ; n < l-80 ; n++ ){
tujuan = destarray [n];
calculateDistances();
}
}
}
function calculateDistances() {
//var s = 0;
//for (m = 0 ; m < l-80 ; m++ ){
// asal = originarray[m];
//for (n = 0 ; n < l-80 ; n++ ){
//servicearray[s] = new google.maps.DistanceMatrixService();
//tujuan = destarray [n];
service.getDistanceMatrix(
{
//origins: [origin1, origin2],
// destinations: [destinationA, destinationB],
origins: asal,
destinations: tujuan,
//origins: originarray,
//destinations: destarray,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
// s++;
//}
// }
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
//outputDiv.innerHTML = '';
// deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
// addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
// addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: peta,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
Check if you're receiving a response from Google by logging the response...
function callback(response, status) {
console.log(response);
}
I am using window.onbeforeunload in my javascript.
This works perfectly in IE but is not triggered in Firefox.
I checked on different links in stackoverflow.... In it I read that window.onbeforeunload is not supported by firefox. Is this true?
If yes, can you please tell me a different way to call app.deleteAccount(key) on close of browser. Here is my javascript. Please look at the deleteFile() and dontDeleteFile() methods.
<script type="text/javascript">
//Event handler for body onload
function confirmDeleteFile(){
var secured =document.r_form.Secure[1].checked;
alert("confirmDeleteFile : "+secured);
if(secured){
var agree=confirm("Are you sure you wish to continue?");
if (agree){
//document.form1.submit();
return true;
}
else
return false ;
}
// submitForm();
return true;
}
function deleteFile() {
alert('inside deleteFile() but outside window.onbeforeunload');
window.onbeforeunload = function(){
var key = DOMAIN+'::' + elem('userName').value;
alert('inside deleteFile()');
app.deleteAccount(key)
alert('Unloading!');
}
}
function dontDeleteFile() {
alert('inside dontDeleteFile() but outside window.onbeforeunload');
window.onbeforeunload = function(){
alert("Not deleting");
}
}
function validateFormOnSubmit(theForm) {
var reason = "";
var userName = theForm.username.value;
var pin = theForm.pin1.value;
var PAM = theForm.pam.value;
var organization = theForm.organization.value;
//reason += validateUsername(theForm.username);
reason += validateEmpty(theForm.pam);
reason += validatePinMatch(theForm.pin1,theForm.pin2);
reason += validatePin(theForm.pin1,theForm.pin2);
if (reason != "") {
if(!confirmDeleteFile()){
return false;
}
alert("Some fields need correction:\n" + reason);
return false;
}
else{
if(!confirmDeleteFile()){
return false;
}
<% String url = request.getServerName().toString();
int port = request.getServerPort();
String contextPath = request.getContextPath();
%>
var servlet = "arcotebank.az"; //AroctEBanking Servlet
var url = BASE_URL + '/' + servlet;
var query = 'lang=en&reqid=1&version=1.1';
query += '&device=' + urlEncode(navigator.userAgent);
query += '&uid=' + urlEncode(userName);
query += '&code=' + urlEncode(PAM);
query += '&pin=' + urlEncode(pin);
query += '&usePin=' + usePin+'&method=arcotOTPEnroll&organization='+organization;
//alert("url=>"+url + '?' + query);
var xml = app.openUrl(url + '?' + query) + '';
//alert("xml=>"+xml);
if(appError()){
alert("applet error");
}
var domain = getDomain(url);
app.provisionAccount(domain, xml);
if(appError()){
alert("applet error");
}
var acc = app.getAccount(DOMAIN + '::' + userName);
if(acc!=null){
<%String formSubmitAction1 =
URLEncoderDecoder.encodeURL(
formAction,
"Action.2FA.Arcot.Navigation.LogoutActionCalled=Y",cm);%>
theForm.action ='<%=formSubmitAction1%>';
var secured =document.r_form.Secure[1].checked;
alert("line 131 "+secured);
if(secured){
deleteFile();
}else{
dontDeleteFile();
}
theForm.submit();
}else{
document.getElementById("error").innerHTML = "Failed to Create ArcotOTP";
}
}
}
function resetForm(){
var form = document.forms[0];
form.username.value = '';
form.pam.value = '';
form.pin1.value = '';
form.pin2.value = '';
}
function validateUsername(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a username.\n";
} else if ((fld.value.length < 5) || (fld.value.length > 15)) {
fld.style.background = 'Yellow';
error = "The username should contain more than 4 characters.\n";
} else if (illegalChars.test(fld.value)) {
fld.style.background = 'Yellow';
error = "The username contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function validateEmpty(fld) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "You didn't enter Personal Assurance Message \n"
} else {
fld.style.background = 'White';
}
return error;
}
function validatePin(pin1,pin2){
var error="";
if(pin1.value!=pin2.value){
pin1.style.background = 'Yellow';
pin2.style.background = 'Yellow';
error += "Pin numbers dont match\n";
//alert("Pin numbers dont match");
}
return error;
}
function validatePinMatch(pin1,pin2){
var error="";
if(pin1.value==""){
//elem('otp').style.background = 'Yellow';
pin1.style.background = 'Yellow';
error += "Pin number cannot be empty\n";
//alert("Pin number cannot be empty");
}
if(pin2.value==""){
//elem('otp').style.background = 'Yellow';
pin2.style.background = 'Yellow';
error += "Confirm Pin number cannot be empty\n";
//alert("Pin number cannot be empty");
}
return error;
}
</script>
Note that in Firefox 4 and later the returned string is not displayed to the user. See Bug 588292.
https://developer.mozilla.org/en/DOM/window.onbeforeunload
Maybe this is what's causing your problem in part. Also the example on the page might be better suited for cross-browser compatibility?
window.onbeforeunload = function (e) {
var e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Any string';
}
// For Safari
return 'Any string';
};
window.onbeforeunload is supported by Firefox and all major browsers. It should be implemented as a function that returns a string, which will be used as the message in the confirmation dialog.