I am trying to make sure the data i got from an ajax is passed onto my view. I actually got success with that but on page refresh the data disappears. Here is my jquery code
$(document).ready(function(){
$('#Item').hide();
$('#submitButton').hide();
$("#cartIcon").click(function(){
var id = $('#id').val();
console.log(id);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST', // Type of response and matches what we said in the route
url: '/addtocart/', // This is the url we gave in the route
dataType: 'JSON',
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
$('#subtotal').html(response.totalPrice);
$('#total').html(response.totalPrice);
$('#Item').show();
$('#noItem').hide();
$('#submitButton').show();
}
});
});
});
How do i make my .html response remain after page reload
Save the data into a cookie or local storage. Every time the page loads, you'll need to check if there is some data in the local storage to show.
as they mentioned, you could use LocalStorage:
$(document).ready(function(){
$('#Item').hide();
$('#submitButton').hide();
function load_data(){
var current;
current = localStorage.getItem("cartData");
if(current == null || current == undefined){
return ;
}
current = JSON.parse(current);
$('#subtotal').html(current.totalPrice);
$('#total').html(current.totalPrice);
}
load_data();
$("#cartIcon").click(function(){
var id = $('#id').val();
console.log(id);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST', // Type of response and matches what we said in the route
url: '/addtocart/', // This is the url we gave in the route
dataType: 'JSON',
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
$('#subtotal').html(response.totalPrice);
$('#total').html(response.totalPrice);
localStorage.setItem("cartData",JSON.stringify({"totalPrice":response.totalPrice}));
$('#Item').show();
$('#noItem').hide();
$('#submitButton').show();
}
});
});
});
Related
Want to Access Show function data through AJAX, but it returns error when i passed id variable in route
Contoller
public function show($id)
{
$features['UnitFeatures'] = UnitFeatures::find($id);
return $features;
}
View Blade File
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var feature_id = $('#unitFeatures').val();
$.ajax({
url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Please give me a solution
The problem is that you cannot access a JS variable in your {{}} PHP code.
You will have to get the route uri and replace the placeholder manually in your JS code.
You can get the URI of your Route with this piece of code:
\Route::getRoutes()->getByName('unitfeatures.show ')->uri
This returns the uri as a string like that: /sometext/{id}
Now you can simply replace the {id} with the feature_id by using str.replace() or whatever function you like.
var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
url: origUrl.replace('{id}', feature_id),
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Problem With You are using Javascript Variable in PHP Code You can use Javascript Variable After Execution of PHP Code treated as a String.
$.ajax({
url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.
I am trying to retrieve certain values in a JSON object retrieved from AJAX.
Using console.log(), I was able to view these:
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
Now I want to try storing the whole JSON object above so that I can use the userId and match it with another list of data to find the user who made the post. Problem is, I can't store it to a global variable. Here is my jscript snippet:
var postJson; //global variable
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
console.log(response);
}
});
I also tried doing postJson = $.ajax but nothing happened and postJson continues to be undefined.
$.ajax is async function, you need to use callback or do all the code in success function
var postJson; //global variable
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//do something with postJson or call function doSomething(response)
}
});
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
doSomething(response);
//do something with postJson or call function doSomething(response)
}
});
You can do directly via calling function from response no need to declare variable. Hope it will also helps you
I am creating a json object in which I am pulling fields from form and then using jquery Ajax POST to send the data. But when I see my network tab after pressing submit I basically get the json headers but all the values that should have been pulled from the form are blank except the values I am hardcoding. Note that my json data also has a nested json of type room.
Below is my jquery part:-
var formData={
"checkInDate": $("#checkInDate").val(),
"checkOutDate": $("#checkOutDate").val(),
"roomsWanted":$("#roomsWanted").val(),
"room":{
roomType: $("input[name=roomType]:checked").val(),
roomProperty:"non-smoking"
}
};
$("#checkAvailabilityForm").submit(function(e){
e.preventDefault();
$.ajax({
type: 'post',
url: '',
dataType: 'json',
data: JSON.stringify(formData),
contentType: 'application/json',
success: function(dataRecieved){
var dataRecieved= $.trim(dataRecieved);
if(dataRecieved === ''){
}else{
}
}
});
});
Move your declaration of formData inside of the .submit() function. The way you have it now the page loads, and then var formData = ... immediately sets the value for formData (to the values of the new empty form).
Your code should look like this:
$("#checkAvailabilityForm").submit(function(e){
e.preventDefault();
var formData={
"checkInDate": $("#checkInDate").val(),
"checkOutDate": $("#checkOutDate").val(),
"roomsWanted":$("#roomsWanted").val(),
"room":{
roomType: $("input[name=roomType]:checked").val(),
roomProperty:"non-smoking"
}
};
$.ajax({
type: 'post',
url: '',
dataType: 'json',
data: JSON.stringify(formData),
contentType: 'application/json',
success: function(dataRecieved){
var dataRecieved= $.trim(dataRecieved);
if(dataRecieved === ''){
}else{
}
}
});
});
You don't need to stringify your json just past the json as it
data: formData
I do an ajax call to get a list of all elements, say Products and populate them in a table with checkboxes. Then I make another ajax call to get which products were already selected and select them. This works in all browsers except ie. Am I doing something wrong?
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});
This is due to caching by IE.
Please try this
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});
and if you need more details please look into this
The thing in this code that always screws me up is trying to get the check box selected. Make sure obj[0].checked = true actually works.