I'm trying to use an api and I'm just learning how to actually implement an api using php, hopefully I'll learn to incorporate jquery. I know how to create a simple search feature through mysql and its data with php, but is there a way to create search within the api? with API, there's json/xml responses, and they're all strings, so I was wondering if the user was able to search those strings?
Thanks
First you have to send the json data to php via AJAX. Something like this:
var request;
function runAjax(JSONstring)
{
// function returns "AJAX" object, depending on web browser
// this is not native JS function!
request = getHTTPObject();
request.onreadystatechange = sendData;
request.open("GET", "parser.php?json="+JSONstring, true);
request.send(null);
}
// function is executed when var request state changes
function sendData()
{
// if request object received response
if(request.readyState == 4)
{
// parser.php response
var JSONtext = request.responseText;
// convert received string to JavaScript object
var JSONobject = JSON.parse(JSONtext);
// notice how variables are used
var msg = "Number of errors: "+JSONobject.errorsNum+
"\n- "+JSONobject.error[0]+
"\n- "+JSONobject.error[1];
alert(msg);
}
}
You then can call the variable that javascript creates by calling the $_GET['json'] variable.
strstr($_GET['json'] , $whatEverYourSearchingFor);
Related
I am trying to send some data from my AngularJS Project to a PHP Server where I am using PHP Slim but I have tried everything I know and nothing seems to work.
SERVER PHP SLIM
$app->get('/create',function() use ($app) {
$data = $app->request()->params();
response_json(200,"DB: User Created",$data);
});
It works if I type directly from the browser
http://localhost:8888/core/users/create?login=test&password=123&name=Test&email=test#test.com&phone=12313
But if I try to send from the app using $http or $resource
var obj = { name:"Hello",email:"hello#email.com"};
$http.get('/core/users/create?',obj).success(function(data){console.log(data); });
I get an empty Array[0].
And if I try to use $resource I got an obj but not how I expected.
.factory('qServer',function($resource){
return $resource('/core/users/create?:data',{data: '#data'});
});
var obj = { name:"Hello",email:"hello#email.com"};
var send = JSON.stringify(obj);
//console.log(lol);
qServer.get({data:send},function(data) { console.log(data) });
With this code I get an Object like that:
data: Object
{"name":"Hello","email":"hello#email_com"}: ""
Anyone could tell me what I am doing wrong?
The second argument of $http.get method is not GET params but a request config.
You want to use something like this (notice the params key in config argument and lack of ? at the end of URL):
var obj = { name:"Hello",email:"hello#email.com"};
$http.get('/core/users/create', {params: obj})
.success(function(data){console.log(data); });
See also: Q: $http get parameters does not work and config argument docs.
I am trying to send a javascript array via the url.But it fails
function viewReport(mode,someid){
if(mode==0){
var para= new Array();
para['para1'] = 'para1'||0;
para['para2']= 'para2' || 0;
console.log(para);
window.open('somePDFView/'+para,'_blank');
}else{
var para=[];
var paraelements={
para1:'anotherpara1'||0,
para2:'anotherpara2'||0
};
para[0]=paraelements;
window.open('somePDFView/'+para,'_blank');
}
}
On if part(mode=0), the para array is not sending any more and on else part (mode=1) the
para is sends like this:
somePDFView/[object Object]
Which shows the error:
The URI you submitted has disallowed characters
How can we send an array via url.I can't use Ajax (because its a popup window) or session or storing in a temporary table.Also how can we retrieve this value in the controller.
Edit:
I miss an important thing that I am using codeigniter. Then I think it disallows special characters like - &,=,[,],etc..So if any other methods available for sending data as an array?..
To send an array of params via URL from Javascript to PHP/Codeigniter, you need to follow 2 steps:
Convert your params array to JSON String and send that as a single query param.
para = JSON.stringify(para);
window.open('somePDFView?params='+para,'_blank');
Decode the query string param (i.e JSON string) at your controller
$params = json_decode($_GET['params']);
Now you can use all the params at your controller by accessing through $params.
Your code block becomes:
function viewReport(mode,someid){
if(mode==0){
var para= new Array();
para['para1'] = 'para1'||0;
para['para2']= 'para2' || 0;
console.log(para);
para = JSON.stringify(para);
window.open('somePDFView?params='+para,'_blank');
}else{
var para=[];
var paraelements={
para1:'anotherpara1'||0,
para2:'anotherpara2'||0
};
para[0]=paraelements;
para = JSON.stringify(para);
window.open('somePDFView?params='+para,'_blank');
}
}
Try this out and let me know if you still faces this issue.
You can also use Json here. Use JSON.stringify().
Note:
Don't sent long data over a URL. There is a limit for sending data via url and it will end up in a corrupted data if exceeded the limit. For large data, use POST method.
function viewReport(mode,someid){
var json;
if(mode==0){
var para= new Array();
var paraelements={
para1:'para1'||0,
para2:'para2'||0
};
para[0]=paraelements;
json = JSON.stringify(para);
window.open('somePDFView/'+json,'_blank');
}else{
var para=[];
var paraelements={
para1:'anotherpara1'||0,
para2:'anotherpara2'||0
};
para[0]=paraelements;
json = JSON.stringify(para);
window.open('somePDFView/'+json,'_blank');
}
}
If you are using php, use json_decode() to convert json into PHP variable.Also refer,
http://php.net/manual/en/function.json-decode.php
You can try to pass them as individual parameters:
var para1 = '1';
var para2 = '2';
var para= new Array();
para.push('para[]=' + para1 || 0);
para.push('para[]=' + para2 || 0);
var url = para.join('&');
alert(url)
Returns para[]=1¶[]=2. Note that this solution does not require jQuery.
Use jQuery.param() and change your data structure :
var para = {
para1:'anotherpara1'||0,
para2:'anotherpara2'||0
};
window.open('somePDFView/'+jQuery.param(para), '_blank');
The Demo jsFiddle
I'm attempting to retrieve and load a series of waypoints from a mysql database onto a map using ajax, javascript and php. The route is stored in the database using a JSON string.
This is the javascript function that is called (the parameter is the id of the route to be loaded, as there are many routes in the database):
function fetchdata(id) {
var routeID = id;
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch&rid='+routeID);
jax.onreadystatechange = function(){
if(jax.readyState==4) {
try {
setroute(JSON.parse(jax.responseText));
}
catch(e){
alert(e);
}
}
}
The php file it calls contains this if statement to seperate save and fetch commands:
//Retrieving the route from the database.
if($_REQUEST['command']=='fetch') {
$query = "SELECT * FROM Route WHERE route_id='$id'";
if(!($res = mysql_query($query))) {
die(mysql_error());
}
else {
$rs = mysql_fetch_array($res,1);
die($rs['waypoints']);
}
}
The problem that I'm having is that when the value is passed back to ajax/javascript it is just reporting an "Object Error" and is not being parsed by the JSON.parse() method. I'm not if I'm passing the wrong type of object back to ajax, but I have tried converting it to a strong also.
Any help on solving this would be greatly appreciated!
Thanks
is it possible to call a PHP function from flash and have it execute right away?
If so how could I go about doing that, because I am trying to call a PHP function that will update a users facebook status, but thus far I have been unsuccessful, so I am kind of at the end f my rope.
Any help would be appreciated, thanx!
My idea would be something similar to the following:
function updateFBStatus(newStatus)
{
// create two new instances of LoadVars, one to send and one to receive data
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
// define what should happen when the response is received,
// using 'this' to refer to dataIn and get data from it
dataIn.onLoad = onReturn;
dataOut["newStatus"] = newStatus;
dataOut.sendAndLoad(serverURL+"setFBStatus.php", dataIn, "POST");
}
You then define the setFBStatus.php file on your server to read $_POST['newStatus'] and do whatever you would normally do in php to set the facebook status. That php file can optionally echo some return values in url request format (i.e, paramName1=param1¶mName2=param2&) for your onReturn function to read, if you need to.
Have a look at AMF PHP!
Save the PHP function in facebookFunction.php and call it using a URLLoader.
var urlLoader:URLLoader = new URLLoader();
var data:URLVariables = new URLVariables();
//you can use dot syntax and/or [] syntax to add data.
data.user = "kiele";
data["someThingElse"] = "something else";
var req:URLRequest = new URLRequest("facebookFunction.php");
req.data = data;
urlLoader.load(req);
At the php side, you can read the values from the global get variable.
$user = $_GET["user"]
The way I would do it is in the flash actionscript is call a javascript function using getURL("javascript:someFunction(var-1, var-2, var-n)") http://www.adobe.com/livedocs/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001180.html
That javascript function can then do an ajax request to a php script.
EDIT:
you could just post data directly without using AJAX:
var firstName:String = "Gus";
var lastName:String = "Richardson";
var age:Number = 92;
getURL("http://www.adobe.com", "_blank", "POST");
Why you are not using a Flash API for Facebook: http://code.google.com/p/facebook-actionscript-api/ ?
I am trying to create a little ajax chat system (just for the heck of it) and I am using prototype.js to handle the ajax part.
One thing I have read in the help is that if you return json data, the callback function will fill that json data in the second parameter.
So in my php file that gets called I have:
header('Content-type: application/json');
if (($response = $acs_ajch_sql->postmsg($acs_ajch_msg,$acs_ajch_username,$acs_ajch_channel,$acs_ajch_ts_client)) === true)
echo json_encode(array('lastid' => $acs_ajch_sql->msgid));
else
echo json_encode(array('error' => $response));
On the ajax request I have:
onSuccess: function (response,json) {
alert(response.responseText);
alert(json);
}
The alert of the response.responseText gives me {"lastid": 8 } but the json gives me null.
Anyone know how I can make this work?
This is the correct syntax for retrieving JSON with Prototype
onSuccess: function(response){
var json = response.responseText.evalJSON();
}
There is a property of Response: Response.responseJSON which is filled with a JSON objects only if the backend returns Content-Type: application/json, i.e. if you do something like this in your backend code:
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($answer));
//this is within a Codeigniter controller
in this case Response.responseJSON != undefined which you can check on the receiving end, in your onSuccess(t) handler:
onSuccess:function(t) {
if (t.responseJSON != undefined)
{
// backend sent some JSON content (maybe with error messages?)
}
else
{
// backend sent some text/html, let's say content for my target DIV
}
}
I am not really answering the question about the second parameter of the handler, but if it does exist, for sure Prototype will only provide it in case of proper content type of the response.
This comes from Prototype official :
Evaluating a JavaScript response
Sometimes the application is designed
to send JavaScript code as a response.
If the content type of the response
matches the MIME type of JavaScript
then this is true and Prototype will
automatically eval() returned code.
You don't need to handle the response
explicitly if you don't need to.
Alternatively, if the response holds a
X-JSON header, its content will be
parsed, saved as an object and sent to
the callbacks as the second argument:
new Ajax.Request('/some_url', {
method:'get', onSuccess:
function(transport, json){
alert(json ? Object.inspect(json) : "no JSON object");
}
});
Use this functionality when you want to fetch non-trivial
data with Ajax but want to avoid the
overhead of parsing XML responses.
JSON is much faster (and lighter) than
XML.
You could also just skip the framework. Here's a cross-browser compatible way to do ajax, used in a comments widget:
//fetches comments from the server
CommentWidget.prototype.getComments = function() {
var commentURL = this.getCommentsURL + this.obj.type + '/' + this.obj.id;
this.asyncRequest('GET', commentURL, null);
}
//initiates an XHR request
CommentWidget.prototype.asyncRequest = function(method, uri, form) {
var o = createXhrObject()
if(!o) { return null; }
o.open(method, uri, true);
o.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
var self = this;
o.onreadystatechange = function () {self.callback(o)};
if (form) {
o.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
o.send(makePostData(form));
} else {
o.send('');
}
}
//after a comment is posted, this rewrites the comments on the page
CommentWidget.prototype.callback = function(o) {
if (o.readyState != 4) { return }
//turns the JSON string into a JavaScript object.
var response_obj = eval('(' + o.responseText + ')');
this.comments = response_obj.comments;
this.refresh()
}
I open-sourced this code here http://www.trailbehind.com/comment_widget