Google app engine JSON/AJAX not working - ajax

Here is my JS code:
<script>
$("#comments").click(function(event) {
$.ajax({
type: "GET",
url: '/localhost:8080/comment',
data: JSON.stringify(
{
'name': 'anon',
'subject': 'MY COMMENTS',
}),
contentType: 'application/json',
success: function(data,textStatus, jqXHR) {
console.log('POST response: ');
console.log(data);
}
});
});
</script>
and here is my Python Code:
class Guestbook(webapp2.RequestHandler):
def get(self):
Jguest_data = json.loads(self.request.body)
return self.response.out.write(json.dumps(Jguest_data))
I got the error 404 Resource not found. After digging around there is some issues with localhost . so I tried with JSONP as follows:
<script>
$("#comments").click(function(event) {
$.ajax({ // ajax call starts
url: "localhost:8080/comment", //
type: "GET",
data: JSON.stringify(
{
'name': 'anon',
'subject': 'MY COMMENTS',
}),
dataType: "jsonp", // Choosing a JSON datatype
success: function(data,textStatus,jqXHR)
{
console.log('POST response: ');
console.log(data);
}
});
});
</script>
That still does not work... I get "No JSON object could be decoded" Error.
I tried replacing JSON.loads with JSON.load... and that still errors out...
Can someone please let me know what the issue is?
Thanks a mil in advance

when you do a GET request with ajax you are using url parameters.
so there is no body in the request.
make a POST and change your get() to post()

You should edit your app.yaml file if there is one in your project, and if there is not one, add one.
Add this code to your file (app.yaml).
-url: /comment
script: <url-to-the-server-side-script>
You can see a more complete app.yaml documentation for use with python here.
https://cloud.google.com/appengine/docs/python/config/appref

Related

WordPress - Get server time using ajax and admin-ajax.php

I am new to using Ajax to get WordPress data.
The following code should return the server time but the response always is "400 Bad Request".
$.ajax({
url: obj + "?action=wps_get_time&format=U",
success: function(data) {
console.log(data);
}
});
Also tried it as POST and it was the same.
$.ajax({
url: obj,
method: "post",
data: { action: "wps_get_time", format: "U" },
success: function(data) {
console.log(data);
}
});
Any suggestions what's wrong please? Can't figure.
I always thought there are actions I can use always such as wps_get_time, without using a plugin. Am I wrong?
Ist there any easy way to get the server time by ajax?
Thank you all in advance.
The code below will return server time in Indochina and log it to console.
$.ajax({
type: 'GET',
cache: false,
url: location.href,
complete: function (req, textStatus) {
var dateString = req.getResponseHeader('Date');
if (dateString.indexOf('GMT') === -1) {
dateString += ' GMT';
}
var date = new Date(dateString);
console.log(date);
}
});```

Check if a URL exists then open in iframe

Currently, I open a url with
window.open("#iframeid", myurl);
However, ideally I want to check if the url exists before loading it.
I've changed my code to the following, but I cannot see where I'm going wrong.
Nothing appears to happen.
if I change .add to .src, I get an error.
Any help would be appreciated.
$.support.cors = true;
$.ajax({
url: myurl,
dataType: 'html',
success: function(data){
$("#iframeid").add(data);
},
error: function(data){
alert("didn't work");
}
});
You can execute code based on the statusCode:
$.ajax({
url: myurl,
dataType: 'html',
statusCode: {
200: function(){
//run your success code
},
404: function() {
alert( "page not found" );
}
}
});

Ajax Call with PUT method

i am trying to make ajax call with PUT method. Below is the code, but i am getting with the error XML Parsing Error: no element found Location: moz-nullprincipal:{c847a4af-f009-4907-a103-50874fcbbe35} Line Number 1, Column 1:
$.ajax({
type: "PUT",
async: true,
url: "http://localhost:8080/karthick/update",
data: JSON.stringify(params),
contentType: "application/json",
dataType: "JSON",
processdata: true,
success: function (json) { //On Successfull service call
},
error: function (xhr) {
alert(xhr.responseText);
}
});
return false;
};
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
But this service is working Good with Rest-client jar. Also my POST method works fine in my browser. Please help me in this.
Regards
Karthick
Usually, this error comes, when making a cross browser request. Try data: JSONP and see if it helps.

Ajax Success Function not working

I am using Ajax to add contents on my database. And here's the code:
function addToFavorites(){
var recipe_id = $("#recipe_id").val();
var url = connect_url+'addFavorite.php?user_id='+user_id+'&recipe_id='+recipe_id;
$.ajax({
type: 'POST',
data: [{
user_id: user_id,
recipe_id: recipe_id
}],
url: url,
async: true,
jsonpCallback: 'userCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
alert("HELLO!!!");
},
error: function (e) {
alert("ERROR!");
}
});
}
The Ajax call was successful and I was able to add records on the database but I'm just wondering why is it not displaying the alert message if the calling was successful? Is there something wrong with my code? Or is there something wrong with my understanding? Thanks!
you must give a response with some info to the ajax or it won't know the response succeeded

How to send parameters with jquery $.get()

I'm trying to do a jquery GET and i want to send a parameter.
here's my function:
$(function() {
var availableProductNames;
$.get("manageproducts.do?option=1", function(data){
availableProductNames = data.split(",");;
alert(availableProductNames);
$("#nameInput").autocomplete({
source: availableProductNames
});
});
});
This doesn't seem to work; i get a null in my servlet when i use request.getParameter("option");
If i type the link into the browser http://www.myite.com/manageproducts.do?option=1 it works perfectly.
I also tried:
$.get(
"manageproducts.do?",
{option: "1"},
function(data){}
which doesn't work either.
Can you please help me?
EDIT:
also tried
$.ajax({
type: "GET",
url: "manageproducts.do",
data: "option=1",
success: function(msg){
availableProductNames = msg.split(",");
alert(availableProductNames);
$("#nameInput").autocomplete({
source: availableProductNames
});
}
});
Still getting the same result.
If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:
$.get('manageproducts.do', { option: '1' }, function(data) {
...
});
as it would send the same GET request.
Try this:
$.ajax({
type: 'get',
url: 'manageproducts.do',
data: 'option=1',
success: function(data) {
availableProductNames = data.split(",");
alert(availableProductNames);
}
});
Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.
I got this working : -
$.get('api.php', 'client=mikescafe', function(data) {
...
});
It sends via get the string ?client=mikescafe
then collect this variable in api.php, and use it in your mysql statement.
This is what worked for me:
$.get({
method: 'GET',
url: 'api.php',
headers: {
'Content-Type': 'application/json',
},
// query parameters go under "data" as an Object
data: {
client: 'mikescafe'
}
});
will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe
Good Luck.

Resources