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 !
Related
I've seen several questions here with the similar subject but I can't find anything which is relevant to my situation. I am trying to build jQuery code that is able to build a list of items to save it in an inventory database and I am using .post() those to a additems.php that will add them to that database (after sensitization), as well as the current path name so the .php can send the user back to the same page.
The behavior I am getting is nothing whatsoever with no console error (except the 'this works' alert when I leave that in.) The behavior I am looking for is, the page should redirect to additems.php as an html form action would, execute the code there and redirect back to this page.
Here is my piece of code:
$(document).ready(function(){
$("#button").click(function(){
alert("this works");
var itemsarray = ['itemname'];
var itemattributesarray = ['itemattribute'];
var quantitiesarray = ['1'];
$.post('additems.php', {
items:{items: itemsarray},
itemattributes:{itemattributes: itemattributesarray},
quantities:{quantities: quantitiesarray},
returnpath: window.pathname
});
});
});
Thank you for your time and any suggestions. I've never used this site so please let me know how I can improve my question as well, if you have the time.
An alternative way is,
$.ajax({
'url':'additems.php',
'method' : 'POST',
'data':{
'items':itemsarray,
'itemattributes':itemattributesarray,
'quantities' : quantitiesarray
},
success: function(data){
//here you will get ajax response
console.log(data);
}
});
I'm trying to create a game with symfony in which there are warriors. Each warrior has a level. To understand jquery and ajax which i'm new with, i want to create a simple button which when clicked use jquery ajax to get the warrior id and make him lvl up. Here is the level up method controller :
public function warriorLevelUpAction(Warrior $warrior){
$warrior->levelUp();
return $this->render('StormbladesWarriorBundle:Warrior:homepage.html.twig', array(
'warrior' => $warrior
));
}
Here is my Jquery ajax method
$('#cpt').click(function() {
$.ajax({
url: "/stormblades/web/app_dev.php/warriors/levelUp/"+{{ warrior.id }},
error: function(xhr, error){
console.debug(xhr);
console.debug(error);
}
});
And here is my routing :
stormblades_warrior_leveluppage:
path: /warriors/levelUp/{id}
defaults: { _controller: StormbladesWarriorBundle:Warrior:warriorLevelUp }
requirements:
id: \d+
Obviously, this doesn't work, i got a beautiful error 500. Any help and suggestion on what's wrong would be appreciate.
A couple of things stand out to me.
Firstly, your warriorLevelUpAction function requires a warrior object, but in the request you are only passing an id. Therefore, you require an extra step to get the warrior by it's ID then level up. For example:
public function warriorLevelUpAction($id){
$warrior = $this->getDoctrine()
->getRepository('StormbladesWarriorBundle:Warrior')
->find($id);
$warrior->levelUp();
return $this->render('StormbladesWarriorBundle:Warrior:homepage.html.twig', array(
'warrior' => $warrior
));
}
Secondly, if you are only ever going to call this function through AJAX, then you could just return a HTTP 200 Status OK, rather then render homepage.html.twig. You don't have to but, I just find it more efficient. Something like this should be fine:
$response = new Response(Response::HTTP_OK);
return $response;
Lastly, in your AJAX code, the url should be: "/warriors/levelUp/"+{{ warrior.id }}, unless there is a specific reson you are using the full path. This path will work in both development and production, whereas your current code will always run in Debug Mode.
everything said above +....
allow POST in your route through the method : POST attribute like this ( probably the reason of the 500)
defaults : ......
requirements:
_method: POST
As jrmck said , in your controller, either return a Reponse object or
return $this->container->get('templating')->renderResponse('..:page.html.twig',
array( 'var' => $var ));
If you can, use FOSJSRoutingBundle (symfony routes for javascript). Calling routes by URL is not that great if you change of adress or anything. https://github.com/FriendsOfSymfony/FOSJsRoutingBundle.
Or also
url: "{{ path('my_route_php")}}",
Im building a windows 8 app (html)
And have a api im fetching data from.
I keep getting this error however
0x800a138f - JavaScript runtime error: Unable to get property 'json' of undefined or null reference
in my scripts1.js file. then my program crashes -_-.
Here is the the code i use
$(function () {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh, 10000);
var url = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=132';
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json', function (data) {
jQuery('#ticker').html(data['query'].results.json.return.markets.DOGE.lasttradeprice);
jQuery('#ticker').append(' ' + data['query'].results.json.return.markets.DOGE.secondarycode);
jQuery('#ticker2').html(data['query'].results.json.return.markets.DOGE.lasttradetime);
jQuery('#ticker3').html(data['query'].results.json.return.markets.DOGE.volume);
});
}
This is located in scripts1.js Then i use ect.
It works everything comes and displays just get that error. Not sure what to do.
Seems like data['query'].results is undefined. Pasting the JSON you get will help.
Also, one small piece of advice: If you are going to access an in-depth attribute and, specially, a DOM node several times, you might want to recycle a reference to it rather than travelling again and again to fetch it for performance reasons. Something like this:
var ticker = jQuery('#ticker');
var DOGE = data['query'].results.json.return.markets.DOGE;
ticker.html(DOGE.lasttradeprice);
...
It looks like, occasionally, the API will send back some JSON that, when parsed, doesn't contain a results object. To mitigate this you should put a condition in to catch this eventuality.
if (data.query.results) {
jQuery('#ticker').html(data['query'].results.json.return.markets.DOGE.lasttradeprice);
// rest of DOM update code
}
Demo.
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.
I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});