I have called ajax request in some interval of time. Now, if I pressed the back button after success ajax then, the browser displayed all of my HTML code instead of displaying HTML elements.
<script>
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
}
});
}, 1000);
</script>
if($request->ajax()){
foreach ($devices as $device){
$latestUpdate = Carbon::parse($device->updated_at);
$diff = Carbon::now()->diffInMinutes($latestUpdate);
if($diff > 2){
Device::where('id',$device->id)->update(['status'=>'3']);
}
}
return response()->json(['msg' => "successfully checked"]);
}
I had expected to render the HTML elements, but it displayed.
{
"msg": "successfully checked"
}
Same things happened when I send HTML in json.
if($request->ajax()){
$returnHtml = view('alerts.index', compact('threshold'))
->with('alerts', $alerts)->render();
return response()->json(['html' => $returnHtml, 'data' => $alerts]);
}
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('alerts.index')}}',
dataType: 'json',
success: function (data) {
var formatedhtml = $('<div>').html(data.html).find('table');
$('table').html(formatedhtml);
}
});
}, 5000);
In this case it display
Instead of returning as json return data as array:
Try something like this
return ['html' => $returnHtml, 'data' => $alerts];
There's nothing wrong with how you are receiving the data when you use return response()->json(['html' => $returnHtml, 'data' => $alerts]);
If you want to actually put the html that you received from your server into an element in your page, you will need to use Element.innerHTML (https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) so that the html will not be escaped by the browser.
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
// this is the table where you want to place the received table contents
var my_table=$('#my-table')
// we turn the data we received from the server into a jQuery object, then find the table we want data from
var received_table=$(data.html).find('table')
// switch out the table contents
my_table.html(received_table.html())
}
});
}, 1000);
EDIT: Since you are using jQuery, I changed the answer to fit.
Related
When a user clicks 'buy now', I want the transaction to happen and the div to eventually be faded out and removed once being processed by the controller. Everything in the controller works as it should, but when I put the function in the success, it isn't called. However it works when the function is placed outside the success. Additionally, a window.alert() somehow works when there's a success.
Here is my script, everything works in regards to the controller etc
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).attr("id");
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'json',
success: function () {
window.alert("THIS ALERT COMMAND WORKS BUT THE FUNCTION DOESN'T!");
$(this).closest('.product').fadeOut("normal", function() {
$(this).closest('.product').remove();
});
}
});
}));
});
Everything above in the controller works fine as well, here is what it returns:
return response()->json(['ok' => 'ok']);
You cannot use this under success function because this is out scope . Just change your code like below :
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).attr("id");
var element=this;//getting current element click in variable
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'json',
success: function () {
window.alert("THIS ALERT COMMAND WORKS BUT THE FUNCTION DOESN'T!");
//passing variable
$(element).closest('.product').fadeOut("normal", function() {
$(element).closest('.product').remove();
});
}
});
}));
Please see my below code,
Controller -
public ActionResult AmountOwed()
{
int vehicleID = Convert.ToInt32(Request.Cookies["VehicleID"].Value);
var amountOwed = _PUSPERSContext.TblEOYPayments.Where(x => x.VehicleID == vehicleID).OrderByDescending(x => x.PaymentID).Take(1).Select(x => x.AmountOwed).ToList().FirstOrDefault();
return Json(amountOwed, JsonRequestBehavior.AllowGet);
}
This gives me the value I want but I now want to display it in a textbox in a partial view (_EOYPaymentsLayout.cshtml) -
<div class='form-group'>
#Html.LabelFor(m => m.TblEOYPayment.AmountOwed, new { title = "Amount Owed" })
#Html.TextBoxFor(m => m.TblEOYPayment.AmountOwed, new { title = "Amount Owed", #class = "form-control inputSizeMedium"})
</div>
I have have tried various things in my ajax code but I can never get the value into the view (this code is in the main view called Payments) -
$(document).ready(function () {
$('#addEOYPayment').click(function () {
$.ajax({
type: "GET",
url: "AmountOwed",
datatype: "Json",
success: function (data) {
$('#TblEOYPayment_AmountOwed').html(data.amountOwed);
}
});
});
});
Would be grateful for some advice. Thanks
Instead of return a json object, you can return a partial view
C#
public ActionResult AmountOwed()
{
int vehicleID =
Convert.ToInt32(Request.Cookies["VehicleID"].Value);
var amountOwed = _PUSPERSContext.TblEOYPayments.Where(x => x.VehicleID == vehicleID).OrderByDescending(x => x.PaymentID).Take(1).Select(x => x.AmountOwed).ToList().FirstOrDefault();
return PartialView("NameOfView.cshtml", amountOwed );
}
js
$(document).ready(function () {
$('#addEOYPayment').click(function () {
$.ajax({
type: "GET",
url: "AmountOwed",
datatype: "Json",
success: function (data) {
$('#TblEOYPayment_AmountOwed').html(data.responseText);
}
});
});
});
and your view may receive the type of thevariable amountOwed.
You must double check your url. Please do include the controller name. For an instance: URL: "\Home\AmountOwed\" + ID,
Thanks for the replies.
Finally got it working, it was just this:
$(document).ready(function () {
$('#addEOYPayment').click(function () {
$.ajax({
type: "GET",
url: "/Home/AmountOwed",
datatype: "Json",
success: function (data) {
$('#TblEOYPayment_AmountOwed').val(data);
}
});
});
});
So I'm having this ajax GET request to my API:
$(document).ready(function() {
//id=$("#id").val();
url="api.php/fcomment/"+5;
$.ajax({
type: "GET",
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data)
{
console.log(data);
alert(data);
$('.greeting-content').append(data.comment);
}
});
});
I get JSON data, results of it is:
[{"id":"5","comment":"Test","post_date":"18:17 18.05.2017","forum":"2","user":"0"},{"id":"8","comment":"Test2","post_date":"18:05 24.05.2017","forum":"2","user":"7"}]
I would like to get values out of JSON format, but nothing is added to div. If i add JSON.stringify around data then I get entire JSON but I need each attribute by itself
your accessing data.comment it's is undefined access like this data[0].comment
$('.greeting-content').append(data[0].comment);
You can use $.each to get all data
data = [{"id":"5","comment":"Test","post_date":"18:17 18.05.2017","forum":"2","user":"0"},{"id":"8","comment":"Test2","post_date":"18:05 24.05.2017","forum":"2","user":"7"}];
console.log(data[0].comment);
$.each(data,function(i,v){
console.log(data[i].comment);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You are getting collection you need loop over it
$.each(JSON.parse(data), function (i, data) {
var row = data; // data.comment
console.log(row);
});
OR
$.each(data, function (i, data) {
var row = data;
console.log(row);
});
I need validate user's nickname when the gonna registre in my proyect:
My Controller
$inputData = Input::get('nickname');
parse_str($inputData);
$informacion = array('nickname' => $inputData);
$regla = array('nickname'=>'required|unique:usuarios|alpha_num|min:6|max:15');
if($request->ajax()){
$usuarios = Usuarios::Usuarios();
$validar = Validator::make($informacion,$regla);
if($validar->fails()){
return Response()->json(array(
'fail' => true,
'errors' => $validar->getMessageBag()->toArray()));
}
else{
return Response()->json(array('success' => true, "message" => "Nombre de Usuario Disponible"));
}
}
My Script
$( "#validar" ).click(function( event ) {
var dato = $('#nickname').val();
var route = $('#form-sign-up').attr('action');
var tipo = $('#form-sign-up').attr('method');
var token = $('#form-sign-up #token').val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{nickname: dato},})
.fail(function(data){
$('#nickname-msj').html(data.errors);
$('#nickname-msj').fadeIn();
})
.done(function(data) {
$('#nickname-msj').html(data.message);
$('#nickname-msj').fadeIn();
});
});
.done works, but .fails not, and i need display that information to my user, because so they can know what is the problem, if someone can help me will be great.
I am using Laravel 5.2
Thank you.
The fails function of Ajax is triggered with a code different from 200. So you can return
if($validar->fails()) {
return response()->json($arrayHere, 400); //HTTP 400 error for bad request
}
So, just basically add 400 after your array, inside of json() function. When you don't specify the code, it defaults to 200.
Maybe also change your ajax request ? Or not
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{
nickname: dato
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
Hayush!
Been trying to transfer my Chrome extension to manifest 2. Everything is working except for one script which calls an ajax. I have a variable that contains a JSON content which needs to be transferred to the server.
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
For some reason the ajax part is not executed at all. No error message was triggered, nor in the server error log.
All of the inline scripts and scripts in general were included in the popup.js. So it's probably not the issue.
Any thoughts?
Thanks!
The following code works perfectly on previous manifest
function importbookmarks(){
$('#formadd').css('display','none');
$('#importing').css('display','block');
_gaq.push(['_trackEvent', 'chromextension','importbookmarks', username]);
chrome.bookmarks.getTree(function(bookmarks) {
sendlist(bookmarks);
});
}
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
// processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
}
});
}
The problem wasn't with the function. The button execution wasn't calling it correctly.
Here is the code I used to get the function to work in manifest 2
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("import-bookmarks").addEventListener("click", function () {
importbook();return;
});