I want to use this jquery plugin to get values from database...
I create jquery ajax code and HTML to get values from database:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<link href="http://ivaynberg.github.com/select2/select2-3.3.2/select2.css" rel="stylesheet" type="text/css" />
<script src="http://ivaynberg.github.com/select2/select2-3.3.2/select2.js"></script>
</head>
<body>
<select id="test" style="width:200px;">
<option value=""><option>
</select>
<script>
$('#test').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
}
});
</script>
</body>
and json.php code:
<?php
$pdo=new PDO("mysql:dbname=ddd;host=localhost","ddd","ddd");
$statement=$pdo->prepare("SELECT id,ime_prezime FROM radnici");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
when I run php code i get json:
[{"id":"1","ime_prezime":"Pera Peric"}]
s the problem is not with php code... what is wrong in my html/jquery code?
I dont get anything, I cant fetch values from json.php file
UPDATE:
I find error is was json format, but now I cant save values that I get , so when I click values just disapear...
<input id="test" style="width:300px;">
<select multiple id="test" style="width:300px"></select>
<script>
function formatValues(data) {
return data.ime_prezime;
}
$('#test').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
},
formatResult: formatValues
});
</script>
You need to return id, text pair and use following structure;
<input type="hidden" name="test" id="test" style="width:200px;"/>
$('#test').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
}
});
You can see demo here: http://jsfiddle.net/huseyinbabal/68fD2/1/ . In demo, I have used local data, but it works with your ajax code like above.
Edit:
If you want to do that as in your demo, you can use following;
function formatValues(data) {
return data.ime_prezime;
}
var test = $('#test');
var data = [{"id":"1","ime_prezime":"Pera Peric"},
{"id":"2","ime_prezime":"Something else"},
{"id":"3","ime_prezime":"Lorem"},
{"id":"4","ime_prezime":"Ipsum"}
];
$(test).select2({
data:{results: data, text: 'ime_prezime'},
width: "300px",
formatResult: formatValues,
formatSelection: formatValues,
multiple: true
});
Here is a working demo: http://jsfiddle.net/huseyinbabal/68fD2/6/
Related
i new to use laravel framework,,
i want to passing datepicker value after user select the date
i try to give button, to submit that value, but i got error.
Anybody have idea to passing value without button ?
this is my blade :
<form id="myform" name="myform">
<input type="text" id="datepicker" name="datepicker" value="Date"/>
<input placeholder="Submit" type="button" id="submitMe" style="width:
100px;"/>
//can i passing this value without button?
<script>
$('#datepicker').datepicker({
format : 'yyyy-mm-dd'
});
</script>
</form>
<script>
$("#submitMe").click(function() {
$.ajax({
type: 'POST',
url: "/index/getDate",
method: "POST",
dataType: "json",
data: $('#myform').serialize(),
success: function(data) {
console.log("Done");
}
});
return false;
})
</script>
this is my route :
Route::post('index/getDate', 'UserController#getDate')-
>name('Usercontroller.getDate');
this is my controller :
function getDate(Request $request){
$date = urldecode ($_GET['datepicker']);
echo "chosen date is: ".$date;
}
i try to get output like this :
thankyou so much, if somebody want to help me :))
try this in your controller:
function getDate(Request $request){
$date = $request->datepicker;
return "chosen date is: ".$date;
}
then in your view:
<input type="text" id="datepicker" name="datepicker" value="Date"/>
<label id="dateSelected"></label>
<script>
$("#submitMe").click(function() {
$.ajax({
type: 'POST',
url: "/index/getDate",
method: "POST",
data: $('#myform').serialize(),
success: function(data) {
console.log(data);
$('#dateSelected').text(data);
}
});
return false;
})
</script>
you pass the form data with POST method, so you can get the parameter with
$request->input('datepicker');
I am writing a script that sends an ajax request. The Cloud seems to response with the JSON, but how can I display the data from the JSON on my webpage?
Here the link for the pretty printed JSON.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<script>
function myFunctionPost() {
jQuery.ajax( {
url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_77877E443B666B7FED2F?$format=json',
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
success: function( response ) {
console.log(response);
},
error : function(error) {
console.log(error);
}
} );
}
</script>
</body>
</html>
To achieve this you can use JSON.stringify() space argument. You will also need to wrap the output with <pre> </pre> will preserve the line spacing.
function myFunctionPost() {
$.ajax( {
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'GET',
success: function(response) {
$('#pp').html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
},
error: function(error) {
console.log(error);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<p id="pp"></p>
</body>
</html>
Source: Does jQuery have a JSON/javascript object to HTML pretty print function similar to PHP's var_dump?
By var responseObject = json.parse(response) to make a javascript object.
And then do as you would with JS object?
Hard to tell exact code without knowing what do you wanna display, in what HTML.
I'm running a database with itemID's and a shelfnumber for every itemID..
As the user enters an itemID I want it to run through my database to get the shelfnumber using Ajax/PHP. Then post the shelfnumber back so the user can see where to find the item. (The items are in a room and are marked with unique ID's and shared shelfnumbers.) I need to use the onChange method (or anything similar) beacuse I want it to work like a tip/search engine. In other words automatic..
I'm totally new to ajax and I can't seem to get this to work at all.. No result is given and i'm at a roadblock right now.. Any form of help will be very appreciated
HTML
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
}
});
});
</script>
</head>
<body>
<a>Enter Item ID 1:</a>
<input id="target" type="text" name="itemID" required />
<div id="hyllplacering">ENTER Shelfnumber here: </div>
</body>
</html>
PHP
<?php
$con = mysql_connect("localhost", "root", "") OR die(' Could not connect');
$db = mysql_select_db('book1', $con);
$itemID = filter_input(INPUT_POST, 'itemID', FILTER_VALIDATE_INT);
$query = "SELECT Hyllplacering from booking WHERE itemID = $itemID";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo json_encode(array('itemID' => $itemID, 'Hyllplacering' => $row['Hyllplacering']));
?>
JavaScript is executed as soon as it is encountered. You bind the Event to an Element before it is available.
You need to wrap the script in a document.ready body.
As the other answers mentioned you want to use the success callback instead of done.
<script>
$(document).ready(function(){
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
})
.success(function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
});
});
});
</script>
You may add a sentence in AJAX function
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
success:function(data){
console.info(data);
}
})
to monitor what your PHP responsed, it's more easy to check what's wrong.
I think you incorrect to use the done method of the Ajax object. I am pretty sure you wont have your response available in that scope. Try to do it like..
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
},
error:function(response){
alert('error '+response);
};
})
});
I'm new to programming, and I'm trying to call a function when the user inputs data and clicks submit button. I'm using Yii2 and I'm not familiar with Ajax. I tried developing a function, but my controller action isn't called.
Here is the example code I'm trying:
views/index.php:
<script>
function myFunction()
{
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},
success: function (data) {
alert(data);
}
});
}
</script>
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<select id="searchby">
<option value="" disabled="disabled" selected="selected">Search by</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input type="text" value ="" name="searchname", id="searchname">
<button onclick="myFunction()">Search</button>
<h3> </h3>
Controller:
public function actionSample(){
echo "ok";
}
My problem is that when I click on the Search button nothing happens, and when I try to debug it, the debugger runs no code!
This is sample you can modify according your need
public function actionSample()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$searchname= explode(":", $data['searchname']);
$searchby= explode(":", $data['searchby']);
$searchname= $searchname[0];
$searchby= $searchby[0];
$search = // your logic;
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'search' => $search,
'code' => 100,
];
}
}
If this will success you will get data in Ajax success block. See browser console.
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {
searchname: $("#searchname").val() ,
searchby:$("#searchby").val() ,
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
console.log(data.search);
}
});
you have to pass _csrf tokin as a parameter
_csrf: yii.getCsrfToken()
or you can disable csrf valdation
The correct way to get the CSRF param is this:
data[yii.getCsrfParam()] = yii.getCsrfToken()
I am working on ZEND Framework that is new to me and same is the case with the AJAX. I tried lots of example but non of them work.
Please tell me I am wrong in this code.
home.phtml
<select name="year" onchange="saveChanges(this);">
<option value="najam">Najam</option>
<option value="Ali">Ali</option>
<option value="Hassan">Hassan</option>
<option value="Hassam">Hassam</option>
</select>
<script type="text/javascript">
function saveChanges(object){
$.ajax({
method :'POST',
url: 'home',
data: object.value,
cache: false,
error: function(e){
alert(e);
console.log("error" + e);
},
success: function(response){
// A response to say if it's updated or not
alert("Success" + object.value);
console.log("Success");
}
});
}
</script>
HomeAction
if($this->_request->isXmlHttpRequest()){
//do this
}
else {
//do this
// It always in the else Part.
}
Although it print success message on console and also on the javascript alert message.
Help me if am wrong with this code
method :'POST'
to
type: "POST"
I always use $this->_request->isXmlHttpRequest() to detect a ajax request and always working.
Sorry i speak English not well
Update:
Controller:
final class IndexController extends Zend_Controller_Action
{
final public function indexAction(){
if($this->_request->isXmlHttpRequest()){
header('Content-type: application/json;charset=UTF-8');
exit(json_encode(($this->_request->getPost())));
}
}
}
View:
<select id="year" name="year">
<option value="najam">Najam</option>
<option value="Ali">Ali</option>
<option value="Hassan">Hassan</option>
<option value="Hassam">Hassam</option>
</select>
<script type="text/javascript">
$(function(){
$("#year").change(function(){
var _this = $(this);
$.ajax({
type :'POST',
url: "", // empty string means current URL
data: {year: _this.attr("value")},
dataType: 'json',
cache: false,
error: function(e){
console.log(e);
},
success: function(response){
console.log(response);
}
});
});
});
</script>
Here is the source code:
http://www.mediafire.com/?hvv4830macfl0wm
Hope the help!
In Zend Framework you can add a ContextSwitch to your actions.
Based on the Context the action will render in the relevant template.
e.g.
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'xml')
->initContext();
}
In your case
$contextSwitch->addActionContext('home', 'ajax')
See here http://framework.zend.com/manual/1.8/en/zend.controller.actionhelpers.html
Edit: That's for ZF1 though, if you're using ZF2 you might want to look into View Strategy
http://framework.zend.com/manual/2.0/en/modules/zend.view.quick-start.html#creating-and-registering-alternate-rendering-and-response-strategies