jQuery Ajax - Wrong response - javascript

I have a problem with jQuery ajax function:
var arrayIdEq = JSON.stringify(iditem);
$.ajax({
type: "POST",
url: "index.php",
dataType : 'text',
contentType: 'application/json; charset=utf-8',
data: {
arrayIdEq : arrayIdEq
},
success: function(answer) {
alert(answer);
},
complete: function() {
},
error: function(jqXHR, errorText, errorThrown) {
alert(jqXHR+" - "+errorText+" - "+errorThrown);
}
});
"arrayIdEq" contains number from 0 to 7, or string "EMPTY".
PHP code:
elseif(isset($_POST['arrayIdEq'])){
$answer = "my_answer";
return $answer;
After request, when success response come, alert show up... but here's the problem. Instead of "$answer" value, alert contains... HTML code from my main page!
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Medivia</title>
</head>
<body>
<h1>Medivia</h1>
<form action="index.php" method="POST">
<label>E-mail:<br><input type="text" name="mail" required></label>
<br>
<label>Hasło:<br><input type="password" name="pass" required></label>
<br>
<button name="login">Zaloguj się</button>
</form>
</body>
</html>
I have no idea what happend here. Could anybody explain to me what happend there? What did i do wrong?

Your answer variable in the success function will contain the complete output of your php script.
So when you call index.php and you do:
elseif(isset($_POST['arrayIdEq'])){
$answer = "my_answer";
return $answer;
}
The script will only exit if the return statement is called from the main script (not from within a function) but the output will be the output generated by the script until that point.
Your script should output - and not return - only what you want returned to the javascript.
Probably a separate script for ajax requests will be a more convenient solution than using the index.php file you use to build the complete page.

Related

javascript eventlistener autoincrements

I'm building a dashboard with multiple eventlisteners and AJAX, which transfers data back and forth to a Python backend. It works fine the first time. The 2nd time I click the eventlistener function, I get two responses... the third time 3... I can reset it by reloading the page. So I assume that somehow each time the AJAX comes back the eventlistener registers again. I've done a bunch of searching and can't find a similar problem. Here's the javascript code (including the google map api that I'm passing back to the server).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link href="../static/css/bootstrap.css" rel="stylesheet">
<link href="../static/css/drunken-parrot.css" rel="stylesheet" type="text/css">
<link href="../static/css/jquery.ui.core.min.css" rel="stylesheet" type="text/css">
</head>
<div id="leftCol" class="bodyx">
<form role="form">
<placebutton class="btn btn-lg btn-primary btn-block" type="button" id="placebutton">Save</placebutton>
</form>
</div>
<script type="text/javascript">
function sendplace() {
$('placebutton').click(function() {
pete = ({"firstName":"John"});
console.log("Test");
$.ajax({
url: '/new_place2',
data: (pete),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(response) {
console.log(response);
},
});
});
};
var placebutton = document.querySelector("placebutton");
placebutton.addEventListener("click", sendplace, false);
console.log("addEvent");
</script>
</body>
</html>
I've whittled the file down thinking there might be some interference - I can't find anything - the entire file is here. It still has the two problems - 1 - first click doesn't do anything, and 2 - it sends one more loop every time. Hopefully this is easier to see... Thanks again.
I can't really see the context, but clearly, you're attaching the listener each time ajax is done. Try replacing this:
placebutton.addEventListener("click", sendplace, false);
with this
placebutton.removeEventListener("click",sendplace);
placebutton.addEventListener("click", sendplace, false);
Mind you that this is not a very clean way to fix it. You should really figure out why placebutton.addEventListener is executed many times (or maybe it's added somewhere else in the code?).
Thanks to #MikeMcCaughan for making it clear - I had a jQuery function wrapped inside of an addEventListener function.
Here's how this looks (working):
function sendplace() {
var add1 = place;
console.log(place);
$.ajax({
url: '/new_place2',
data: JSON.stringify(place),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(response) {
window.alert("Saved!");
console.log(response);
},
error: function(error) {
console.log(error);
}
});
};
And the code that calls the function:
var placebutton = document.querySelector("placebutton");
placebutton.addEventListener("click", sendplace, false);

$.ajax still does not execute

herewith my full code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
<meta name="dcterms.created" content="Tue, 03 Feb 2015 08:06:46 GMT">
<meta name="description" content="">
<meta name="keywords" content="">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function validateLogIn()
{
var username = $("#username").val();
var password = $("#password").val();
var login = $("#login").val();
//var remember = $("#remember").val();
$.ajax({
url: 'validate.php', //i never get to this file!
type: 'POST',
data: { 'username' : username , 'password' : password, 'login' : login}
}).done(function(response){ //Attach a succes handler
alert(response); //this doesn execute
});
return false;
}
</script>
</head>
<body>
<form action="crud.html" method="post" name="form_submit" onsubmit="return validateLogIn()">
<input required placeholder="Username" type="text" name="username" id="username"/>
<input required placeholder="Password" type="password" name="password" id="password"/>
<label for="remember">Remember Me:</label>
<input type="checkbox" name="remember" value="yes" id="remember" />
<br />
<br />
<input type="submit" name="login" value="login" id="login"/>
</form>
</body>
</html>
then validate.php
<?php
//i never get here i dont understand
echo htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8');
echo $username = $_POST['username'];
echo$password = $_POST['password'];
if ($_POST['login']) //check if the submit button is pressed
{
$remember = $_POST['remember'];
....../
please help, i have been struggeing with this the whole day
i get this when i do //localhost/php/validate.php
I've checked your code works perfectly. So what's wrong?
If you access your validate.php directly, you don't send any data to it and hence $_POST[] contains nothing. You should visit your form page, type something in your form and click login and you should get an alert with response from your validate.php.
Via AJAX you send your request in the background and and if you send some data to your validate.php it will work otherwise it won't. I suggest you do all kind of error checking/handling.
For your 'data' property, in my opinion, you should remove the quotes.
Also to really debug and find out the answer, you should debug like this. Adding these other properties will help you determine what issues / errors you're getting.
$.ajax({
url: 'validate.php', //i never get to this file!
type: 'POST',
dataType: 'xml', //YOu're missing this value!!!
data: { username : username , password : password, login : login},
beforeSend: function() {
//This will execute regardless what happends before the AJAX is sent.
},
success: function(xml) {
//Will execute if no errors are present while sending AJAX
},
error: function(xml) {
//If any error happens while sending AJAX, this will be called.
},
complete: function(xHR, textStatus) {
//This will execute regardless what happens.
},
});
The "beforeSend" property will execute before anything is sent to the server to be validated.
The "success" Will only execute if there is no error in the dataType that is returned, or any error for that matter.
The "Error" will only execute if the returned data is not what dataType expected it to be.
The "complete" Will execute regardless what happens.

XML Parsing remote server

I have followed some tutorials on how to parse XML from remote websites and came across the wonderfully articulated question and answer in stackoverflow.
However even after following the question, following program is not working.
<!DOCTYPE html>
<html>
<head>
<title>Aviation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText) ;
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
The website which I am trying to parse is same.
US FAA
Also I want to develop it as stand alone application i.e. Just HTML interacting with the remote website.
As mentioned, you can (need to) use jsonp because faa.gov apparently forgot to add the appropriate header to their API responses.
By the way - always prefer json over xml with Javascript - it's so much nicer to work with.
// ask faa.gov to add the HTTP header "Access-Control-Allow-Origin: *" to their response
// then you can use this
// jQuery.getJSON('http://services.faa.gov/airport/status/IAD?format=json');
jQuery.ajax({
url: 'http://services.faa.gov/airport/status/IAD?format=json',
dataType: 'jsonp',
success: function (data) {
document.myform.result1.value = data.city;
}
});

$.ajax not able to receive JSON HTTP Response

I am in newbie in JavaScript, JQuery and Ajax coding.
I am using JQuery $.ajax method to invoke asyn REST call.
Somehow I am not able to receive HTTP response JSON data.
I can see the below alert result.
alert(data) method result is [Object Object]
alert(data.toSource()) method result is ({"key1","value1"})
alert($.parseJSON(data)) method result is nothing
I have tested the below code in both firefox and chrome browsers.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script>
</head>
<body>
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
$("#foo").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "resources/helloWorld",
type: "GET",
dataType: 'json',
success: function(data){
alert(data);
alert(data.toSource());
var r = $.parseJSON(data);
alert(r);
$("#result").html(data);
},
error:function(){
$("#result").html('there is error while submit');
}
});
});
</script>
</body>
From your post:
alert(data) -> [Object Object]
Right, alert() uses the string representation of the argument, and data is an object.
alert(data.toSource()) -> ({"key1","value1"})
Right, toSource() is a Gecko method that works as JSON.stringify.
alert($.parseJSON(data)) method result is nothing
Right, you are trying to parse an object.
What you want to do is something like perhaps:
success: function(data){
$("#result").html(data.key1);
}

Execute code if page doesn't load

I want to create a code that reloads a part of the page every 10 seconds and if it fails to reload (because of connection issue), then it plays a sound.
Is such thing possible using ajax and how? I have seen this type of feature in web chats before but never came across a code for it.
Try using setInterval function:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<title>Test</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" type="text/css">
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript" language="JavaScript"></script>
<style type="text/css">
<!--
.square {
background-color: #AAAAAA;
width: 250px;
height: 100px;
}
//-->
</style>
<script type="text/javascript" language="JavaScript">
$(document).on('ready',function(){
setInterval(updateDiv,10000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
//Code to play a sound
$('.square').html('<span style="color:red">Connection problems</span>');
}
});
}
</script>
</head>
<body>
<h1>The next div will be updated every 10 seconds</h1>
<div class="square">
Hello
</div>
</body>
</html>
And the php script:
<?php
echo "Updated value --> " . rand();
?>
To test, try renaming the php script (simulating connection problems) and rename to original name (getContent.php) to test correct situation again. Hope this helps.
Using JQuery, you can add handlers to run on fail...
$.ajax({
dataType: "json",
url: "myurl.com"
}).done(function( data ) {
//do what you want when it's all good
}).fail(function() {
//do what you want when the call fails
});
Or you can do it this way...
$.ajax({
type: "post",
url: "/SomeController/SomeAction",
success: function (data, text) {
//do what you want when it's all good
},
error: function (request, status, error) {
//do what you want when the call fails
}
});
And per request, here is a jsfiddle, it calls a service every 2 seconds, either with a URL that will return the date, or with a bad URL that will fail, mimicking a failed server.
UPDATE: I modified the jsfiddle to play a sound, as long as that sound remains on the server it's on :)

Categories