The Program I'm writing and the functionality I'm trying to achieve
Okay. So what I'm writing at the moment is a very simple forum, in Javascript using AJAX. Part of my task is to add a new post, using an API that my lecturer wrote for us in PHP. Just to note, the API and the SQL database are completely local.
The function I am using to add this post is:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
'method':'post',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).send(Object.toQueryString({
// Had to convert it to a query string because it wouldn't work as a normal object.
// These are the required values to send, to store a "post" in the database.
'name':'This is a name',
'comment':'This is a comment!'
}));
}
I am aware this will add the same data every single time. I'm just trying to get the damn thing working!
The problem
What is happening is, when this function is called, I am getting an SQL syntax error. I was confused, because that would imply that my lecturer's code is wrong. After speaking with my lecturer, he explained that this happens when the post data isn't sent correctly to the PHP code. So I went about using Google Chrome's developer tools to see what was going on, and this is what I discovered:
Now to me, this means that the data is successfully being loaded into the request, and is being passed to the PHP files fine. Obviously I'm wrong. I've been racking my brains trying to make this work.
I know that the API works fine, because everyone else in my class isn't having any problem with it, and the code I am using is practically a rip off of the code in the notes, so I'm about 90% sure that's correct to.
One thing to note is that the code in the onSuccess key runs, so I know it's not a problem on the AJAX side.
Another thing is that this code worked in University on those computers, and it's since I've got it home that it's decided not to work.
Stack Trace
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[HY000]: General error: 1 near ")": syntax error' in G:\Ajax
Coursework\guestbook\php\database.php:134Stack trace:#0 G:\Ajax
Coursework\guestbook\php\database.php(134): PDO->prepare('INSERT INTO
pos...')#1 G:\Ajax Coursework\guestbook\php\class.GuestBook.php(44):
DatabaseHandler->insert(Array)#2 G:\Ajax
Coursework\guestbook\control.php(8): GuestBook->insert(Array)#3
G:\Ajax Coursework\guestbook\control.php(56): insertPost()#4 {main}
thrown in G:\Ajax Coursework\guestbook\php\database.php on line 134
Object.toQueryString is used in convert an object to a query string. So if the server is requiring both $_POST['name'] and $_POST['comment'] to be set, it wont be.
Frankly because you are posting it, I dont think $_GET['name'] or $_GET['comment'] would be set either.
Request.send expects an opject. You are sending it a string. So it should be
Request.send({prop: 'value'}), not Request.send(value).
Do yourself a favor and make a PHP with the following php code, and see what it returns. It may clear this up for you right away. I have a feeling nothing is being sent except for $_GET['action']
<?php
echo '<pre>';
print_r($_GET);
print_r($_POST);
echo '</pre>';
?>
Just in-case anyone stumbles upon this thread looking for an answer:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).post('name=This is a name&comment=This is a comment!');
}
Here I'm using the .post method to POST data.
Related
So I'm desperately trying to pull a value from a 3rd party website API. The information is formatted in the following way:
Website's API response
I'd like to pull out a value for "price". So far I've tried many different codes but all have failed. I've also spent a lot of time searching for a solution but without succes. At the moment my code for obtaining the value looks like this, but it's obviously not complete and incorrect as I'm new to NodeJs:
var Request = require("request");
Request.get("url", (error, response, body) => {
if(error) {
return console.dir(error);
}
console.dir(JSON.parse(body));
});
And yes the url is actually inserted in my code + I know that this should only display the full JSON structure, but it fails to do even that :/
Any kind of advice would be welcome :)
EDIT: So I've fixed that issue with not getting data :) However I still need to filter my data in order to pull out the "price" value. As of now my data displays this: "data: { items_on_sale: [ [Object] ], items_not_on_sale: [] } }"
status: 'fail' : The api is not replying with the data.Does the url require any query params/body to be passed with the url?
Try hitting the api using postman/SoapUI and check the response there.
also try printing the response in the log,what values do you get?
console.log('statusCode:', response && response.statusCode);
There was a problem with 2FA code. It wasn't generating properly. It is now fixed.
I searched around, and couldn't find an answer to my question. I'm very new at coding, and at work, we have an application that current names that are logged in, and what they are doing.
Recently, they have changed from jquery 1.4.1 to jquery 1.8.3. Ever since then, I cannot get the results to process correctly, because of the following error;
"Unable to get value of the property 'split': Object is null or undefined"
I have the code setup to grab the results and split them;
function processAgents(xData, status) {
var avail = xData.responseText.split("|")[0];
var acw = xData.responseText.split("|")[1];
var total = xData.responseText.split("|")[2];
var breaks = xData.responseText.split("|")[3];
var pending = xData.responseText.split("|")[4];
The application is setup to open as an HTA file which opens up the PHP script.
Any help would be appreciated, please let me know if I left anything out!
Thanks!
EDIT 1
I did some more investigating, and it looks like I'm not getting data from my process request. This is how it is currently setup
function updateAgents() {
var ts1 = new Date().getTime();
$.ajax({
url: "http://SERVER/AgentSrc.php?x=" + ts1,
complete: processAgents
I'm not sure if this is processing correctly since they went to jquery 1.8.3.
EDIT 2
So after looking into it more, it doesn't appear that the script is getting the data from the server, even though I have access. If I make a local file and put the information in it, it will pull the information and split it, but if I point to the path of the file on the server, it won't get the information. But the strange thing is, if I run it using jquery 1.4.1, it pulls the data fine, but can't display it. But with 1.8.3, it doesn't allow me to pull it from the server.
thanks again!
This will give some clarity
xData.responseText.toString().split("|")[0];
(split is part of string not jQuery)
Here is a possible explanation: in earlier versions of jQuery, ajax calls returned an xmlHttpRequest (XHR) object. Recent versions return a promise (jqXHR) instead.
See this page for more details.
I have been struggling since yesterday with the following piece of code.
function findLocation(){
alert(1);
$.getJSON( "http://www.omc4web.com/geoip/geoip.php",
{ip: "127.0.0.1",
callingurl: "www.thissite.com" },
function( result ){
alert(2);
$.each(result, function(i, field)
{
alert(i);
if(i=="country")
{
country_code = field;
}
});
})
}
It does not seem to want to get beyond the calling of the php script. The returned data is {"country":"US","store":"US"} but the function does not seem to want to process it and I never get to alert(2). I have placed monitors in the php script and I can see that it does indeed get called with the correct parameters and it does return the data expected.
if you call http://www.omc4web.com/geoip/geoip.php?ip=127.0.0.1&callingurl=www.thissite.com from your browser you will see that data is returned.
The same piece of code calling a URL with no parameters behaves correctly, but not with the above setup.
My few remaining hairs would appreciate some help on this.
additional info:
header('Content-type: application/json'); set on php script
tried it on chrome and firefox
no errors show up on firebug just a blank response screen
running script from localhost, but if its a cross domain issue, why am I able to make a similar call (without params) to amazon? $.getJSON("http://freegeoip.net/json/",function(result){ works fine as does the popular flickr example.
I am using <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Thanks in advance
Ossi
I think it's a cross domain issue. I guess you're able to use freegeoip.net because you're using JSONP. Try looking at the jQuery documentation to learn how to use JSONP: jQuery.getJSON()
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!
Anyone can tell me what I'm doing wrong?
I am creating a simple system to get people in and out of user groups and for that purpose I am using Dojo and Perl. (If I could have it my way it would be PHP but I am not the boss.)
At the moment I only use three files, one for Perl, one for JavaScript and one for CSS styles.
The start of the CGI script routes to different functions as follows:
if ($search = $cgi->param('psearch')) {
dbConnect();
jsonSearchPersons($search);
dbDisconnect();
} elsif ($user_id = $cgi->param('person')){
dbConnect();
create_form($user_id);
dbDisconnect();
} elsif ($user_id = $cgi->param('saveuser')) {
save_user();
} else {
mainPage();
};
...
sub save_user {
print $cgi->header(-type=>'text/plain',-charset=>'utf-8');
print("success");
}
The problem I have now is when I want to save the new groups for the user though an Ajax call (a call to this URL: users.cgi?saveuser=xx). This should (in my point of view) be a POST call, so I made this and tried to append the resulting HTML/text in a <div> but it didn't work:
dojo.xhr.post({
url: "/cgi-bin/users.cgi?saveuser="+user_id,
content: {
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
When I do it with dojo.xhr.get(); it works fine, but when I do it with the POST it's like it jumps over that part of the if statement and just appends the mainPage() function. Is there something basic I don't understand between Dojo and Perl? Do I have to set up the pages so it will accept a POST call? Or what am I doing wrong?
NOTE: This is the first "system" I have made though Dojo and Perl. (I'm normally a PHP/jQuery kind of guy who makes everything UI by hand, so I'm kinda new to it.)
Try adding the saveuser-parameter to the content-object of dojo.xhrPost instead of passing it in the url.
You're trying to pass the saveuser-parameter as GET and the other as POST, maybe that confuses your serverside part.
Try it like that:
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
new_groups: group_ids.toString(),
saveuser: user_id
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Found a solution.
The problem was my javascript. When posting to a perl script you use $cgi=new CGI; and all that. This takes both GET and POST variables and validates them. In my javascript/dojo code, i then used an url with GET vars and then made a POST as well. This meant perl could not find out (or was mixing) the two variable types. So when i changed my ajax code (as below) it worked, since $cgi->param('saveuser') both fetches GET and POST of "saveuser" (no change to the perl was needed):
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
saveuser: user_id,
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Kinda wack bug, but im glad since it works great now :D
Line 675 of CGI.pm :
# Some people want to have their cake and eat it too!
# Uncomment this line to have the contents of the query string
# APPENDED to the POST data.
# $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
Made me laugh !