AJAX explained in detail - ajax

I found allot of examples of AJAX and I think I can get some code with it to work on my own. If only I knew what the use of all the terms of the AJAX code where.
I think in general it lacks the availability of these guides or special pages where constructed code is explained in detail for new programmers.
This would help enormously because of the misunderstanding of the syntax in many cases. Me for example spend 8 hours a day on my internship to learn PHP, Jquery, HTML from scratch and there is allot of information out there but its not structured and in most cases to technical. Any tips on that maby ? :)
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});

Ajax is asynchronous, which mean you can use it to get new informations from the server without reloading the whole page.
Here's an explanation of your code :
$.ajax({
$ is the JQuery object, on which you're calling the ajax function
type: 'POST',
You're gonna send your data by post, which mean that you'll have to get them in php with $_POST['variable_name']. You could also put GET instead
url: 'http://kyleschaeffer.com/feed/',
the url you want to reach
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
as you're sending your request with POST, you cannot pass data directly from the URL.
So you have to pass them like that. { nameVar: 'value', .... }
If you were sending with GET, you could directly write them into url like : "http://my_url.php?var1=val1&var2=val2 etc ...
beforeSend:function()
You can define an action before sending your ajax request
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
Here, inside your div "ajax-panel" you want to write some content. (a div "loading" and a picture inside "loading").
success:function(data)
If your request is successful, you can do something. By successful it means if server answer 200 i guess, anyway ... If you have a response from server... ;)
$('#ajax-panel').empty();
You delete content into ajax-panel
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
You're adding some html AFTER (append) the ajax-panel div
error:function()
Not sure you were looking for that, hope that help you ;)

AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develope next generation web application
Take a took at this
$.ajax({
type : varType, //GET or POST or PUT or DELETE verb
url : varUrl, // Location of the service
data : varData, //Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, //Expected data format from server
processdata : varProcessData, //True or False
success : function(msg) {//On Successfull service call
},
error : function() {// When Service call fails
}
});

Related

Shopify order API returns OK but does not update order using JS

I'm trying to create an order using JS. I've authenticated my app and have a function that POST's to orders.json. I see a status code of 200, indicating that the request submitted OK (right?) but the order itself never gets created. I've heard something about disabling cookies in my request, but I don't know how to do that, so if that's what I need to do please let me know.
I'm putting up my entire function, since I'm new to this entire thing and it seems that it's probably the structure of my request, not the API call. I'm seeing the "Error" log in the console, so clearly the error function is running.
function submitShuffle(prodid)
{
console.log(prodid);
var params = {
"order": {
"line_items": [
{
"variant_id": prodid,
"quantity": 1
}
]
}
};
$.ajax({
type: 'POST',
url: 'https://<my-usrnam>:<my-pass>#toyboxshufflesandbox.myshopify.com/admin/orders.json',
dataType: 'application/json',
data: params,
success: function(data){
console.log(data);
},
error: function(data){
console.log("Error");
console.log(data);}
});
}
You cannot retrieve information from Shopify Admin API by AJAX. There is a limitation about this because you have to expose your username/key and password which is not a good idea.
You have to use some service/app or just to create a custom app.
Shopify returns an Object when you make a call. Hence 200 OK status. Inspect the object returned. A failed create POST object will not have an ID. So there is clue number one. Secondly, you'll see that Shopify tells you what the problem was in the Error key of the returned object. If you cannot figure out what you did with the message from Shopify, make the same call to the GraphQL endpoint if you can, as the error messages Shopify returns from those endpoints are currently much better. They are backporting them to the older REST API, but for now, GraphQL is more expressive.

I can't seem to generate content for dynamic content load

I am using wordpress and php along with ajax to create a random loading of customer reviews on our main page
function loadContent() {
$.ajax({
type: "GET",
url: 'http://skillsetsonline.ssosv.com/contentLoader.php',
data: {
company: 1
},
success: function(data) {
alert(data);
var currReview = document.getElementById('reviewRand');
currReview.innerHTML = data;
}
});
}
setTimeout(loadContent, 10000); // milliseconds, so 10 seconds = 10000ms
<div id="reviewRand" class="elementToFadeInAndOut" style="font-color:#FFF;">Hi how are you</div>
I pasted the ajax command in from a stackoverflow posting that was an accepted answer but may not have it exactly right this does not include the fading CSS code I use but that is working I just need to change the content.
Currently "Hi how are you" fades in every 10 seconds. One thing I have not learned about yet with this ajax command is the
data:{company:1}
I know it simply passes &company=1 to the GET URL but in my case I do not need to send anything and since it should not break anything if it is sent I left it alone not sure if
data:{}
would work and be cleaner
I have verified that the url used does get a random review
formatted like this
I love this program.blah blah.<br>
A USER<br>
A location<br>
June 2016<br>
Each line is formatted in CSS via a class tag
Any ideas would be greatly appreciated
Since the domain you're making the AJAX request to is on a different domain/origin, what you're running in to is a CORS issue. By default, the client will not allow you to update the page with data from an AJAX request that is served on a different origin than the site where the request originated. You can read about making CORS changes here https://enable-cors.org/
A common way around this is to serve the response via JSONP. You can do this in your script at http://skillsetsonline.ssosv.com/contentLoader.php if you have access to change that file. There are also third-party sites that will request that URL for you and create a proxy that serves the response via JSONP, then you can use it on your website.
Here's an example utilizing a JSONP proxy on https://crossorigin.me
function loadContent() {
$.ajax({
type: "GET",
url: 'https://crossorigin.me/http://skillsetsonline.ssosv.com/contentLoader.php',
success: function(data) {
var currReview = document.getElementById('reviewRand');
currReview.classList.add('ready');
currReview.innerHTML = data;
}
});
}
setTimeout(loadContent, 0); /* changed this for the demo */
#reviewRand:not(.ready) {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reviewRand"><img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif"></div>

Post data to RESTful Invalid HTTP status code 405

I create a method to post json data to web service :
function WishList() { }
WishList.prototype.addToWishList = function(redirectURL, postURL, userObj) {
$.ajax({
type: "POST",
url: postURL,
data: JSON.stringify(userObj),
dataType: 'json',
contentType: "application/json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
}
This is my object:
var user1 = {
ID:1,
Sex:1,
Name:"titi",
Company:"ABC",
Address:"Phnom Penh",
Email:"test.abc#gmail.com",
Phone:"011123456",
WebAccount:"test.abc#gmail.com",
Password:"123456",
GroupCustomerID:125,
Stars:1,
IsVIP:0,
PriceLevel:1,
LastDateSale:"\/Date(-62135596800000)\/",
TotalCredit:150.12,
AgingData:null,
TotalRedeemPoint:1000.00,
RedeemData:null,
ExchangeRate:155.00,
HistoryData:null
};
Calling function :
$(document).ready(function () {
var myWishList = new WishList();
$('#addToWishList').click(function(){
myWishList.addToWishList('http://www.blahblahblah.com' , 'http://blahblah/Website/Products/Product.svc/Wishlist/' , user1);
});
});
Then I got errors in my console :
"NetworkError: 405 Method Not Allowed in firefox and Invalid HTTP status code 405 , XMLHttpRequest cannot load url in chrome.
Note: When I use Rest Client of Chrome to POST to web service, it worked.
Any help would be much appreciated, thank you.
Not sure what you are using as the service on the other end but this may be due to cross domain posting. I hate to post a link and run but this may be of some use to you.
http://praneeth4victory.wordpress.com/2011/09/29/405-method-not-allowed/
Looks like they could get it working in IE but had some issues as you with the other browsers. Perhaps these couple changes will help access the service better.
This post was good at explaining the error and parts to it as well so if the above link is not helpful this one may help you diagnose the issue further.
http://www.checkupdown.com/status/E405.html
ok ok last edit, just wanted to make sure you have enough info to hopefully resolve your issue, here is a good article on the underlying problem I believe you are having..
http://www.d-mueller.de/blog/cross-domain-ajax-guide/

caching issue with jQuery/AJAX

I am getting data through $.ajax multiple times. However the data is not getting refreshed in every call. Rather I am getting the same data in every call to $.ajax. The code was working properly at my home.
However in below code if I substitute console.log("success "); with console.log("success "+data); and observe in chrome console, then the code works fine. I suspect its a caching issue, but can figure it out.
function getDataJSON()
{
originalData="";
new Date().toString();
$.ajax({
url: 'data.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
success: function(data)
{
console.log("success ");
...
...
Thanks
you can set cache Cache. by default it will set to cache=true.
from DOCS
If set to false, it will force requested pages not to be cached by the
browser. Note: Setting cache to false will only work correctly with
HEAD and GET requests. It works by appending "_={timestamp}" to the
GET parameters. The parameter is not needed for other types of
requests, except in IE8 when a POST is made to a URL that has already
been requested by a GET.
$.ajax({
url:'url',
cache:false,
.....
})
Like #Ravi said cache priperty is you're frined.
You should realy spend more time on studying you're weapon of choice!
Link => first hit on google if you search jquery ajax
There is another method of preventing caching. Just append some random number to url you are accessing.
For example:
"www.url.com?" + new Date().getTime()
or
"www.url.com?" + Math.random()
from Stack answer

Chrome gives "XMLHttpRequest Exception 101" in some cases when doing an Ajax request

I have a JavaScript application that works like this:
Uploads a file, receives the uploaded file ID as a response
This is done using the BlueImp uploader
Uses the file ID to refer to the file in subsequent requests, in this case to receive a preview of the uploaded file.
This is the code for the file upload 'complete' handler. It's originally written in Coffee Script (http://pastebin.com/708Cf9tu).
var completeHandler = function(e, data) {
var url;
if (data.textStatus !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget i konsollen");
console.group('Upload failure');
console.error(data.textStatus);
console.error(data.result);
console.groupEnd('Upload failure');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
return;
}
self.fileUploadResponse = data.result;
url = "" + config.api_root + "/" + config.api_path_tabulardatafilepreview;
return $.ajax(url, {
type: 'POST',
dataType: 'json',
async: false,
data: {
'file_handle': data.result.file_handle,
'rownum': 5
},
complete: function(req, text_status) {
if (text_status !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget " + "i konsollen");
console.group('Failed to receive data file preview');
console.log(text_status);
console.log(req.responseText);
console.log(req);
console.groupEnd('Failed to receive data file preview');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
}
self.previewData = JSON.parse(req.responseText);
return self.setStage(2);
}
});
};
This works brilliantly in FireFox, but in Chrome I just started to get an error in the second jQuery Ajax request. It now returns with status "error", with no responseText and with statusText set to "Error: NETWORK_ERR: XMLHttpRequest Exception 101". Though this doesn't happen in all cases. The uploaded file doesn't seem to have anything to do with the issue, because a 10KB csv file works, a 120KB xlsx file fails but a 1.2MB xlsx works. Additionally it's the second Ajax request that fails, and it doesn't do anything but send two small integers to the server. Why does that fail!?
Also this just started happening today. I haven't changed anything that I know of, and I have not updated Chrome.
Does anyone have a clue as to why Chrome is doing this? Can it have anything to do with an Ajax request being launched in the complete handler of a previous Ajax request?
Thanks for any guesses that can help me solve this
Turns out it's a bad idea to start lengthy processes inside Ajax event handlers. In my case, starting a new synchronous Ajax request in the event handler was the mistake. I have since made both requests asynchronous and separated the code into neat functions, and I'm no longer bothered by the exception.

Resources