passing ajax data another page. - javascript

I was following an on-line tutorial on JSON. I want to be able to pass the returned data to a results page however I cant get it to work. It just returns null. I am getting the data back because it shows up in the console. N00bie, Help please =)
success: function(data) {
console.log(data);
if(data.success){
resultObject.formSubmitionResult = data;
$.mobile.changePage("#results");
.
$(document).on("pageinit", "#results", function() {
console.log('pageinit event - #results only');
$('#results [data-role="content"]').append('This is a result of form submition: ' + resultObject.formSubmitionResult);
});
var resultObject = {
formSubmitionResult : null
};

Related

Error 500 When return View from controller during ajax call

i have to create ajax call when user clicks on checkboxes to fetch the specific jobs according to each checkbox category .
When in controller i return return \Response::json($jobs) The request works fine . But when im trying to return return View::make('jobs.alljobs')->with('jobs', $jobs); i got Error 500
JobController.php
$cat = Input::get('categories');
$jobs = Job::whereIn('category_id',$cat)->get();
return View::make('jobs.alljobs')->with('jobs', $jobs);
AJAX Call function
function filterCategories(){
//Mark : Categories filters jquery
var categories = [];
// Listen for 'change' event
$('input[name="cat[]"]').on('change', function (e) {
e.preventDefault();
categories = []; // reset
$('input[name="cat[]"]:checked').each(function()
{
categories.push($(this).val());
});
console.log(categories);
//Send request
$.ajax({
url: '/jobs/searchcat',
type: 'POST',
data: {categories:categories},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function(response){
console.log(response);
}
})});}
Result when i return json
Error when i return view
Probably means that your script is throwing an uncaught error or exception when you return the view. Enable error logging and check your logs. Either of these pages might help with that.
https://laravel.com/docs/5.8/errors
https://laravel.com/docs/5.8/logging

AJAX: Having trouble retrieving queryset from server and appending to select options

I am able to send the value of the input field with the id datepicker to the server. And with this in the view I filter the time slot by the ones that occur on the same date.
Where I am having difficulties is sending this queryset to the browser and then appending this to the options.
I'm still relatively new to javascript I apologize if this is a newb question. I definitely appreciate any feedback!
My View:
if request.is_ajax():
selected_date = request.POST['selected_date']
slots_on_day = Calendar.objects.filter(date=selected_date)
return HttpResponse(slots_on_day)
My Javascript:
$(document).ready(function() {
$("#datepicker").change(function(){
document.getElementById("display_slots").style.display ="block";
$.ajax({
type: 'POST',
data: {
'selected_date':$('#datepicker').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: function(resp){
for (var i=0; i < resp['slots_on_day'].length;++i){
addOption(
document.getElementById("display_slots"), resp['slots_on_day'][i], resp['slots_on_day'][i]);
}
}
});
});
});
Notes: the id=datepicker field triggers the ajax event. I then want to receive the response from the server and append the options to the input with the id=display_slots
Error:
TypeError: resp.slots_on_day is undefined
Updated ajax success
success: function(data){
$.each(data, function(key, value){
$('select[name=display_slots]').append('<option value="' + key + '">' + value +'</option>');
});
}
from django.forms.models import model_to_dict
if request.is_ajax():
selected_date = request.POST['selected_date']
slots_on_day = Calendar.objects.filter(date=selected_date)
data = []
for cal in slots_on_day:
data.append(model_to_dict(cal))
return JsonResponse(status=200, data={'slots_on_day':data})
It'll send JSON response in frontend and now you can use this data as you want to use. I think, It'll work with your current ajax success method code

Ajax success/error message only displaying once

I have created a form using php ajax and JavaScript.
With ajax I successfully managed to display an error/success message while staying on the same page.
It works alright if I use console.log to display the error/success message.
But I don't want to display the error message on the console.log
so this is what I did:
$('form.form-style-4').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
$('#success-message').html(response);
setTimeout(function() {
$('#success-message').fadeOut('slow');
}, 3000);
}
});
return false;
});
As you can see I created a div called #success-message the reponse is displayed in this div.
My problem now is It only shows the error or success message just once, unless I reload the page.
So my first idea was to reload the entire page every time someone clicks on submit, with javascript like this:
setTimeout(function() {
window.location.reload(1);
}, 2000);
But I don't think that is the way to go.
You have to show your message success-message first
$('#success-message').html(response).show();

Having a hard time understanding redirecting / routing in laravel

I am completely stuck since two hours and definitely need your help. Disclaimer: I am not a coder - just a guy who is trying to mock up an idea.
So my page is actually working fine but I thought about moving content from a modal-popup to an actual sub-page. Meaning: If a user clicks on a button, some data points from the current page are being collected and passed to another view which shall be rendered using the data points as input.
EDIT: For clarification: The button is on /results.php where data is generated dynamically. The method should take some data points from here and generate a new view and render it at /buy.php or maybe at /buy/custom.php
My thoughts:
Normal redirect without parameters: Internal Link
Updating page-content without redirect but with parameters: Ajax
So combining my thoughts -> use ajax and return a new fresh view.
What I tried:
$("body").on("click", ".fa-shopping-cart", function() {
var $para1 = $(this).attr("data1");
var $para2 = $(this).attr("data2");
var $para3 = $(this).attr("data3");
var $para4 = $(this).attr("data4");
$.ajax({
url: "buy",
data: {
a: $para1,
b: $para2,
c: $para3,
d: $para4
},
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
type: "post",
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});});
Routing:
Route::post('/buy', 'PageRouting#buy');
Controller:
public function buy()
{
$para1= $_POST['a'];
$para2 = $_POST['b'];
$para3 = $_POST['c'];
$para4 = $_POST['d'];
// some magic to output $data
return view('pages.buy', compact("data"));
}
buy.blade.php exists and displays $data with help of an foreach-loop.
So, when I first clicked the button the obvious happend:
The view ('pages.buy') is logged / displayed in my console in plain html and not rendered in the browser.
Now I am sitting here since two hours and I have no clue whatsoever. I read some blog post saying that you cannot redirect within an ajax-call. Unfortunately the post did not gave any hint on how to do it instead.
Can someone help me?
All best
If you want to replace entire document with the response you have to use document.write but it's not the best thing to do. Why don't you use normal form submit if you need to return a view?
success: function(response){
document.write(response);
},
P.S. if you want also to change the url, use the history manipulation functions.
https://developer.mozilla.org/en-US/docs/Web/API/History_API
in your buy method -
public function buy ()
{
....//some stuff to get $data
$html = view('pages.buy', compact("data"))->render();
return response()->json([
'success' => true,
'html' => $html
])
}
in your ajax success function
success: function(response){
if(response.success)
{
$('#elementId').html(reponse.html) // or whatever you need
}
},

JQuery AJAX function not receiving PHP-returned text

I've been searching for a while for a solution to this problem. I've found many people with the same problem, but not the same solution.
The issue I'm having is that PHP is not returning any data to the AJAX function. The alert spits out data = undefined. As you can see, using return instead of echo is not the problem. I know that the PHP script I call completes correctly because the values are properly inserted into the database. No matter where I place the echo statement, I can't get it to return the value. Am I using the data variable incorrectly? Is returnValue not the proper variable to use? Has any of the functionality I've been trying to use been deprecated? I'm really at a complete loss. I can't see why this is failing.
//AJAX function
$("document").ready(function(){
$("#add_interest_form").submit(function(event) {
event.preventDefault();
$("#output").html("");
var values = $(this).serialize();
$.ajax
({
url: "./php/add_interest.php",
type: "POST",
data: values,
success: function(data) {
alert('data = ' + data.returnValue);
$("#output").html(data.returnValue);
},
error: function() {
alert('failed adding to database. Please try again or contact the Webmaster.');
}
});
});
});
//PHP snippet
echo 'Success!';
Just do alert('data = ' + data); instead of alert('data = ' + data.returnValue);.

Categories

Resources