I'm trying to use an API to return data for 2 string variables: "_id" and "name". I'm connected correctly because I've tested the error feature by tweaking the API key and I get an error. I don't get that when I put in the correct API. However, what I do get is [Object object].
Here is the ajax code I am using (without the api keys):
$(document).ready(function() {
$("#submit-button").click(function() {
$.ajax({
method: "GET",
url: "myurl",
headers: { "x-api-key": "myapikey" },
data: $("#cdn :input").serialize(),
dataType: "json",
success: function(data){
$(".result").text(data);
},
error: function(d) {
$(".result").html(d.responseText);
}
});
});
});
And here is the HTML:
<html>
<body>
<div id="cdn">
<div>
<button id="submit-button">Submit</button>
</div>
<div class="result"></div>
</body>
</html>
Any help you can offer would be greatly appreciated. I need to be able to get the responses displayed.
The variable "data" in your "success" function is actually a json object.
So you need to get the property in that object.
Let's say the response from the server has a property named "name"
you would have to do this:
$(".result").text(data.name);
Related
I'm using the following code to receive some content from a page called filter.PHP. But the issue is the buttons become not clickable once fetched.
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "POST",
url: "filter.php",
dataType: "html",
success: function(response) {
$("#responsecontainer").html(response);
}
});
});
});
</script>
I have buttons like these on the filter.php file.
<button onclick="location.href='details.php?id=<?php echo htmlspecialchars($result->nid); ?>'" class="buttonnew">Details </button>
Any help would be much appreciated.
You have to add the event listener from JavaScript, when you fetch the html from an ajax response.
document.querySelector('.buttonnew').addEventListener('click', () => { location.href=''});
Or
document.querySelectorAll('.buttonnew').forEach(btn => { btn.addEventListener('click', () => { location.href='';})});
I am trying to make an example of Ajax request with Laravel 5.4.
The test example is simple, just enter a numeric value in an input = text field in my View and leave the field to send to the Controller, then add + 10 to that value and then return that value to my View so that it can displayed on an alert.
HTML : viewteste.blade.php
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<form action="">
Valor: <input type="text" id="valor" name="valor" />
</form>
</body>
</html>
JS: The js file is inside viewteste.blade.php, I just split it to make it easier to interpret.
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$("#valor").on('blur', function()
{
valor = $(this).val();
$.ajax({
type:'POST',
url:"{{ URL::to('/teste/valor') }}",
dataType: 'JSON',
data: {
"valor": valor
},
success:function(data){
alert('Success');
},
error:function(){
alert('Error');
},
});
});
});
</script>
Route
Route::get('/teste', 'TesteAjaxController#index');
Route::post('/teste/valor', 'TesteAjaxController#valor');
Controller
class TesteAjaxController extends Controller
{
public function index()
{
return view('painel.viewteste');
}
public function valor(Request $request)
{
$valor= $request->input('valor');
$valor += 10;
return $valor; // How do I return in json? in case of an error message?
}
}
Always when I try to send the request via ajax it goes to alert ('Error'). is it that I'm doing something wrong in sending the ajax or route?
to return a json response. you need to use.
response()->json([
'somemessage' => 'message',
'valor' => $valor
]);
UPDATE: you are getting an error alert because i think your route method doesnt match your controller methods.
Route::post('/teste/valor', 'TesteAjaxController#valor');
where in your controller you have
public function cep() ...
I am using select2 plugin(ivaynberg.github.io/select2). I am trying to display a dropdown(select). It is getting all the items in data.php as options. However select2 is meant to be autocomplete plugin and should search for the search term a client input, and display the matching results only. At the moment it is displaying all the items and not getting the search results. Sorry for my language
data.php is echoing out this:
[{
"id": "1",
"text": "item1",
"exercise": "blah text"
}, {
"id": "2",
"text": "item2"
}
]
The code is:
$(document).ready(function () {
$('#thisid').select2({
minimumInputLength: 2,
ajax: {
url: "data.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {
results: data
};
}
}
});
});
and the input is:
<input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />
I want to find a clue, I am quite new to this plugin and have spent a day for looking at examples.
select2 will not do AJAX if attached to a standard select form control. It MUST be attached to a hidden input control to load via AJAX.
Update: This has been fixed in Select2 4.0. From Pre-Release notes:
Consistency with standard <select> elements for all data adapters, removing the need for hidden <input> elements.
It can also be seen in function in their examples section.
I guess user2315153 wants to receive multiple remote values, and incorrectly assigning select2() with ajax call to a <select> element.
The correct way to get remote values, is using a normal <input> element, and if is desired multiple values, inform the "multiple" parameter on method call. Example:
<input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />
<script>
$('#thisid').select2({
minimumInputLength: 2,
multiple: true,
ajax: {
...
The <select> element CAN NOT be used to remote values
UPDATE: As of select2 4.0.0, hidden inputs has deprecated:
https://select2.github.io/announcements-4.0.html#hidden-input
This means: Instead of using an input to attrib select2 plugin, use an SELECT tag.
Pay attention: it's easy to use any format of json from your server. Just use "processResults" to do it.
Example:
<select id='thisid' class='select2-input select2'></select>
<script>
$("#thisid").select2({
multiple: true,
closeOnSelect: true,
ajax: {
url: "myurl",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, page) { //json parse
console.log("processing results");
//Transform your json here, maybe using $.map jquery method
return {
results: yourTransformedJson
};
},
cache: (maybe)true
}
});
</script>
I try the code, it works well. I think you not include jquery framework or check the path of js and css.
<!DOCTYPE html>
<html>
<head>
<link href="select2.css" rel="stylesheet"/>
<script src="//code.jquery.com/jquery-latest.min.js"></script>
<script src="select2.min.js"></script>
<script>
$(document).ready(function() {
$('#thisid').select2({
minimumInputLength: 2,
ajax: {
url: "data.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {
results: data
};
}
}
});
});
</script>
</head>
<body>
<input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />
</body>
</html>
I think no need to go with hidden input element. You can give a try, get plain html data from ajax call and set it in and then init select2 resetting method. Here's code snippet
HTML
<select id="select" name="select" class="select2">
<option value="" selected disabled>Please Select Above Field</option>
</select>
Javascript
$.ajax({
type: "POST",
cache:false,
url: YOUR_AJAX_URL,
success: function(response)
{
$('#select').html(response);
}
});
$('#select').select2("val","");
Ajax Response :
<option value="value">Option Name</option>
.
.
.
<option value="value">Option Name</option>
After much reading, I decided to change the select2.js itself.
At line 2109 change it to
this.focusser.attr("id", "s2id_"+this.select.context.id);
If your input tag is as so
<select id="fichier">
Hence your input tag that is searching through the list will have an id of s2id_fichier_search
As far as I know, there shouldn't be a conflict and THIS will allow you to have multiple select2 on the same page and run your functions (including .get, .post) through their events eg.
$(function() {
$('#s2id_fichier_search').keyup(function() {
console.log('Be Practical')
})
}
So this will run like if you were to use
<select id="fichier" onkeyup="console.log('Be Practical')">
In my case, an older version of select2 library was causing the issue, make sure that you include the latest version of js and css in the web page.
I can't find a working solution for this problem:
I want to update a part of my view without reloading it,
I have a form that collects the data to be passed to the controller,
the controller needs to get the data from the DB and spit out a JSON
to the view so that it can be filled with such data.
I tried to adapt this http://tutsnare.com/post-data-using-ajax-in-laravel-5/ but it's not working at all. The data collected is not reaching the controller.
My uderstanding is the javascript part in the view should listen to the click event and send a GET request to the controller, the controller checks if the data is sent through AJAX, gets the data from DB then returns the response in JSON form, the view is then updated.
Please, does anyone have a working example or can explain?
Simple working example using JQuery:
In you routes.php file:
Route::post('/postform', function () {
// here you should do whatever you need to do with posted data
return response()->json(['msg' => 'Success!','test' => Input::get('test')]);
});
and in your blade view file:
<form method="POST" action="{{ url('postform') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="text" name="test" value="" />
<input type="submit" value="Send" />
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$(document).ready(function()
{
var form = $('form');
form.submit(function(e){
e.preventDefault();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: form.serialize(),
success: function(data)
{
console.log(data);
if(data.msg){
alert( data.msg + ' You said: ' + data.test);
}
}
})
});
});
});
</script>
As you can see, most of the logic is done in JavaScript which has nothing to do with Laravel. So if that is not understandable for you, I'd recommend to look for jQuery ajax tutorials or rtfm :)
I have experienced submitting a modal form without reloading the entire page. I let the user add option to the dropdown and then repopulate the items on that dropdown without reloading the entire page after and item is added.
you can have custom route to your controller that handles the process and can be called by javascript and will return json
Route::get('/profiles/create/waterSource',function(){
$data = WaterSource::orderBy('description')->get();
return Response::json($data);
});
then the javascript
<script>
$(document).on('submit', '.myForm-waterSource', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
$.get('{{ url('profiles') }}/create/waterSource', function(data) {
console.log(data);
$.each(data, function(index,subCatObj){
if (!$('#waterSource option[value="'+subCatObj.id+'"]').length) {
$('#waterSource').append('<option value="'+subCatObj.id+'">'+subCatObj.description+'</option>');
}
});
$('#myModal-waterSource').modal('hide');
$('#modal-waterSource').val('');
});
}
});
e.preventDefault();
});
</script>
You can view the full tutorial at Creating new Dropdown Option Without Reloading the Page in Laravel 5
I have a simple ASP MVC3 #Html.TextBox that I'm using to input search criteria. However, I need to append the value to the URL in an Ajax call as a query string. How would I go about this? Below is the HTML in the view:
<div class="editor-field">
#Html.TextBox("searchString")
<span onclick='GetCompName(searchString);'>
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
And here is the Ajax
function GetCompName(searchString) {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + searchString + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}
I will also want to output the returned value into another text box. If anyone knows how to do that that would be really helpful as well. Thanks!
the basic problem with your code is the searchString in onclick='GetCompName(searchString); always gonna be literally "serchString", you must specified the parameter in base the value in the input, like this $('.searchbox').val()
keep your javascript unobstructive.
HTML code
<div class="editor-field">
#Html.TextBox("searchString", null, new { #class = "serachbox" })
<span class="searchbox-trigger">
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
Set de handler for the event span click
$(document).ready(function() {
$('.searchbox-trigger').click(GetProgramDetails);
});
and your ajax request
function GetProgramDetails() {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + $('.searchbox').val() + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}