simple search using restful api - ajax

I'm a complete noob trying out my hands on Ajax and Jquery. By following an online tutorial, I successfully made a search engine using MySQL as the backend database;
<script>
$(function() {
$(".search_butn").click(function() {
// getting the value that user typed
var searchString = $("#input_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "search.php", //server-side script to db (mysql)
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
<form method="post" action="search.php">
<div id="DIV">
<input type="text" name="search" id="input_box" class='input_box'/>
<input type="submit" value="Search" class="search_butn" />
</div>
</form><br/>
<div>
<div id="searchresults"> </div>
<ul id="results" class="update">
</ul>
</div>
Now I want to go a step further by searching using a RESTful api like this one from Solr http://localhost:9090/solr/select?q=employee%3A%28james+blunt%29&wt=json&indent=true
I need someone to please show me how I can go about doing this.

To create a RESTful API, you could write some PHP code to chop down the url of the request.
You should make Apache - your webserver I suppose - redirect all URLs with a certain prefix to this PHP script.
So, say a user requests http://www.somename.com/my_api/some/shiny?suffix, you want Apache to redirect this URL to the script my_api.php, such that my_api.php can chop down the entire URL and do stuff based on that.
For Apache doing so, read up on apache mod_rewrite: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
For more detailed treatment of RESTful APIs, I can suggest this tutorial: http://www.restapitutorial.com/

Related

Login with ionic and material design

I have an ionic project with side menu and all.
Now I want to add in simple way and login cool form, like
http://ionicmaterial.com/
But the issue I didn't see any examples how to add it in exciting project that it will load the login form first and after that will redirect to regular page.
My project looks like:
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.placeslists', {
url: "/placeslists",
views: {
'menuContent': {
templateUrl: "templates/placeslists.html",
controller: 'PlaceslistsCtrl'
}
}
})
How can I add the login page with authentication (token) that it will load first and how can I add the material for login page in easy way.
Thanks!!!
For implementing login, you would require these things
A Login State
A Login Template
Logic to handle your token
$stateProvider
.state('Login', {
url: "/Login",
templateUrl: "app/templates/Login.html"
})
<ion-view view-title="Login" align-title="left">
<ion-content style="background: url(img/login.jpg) center; background-size: cover;">
<div class="hero no-header flat">
<div class="content">
<div class="app-icon"></div>
<h1>Thronester</h1>
</div>
</div>
<div class="list">
<ion-md-input placeholder="Username" highlight-color="balanced" type="text" ng-model='user.username'></ion-md-input>
<ion-md-input placeholder="Password" highlight-color="energized" type="password" ng-model='user.password'></ion-md-input>
</div>
<div class="padding">
<button ui-sref="app.profile" class="button button-full button-assertive ink">Login</button>
</div>
<div class="button-bar social-login">
<button class="button button-small button-border icon-left ion-social-google button-assertive-900" ng-click='DoLogin(user)'>Login</button>
</div>
</ion-content>
</ion-view>
In your DoLogin function, you would need to handle hit your API for login, and receive your token. You would need to store this token. I use SQLlite plugin to store my token into a token table. There are different ways of storing token.
SQLite plugin
Local Storage
WebSQL
File ngCordova
and many more, I can provide you with code snippet using SQLlite.
var DB = window.sqlitePlugin.openDatabase({name: "Token.db", location: 1})
var CreateQuery = 'CREATE TABLE IF NOT EXISTS Token (id integer primary key, access_token TEXT)'
var InsertQuery = 'INSERT INTO Token (access_token) VALUES (?)'
var selectQuery = 'SELECT access_token FROM Token WHERE id = 1'
var Token = // the token you get from your server, make a $http resquest and get it
$cordovaSQLite.execute( DB,CreateQuery ).then(function () {
//table created
})
$cordovaSQLite.execute(DB, InsertQuery, [Token]).then(function(){
// token inserted into table
})
$cordovaSQLite.execute(DB, selectQuery).then(function (res) {
//getting token from table
$rootScope.TokenFromTable = res.rows.item(0).access_token;
})
Don't just copy paste from the code (it wont work), you would need build the logic on where to place all this code and in which order.
After you have received the authToken, you can set it as a common header for all you $http requests, and when user clicks on logout, just drop the table or drop the DB. ( go through the blogs in the link)
you can add new state login in app.js which will load login.html and controller and load it by defalut like:
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
and in login controller when you successfully login then you can redirect it to any page using $state.go('app.placeslists'); it will load regular pages.
I found at the end all info with demos
you can find also in:
https://github.com/zachsoft/Ionic-Material

Send all Form Data in WordPress ajax

<?php
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
email:email
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
<?php
}
?>
Hi , I tried the ajax integration in wordpress. The above example is from codex of wordpress. I am not sure. How to send the form data in ajax.
Previously i tried like
var data = {
action: 'my_action',
email:email
};
That above data only send the value to db and it save perfect, but i need to store all those value like for example
Here is the form:
<form action="" method="post">
<label></label>
<input type="text" name="fname" value=""/>
</form>
I also tried to send all value like
var data= {
action: 'my_action',
email:email,
fname:fname
};
But it doesn't work. For individually email only send and enter properly in db. Is the way to send all value through ajax.
Thanks.
You will need to get the values of each input
var fname = $('input[name="fname"]').val();
if you only have a few inputs this can be done with a few of these statments but if you have loads and of different types you will need to loop through them. There are number of good post on here for doing that.
e.g. jquery get all input from specific form

How can I upload files and form data with jQuery?

I would like to upload a file and form data with Jquery. My html;
<form id="kayit" action="" method="post" enctype="multipart/form-data">
<input type="text" name="yazi" />
<input type="file" id="resim" name="resim"/>
<a onclick="kontrolet();" id="yolla">Yolla</a>
</form>
<div id="sonuc"></div>
and my js;
function kontrolet()
{
var veriler = jQuery("#kayit").serialize();
//console.log(veriler);
jQuery.ajax({
type:'POST',
url:'form.php',
data: veriler,
processData: false,
beforeSend: function () {
jQuery("#sonuc").html("Lütfen Bekleyin....");
},
success: function(sonuc)
{
jQuery('#sonuc').html(sonuc);
}
});
}
I have get filename, but this not working. Help ?
You cant upload a file through ajax using simple javascript (one of the reasons is that javascript cannot access the file system at the moment, so it cannot read content to send it on an AJAX request).
For that kind of feature you have to use some plugin that uses action script or java. There are many available online (search ajax file upload), but in my opinion you are better off using an old fashioned POST.
I've used jQuery to upload file in the background using the AjaxUpload plugin - it builds an iFrame in the background, clones your form and submits the clone to that.

Render different Zend forms based on Ajax post request

I am trying to display different forms based on user type using Ajax post request. The request response works fine but I don't know how to display the form. For example, if the user selects parent then I want the parent form to be displayed and so on. I'm using ZF 1.12.
public function init() {
$contextSwitch = $this->_helper->getHelper('AjaxContext');
$contextSwitch =$this->_helper->contextSwitch();
$contextSwitch->addActionContext('index', 'json')
->setAutoJsonSerialization(false)
->initContext();
}
public function indexAction() {
$this->view->user = $this->_userModel->loadUser($userId);
//if($this->_request->isXmlHttpRequest()) {
//$this->_helper->layout->disableLayout();
//$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isPost()){
$type = $_POST['type'];
$this->view->userForm = $this->getUserForm($type)->populate(
$this->view->user
);
}
}
And here's what I have on the client side. What do I need to write in the success section?
<script type="text/javascript">
$(document).ready(function(){
$('#userType').on('change', function(){
var type = $(this).val();
select(type);
});
});
function select(type) {
$.ajax({
type: "POST",
url: "admin/index/",
//Context: document.body,
data: {'type':type},
data: 'format=json',
//dataType: "html",
success: function(data){
// what to do here?
},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
});
}
</script>
<form id="type" name="type" method="post" action="admin/index">
<select name='userType' id='userType' size='30'>
<option>admin</option>
<option>parent</option>
<option>teacher</option>
</select>
</form>
<div id="show">
<?php //echo $this->userForm;?>
</div>
If your ajax request form returns you the HTML from the Zend_Form, you could simply write the HTML in the #show div.
In you view you will need to do this :
echo $this->userForm;
This way, all the required HTML will be written on the server side, before sending the response to the HTML page. In the HTML page you then just have to write the response in the right location with the method $('#show').html(data). You also have to make sure that each of your forms has the right action when you render them.
The other option would be to have all three forms hidden in your page (through Javascript) upon loading and based on the select (Generated with JS), display the right form. This way you don't have to load data from an external source and if someone have JS disabled, he still can use the application. On the other hand, this method will have each page load about 1/2 a KB more of data.

API trouble with jQuery / AJAX

This is my second day with jQuery & AJAX. I've done as much googleing as I know to do for this. But, with not knowing what I'm looking for, I'm lost. This is very close to working, but I can't quite figure it out.
I'm trying to use my company's ("xyz") API, and it won't work when I have the form action = a url to the page.
I've done this many times in PHP. The APIs URL is:
xyz.com/getdata.php?from=tt&isbn={variable_int}
Can someone give me a hand?
<form method="post" action="xyz.com/getdata.php" id="searchForm">
<input type="text" name="isbn" placeholder="Search..." />
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
<div id="result"></div>
{literal}
<script>
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
term = $form.find( 'input[name="isbn"]' ).val(),
url = $form.attr( 'action' );
// Send the data using post and put the results in a div
// $.post( url, { doSearch: "Search", isbn: term } ,
$.post( url, { from: "tt", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).html( content );
}
);
});
</script>
Thanks so much (in advance)!
Cross-domain with an AJAX request is not as easy as it seems.
Here's an interesting link you should read: http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
I'm not sure but if you use the string below
xyz.com/getdata.php?from=tt&isbn={variable_int}
the method to send data is "get". The form uses the method "post". I think there is a conflict.

Resources