I've been developing a phonegap application which uses jQuery Mobile for it's main structure.
When the site/app runs, it executes a number of ajax calls to get the latest data to the app. For example, a list of items is gathered for the homepage, whilst other lists of other items are gathered for other pages.
What I am finding is that every now and then there is a mixup in data.
As a random (but applicable) example:
Query 1 - get names and photos of people
Query 2 - get names and photos of cities/locations
In each of the ajax calls, instead of using (data, status) I have renamed the data object to a unique identifier hoping this would resolve the issue.
Then, on my $.each function I have ensured that the iterator has a different name too, so instead of (i, item) it might be (i, personitem) and (i, cityitem)
The Issue
Despite my best attempts to get this data to not have any possibility of crossover, I'm finding that (to keep with the current example) - photos of people will show up on the cities page, and photos of cities will show up on the users page.
This is also an intermittent issue. Sometimes it won't happen at all, other times it will happen a lot or only a little bit.
I hope I have explained myself clearly. Thank you in advanced to anyone willing to help! I'm all out of ideas :-(
==================
UPDATE
My main question is if anyone knows what might cause data-mixups in such queries.
My queries all look like this:
$.ajax({
url: 'get_cities.php?country='+country,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(citydata, status){
if(citydata.length == 0){
$('#somediv').append('no data to show');
}
$.each(citydata, function(i,cityitem){
var content = '<img src="'+cityitem.image+'" />'
+'<p>'+cityitem.name+'</p>';
$('#somediv').append(content);
}
});
At this point I believe #mason81 was correct with his suggestion.
I removed all of the:
jsonp: 'jsoncallback',
in my code, and then updated my PHP files to use
echo $_GET['callback'] . '(' . json_encode($records) . ');';
instead of
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
I originally also placed &callback=? into my URL's but from reading the jQuery Ajax documentation it should automatically assign a random unique callback to each call as long as you are using dataType: jsonp without manually specifying a callback parameter.
If this fails I'll still consider this the correct answer, I'll probably just have to go through and either assign unique callback parameters to each request or ammend my URL's with &callback=? as mentioned above.
Thanks everyone for their input!
Related
Problem- I have an API that displays a random quote once the page loads. My button(div) called "newQuote" doesn't generate a new quote, instead, it displays the exact same quote, making my button useless.
My code can be found on GitHub here
SO-
I have a javascript function, called getNewQuote() that runs when my page loads. This function grabs a quote and author from an API (https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1), and appends it to my div with the class quoteTitle and quoteDisplay.
function getNewQuote() {
$.ajax({
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
jsonp: 'jsonp',
cache: 'false',
success: function(data) {
var post = data.shift();
$("#quoteTitle").empty();
$("#quoteDisplay").empty();
$("#quoteTitle").append(post.title);
$("#quoteDisplay").append(post.content);
}
});
}
getNewQuote();
Then, I set another div called newQuote which, when clicked, would display a new quote.
$('#newQuote').on('click', function(e) {
e.preventDefault();
getNewQuote();
Now, to me, it seems that the problem is caching. The reason that I think it is a cache problem is because if I go to the site on my phone using the app Firefox Focus, which (pretty sure) doesn't store any cache, the site will run as wanted, and will change my quote whenever I click on my #newQuote. You can try it for yourself at 'rqg.ronlaniado.me', where it is hosted.
Since my problem is cache, I did use some methods and plans to avoid this.
cache: 'false',
I set cache-ing to false in my .ajax request.
<script src="qg_js.js?v=42"></script>
I put "?v-42 which, according to Google, shouldn't keep cache stored.
If anyone can look through my code and assist me in solving my issue, that'd be great. Also, this is my first time posting here, so sorry if I am a bit messy with everything.
The error was here:
cache: 'false';
The correct usage is:
cache: false;
These quotes caused cache to be kept, meaning that the quotes didn't change.
Here is a quick example of something I was wondering about, before we start I am aware that eval should only be used when absolutely needed.
Let's say I have an endpoint that runs some code like this:
endpoint.php
<?php
$input = sanitised($_POST['someData']);
$array = someDatabaseQueryMethod($input);
echo 'runtime.getItem("'.A_SAFE_DEFINED_CONSTANT.'").stateChange({"newValues":'.json_encode($array).'});';
?>
then I have an index.php that looks like this:
... ommitted...
<body>
$.ajax({
url : "./endpoint.php",
type: "POST",
data : {someData: 1},
success: function(data, textStatus, jqXHR)
{
eval(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
//error logic here
}
});
...
Is there a situation that can occur where some content in $array (which, lets say, could contain anything at all, multi dimensional, loads of different strings / other data types, but will always be a valid array that won't cause json_encode to fail) could mean that the eval statement could be vulnerable to some kind of injection?
Effectively I always want .stateChange to recieve an object that it can take a look at and decide what to do in this example
I know this might seem like quite a convoluted example, it is taken out of context - this is the smallest verifiable example i could come up with.
EDIT: while the above is closes to what I am doing, i guess the smallest example would actually be this:
endpoint.php
<?php
$input = sanitised($_POST['someData']);
$array = someDatabaseQueryMethod($input);
echo 'var a = '.json_encode($array).';';
?>
OK guys i get it - no need for more comments that do not answer the question which is not about different methods of doing the same thing but thanks for your feedback
It would be great to get an example of where this would break, not hearsay about how bad eval is.
Is there a situation that can occur where some content in $array
(which, lets say, could contain anything at all, multi dimensional,
loads of different strings / other data types, but will always be a
valid array that won't cause json_encode to fail) could mean that the
eval statement could be vulnerable to some kind of injection?
Yes, absolutely! If I were a hacker, I could very likely find a way to hijack a user's entire session if there's ever even the slightest mistake made in escaping user strings. There is absolutely no reason you should need to take that kind of risk. Use JSON.parse(str) instead. Since you're currently returning JavaScript code, change it to simply return your value as an object with two values that you automatically do two things with. (eg: {stateChangeTarget: 'CONSTANT_IDENTIFIER', stateChangeData: {"newValues": [...]} }) This will give you the array that you want. Then perform the expected functions in the result like this:
dataType: "json"
success: function(data)
{
runtime.getItem(data.stateChangeTarget).stateChange(data.stateChangeData);
},
This is also extensible to other client applications. If you decide to write a mobile app, that app won't be able to run JavaScript, and so it'll be lost when the server returns a pure JavaScript command with no neutral way to access the data (JSON)
I am new to the web development world and I would like to be able to connect an HTML page to a web api through . and I was really not successful in this.
I followed this tutorial to be able to make this connection : http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
All I need is to send some inputs from an HTML page to a web api that takes these parameters and returns an object
I am using this code
$.getJSON("api/GeneratorController/setparameters/"+firstparameter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter,
function (data) {
alert(data); //never comes here
}).fail(function (jqXHR, textStatus, err) {
alert("All checks are correct, image was not generated. jqXHR = " + jqXHR.valueOf() + " textStatus=" + textStatus + " Error" + err);
});
it always goes into the fail portion , I attached the alert message that comes out of it
Any Reason why it is doing this ?
#smartmeta (I changed the typo , thanks) I followed your advice and here is the output of the alert (as expected , values that I have inserted are displayed):
Your url needs to start with your domain, not 'api/generatorcontroller/...'. If you are developing locally, something like http://localhost:[port]/api/generatorController/....
Also, webApi maps to url verbs, (get, post, put, delete..), not functions like setparameters, unless you have a [name=setparameters] above your get() function.
Also, I am pretty sure you don't have a route setup to handle the url with all those parameters. What you want to look at, as it seems your using jQuery, is jQuery.get documentation. The second example near the bottom shows where to place parameters. WebAPI will check for them in the body if they are not in the query string. so it would end up looking like:
$.getJSON("http://"+window.location.host+"/api/GeneratorController/setparameters", {parameter1: parameter1, parameter2:parameter2 ...});
Well, the first thing to check is to make sure that your server-side function is returning the values you expect. You can do this with Chrome's developer tools or with the Firebug Firefox extension, and I think IE10 has something equivalent, too. Go to the "net" tab, find the request corresponding to your API call, and take a look at what the server responded with.
Please add the line
alert("api/GeneratorController/setparameters/"+firstparemeter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter)
Then call your script and take the output of the alert into a browser. Then check if your application Handels that route.
By the way I think you have a typo. I guess it should be firstparameter.
I assume you would like to do
"api/GeneratorController?foo=Bar
But when you are new to this, I would suggest that you first try the example like it is. And After that you can start changing setails.
So I found what was the problem with my code
Two things :
1- I shouldn't use the word "Controller" when I call my API ,it should be api/Generator/...
2- the function name needs to start with "get" and not "set" since it "gets" the return value from the api
Thanks everyone!
A quiz form is completed by the user and the "Score Quiz" link is clicked. What is wanted is for the score to be tallied, results sent to server via jQuery ajax call, and the fancybox presenting the user notice.
What is happening is the tally is done and the ajax call is initiated and the page reloads. If I comment out the ajax call, the fancybox appears as desired. Using Wordpress 3.4.2.
What might be going on?
jQuery('#checkQuiz').click(function(){
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// tally correct answers
var quizData = tallyScore();
// display user notice
jQuery('a#hiddenAnchor').trigger('click');
// store the data while the user is reading the results display
jQuery.ajax({
type:"post",
url:ajaxurl,
data:quizData
});
return false;
});
NOTE 1: I was able to catch an error in the Firebug console:
NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace]
The file reported is jQuery.js and that appears to be a version 1.7.2. I noted that jQuery current release is 1.8.1. I wonder if that is part of the problem.
NOTE 2: I forgot to mention that this code is part of page template in a child theme. Similar ajax calls made on other pages in the web app work fine. I added a post to the Wordpress.org troubleshooting forum in case someone there doesn't visit stackoverflow.
NOTE 3: I tested this with the standard theme for wordpress "twentyeleven". The same error occurred. I am running out of options to test.
You should try:
jQuery('#checkQuiz').click(function(e){
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// tally correct answers
var quizData = tallyScore();
// display user notice
jQuery('a#hiddenAnchor').trigger('click');
// store the data while the user is reading the results display
jQuery.ajax({
type:"post",
url:ajaxurl,
data:quizData
});
e.preventDefault()
return false;
});
Using e.preventDefault should stop the page from reloading.
Note that I made two changes to your code. I added e to the parameter-list for your callback function and e.preventDefault at the end of that function.
After testing and decomposing the code involved, the error was found in the data array passed into the ajax call. To aid anyone seeking answers for a similar error here is what I found in the code.
quizData is an array structured for the WordPress ajax handler.
Code As Found
var quizData = {
action: 'save_quiz',
item: invoice_item,
lesson: jQuery("#lesson"),
score: ratio };
There are two problems with this code. First, the jQuery call is assigning a jQuery object to the array value element "lesson". This results in an "undefined" value in the array that creates the error condition. The missing bit here is the ".val()" function invocation.
The second one may be the code architecture of the project, but it appears that a jQuery call within array assembly block does not work as expected. In my tests, the data array contained an empty value.
Resolution
var lesson_id = jQuery("#lesson").val();
var quizData = {
action: 'save_quiz',
item: invoice_item,
lesson: lesson_id,
score: ratio };
I hope this helps someone.
The snippet of JavaScript that I am having trouble with looks like this:
var content_value = encodeURI(document.getElementById("chattext").value)
downloadUrl("/getchats", "POST", "content=" + content_value, onChatsReturned);
This code works, but it only posts the content. How would I have to change this in order to post another item, such as a description? I have all the other code ready and working, I just don't know how the parameters work for downloadUrl.
It's quite hard to say anything for certain since I can't know what downloadUrl() function actually does, but here is a solution that at might solve your problem (if it just passes the 3rd argument to the backend).
downloadUrl("/getchats", "POST", "content=" + content_value + "&description=" + desciption_value, onChatsReturned);
As the comments mention more information on the downloadUrl-function is needed to say for sure.