Sammy.js does not get the location in Internet Explorer - sammy.js

Is there some explanation as when executing the following :
location.hash = "#/";
it works well in firefox (19.0.2) but not in IE (10.0.92).
In firefox it returns to the "homepage", whereas in IE it does nothing. No error shown either.
this code comes from this function :
self.addStoreItem = function () {
var data = appFsMvc.utility.serializeObject( $("#StoreItemForm") );
$.ajax({
url: "/api/StoreItems",
data: JSON.stringify( data ),
type: "POST",
dataType: "json",
contentType: "application/json"
})
.done(function () {
toastr.success( "You have successfully created a new StoreItem!", "Success!" );
self.StoreItems.push(data);
location.hash = "#/";
})
.fail(function () {
toastr.error( "There was an error creating your new StoreItem", "<sad face>" );
});
};
and the code to manage sammy.js :
appFsMvc.App = function( StoreItemsViewModel ) {
return $.sammy( "#content", function () {
var self = this;
this.use( Sammy.Cache );
this.StoreItemViewModel = StoreItemsViewModel;
this.renderTemplate = function ( html ) {
self.$element().html( html );
ko.applyBindings( self.StoreItemViewModel );
};
// display all StoreItems
this.get( "#/", function() {
this.render("/Templates/StoreItemDetail.htm", {}, function ( html ) {
self.renderTemplate( html );
});
});
// display the create StoreItems view
this.get( "#/create", function() {
this.render("/Templates/StoreItemCreate.htm", {}, function ( html ) {
self.renderTemplate( html );
});
});
});
};
I have tried to use firbuglite, but this latter ends up in crash when I try using it on my website. Developers tool of IE do not show any errors.
[EDIT]
found how to enable firebuglite using getfirebug.com/firebuglite#Debug instead of stable release :
the console is giving me these hints :
when clicking on CreateNewItem
[Thu Mar 21 15:38:11 UTC+0100 2013] #content runRoute get /#/create
GET /Templates/StoreItemCreate.htm 200 OK 5ms
POST /api/StoreItems 200 OK 7ms
whereas doing the same in Firefox gives me :
[Thu Mar 21 2013 15:40:41 GMT+0100] #content runRoute get /#/create
GET http://myLocalHost:9501/Templates/StoreItemCreate.htm 200 OK 1ms
POST http://myLocalHost:9501/api/StoreItems 200 OK 27ms
[Thu Mar 21 2013 15:40:46 GMT+0100] #content runRoute get /#/
I can see in IE the url in the adress bar giving the correct url http://localhost:9501/#/create and then http://localhost:9501/#/ after posting my form.
[/EDIT]

Related

Saving blob image in laravel's controller

In my Laravel 5/vuejs 2.6 I upload an image with the vue-upload-component and am sending a requested image blob
I try to save it with the controller code like :
if ( !empty($requestData['avatar_filename']) and !empty($requestData['avatar_blob']) ) {
$dest_image = 'public/' . Customer::getUserAvatarPath($newCustomer->id, $requestData['avatar_filename']);
$requestData['avatar_blob']= str_replace('blob:','',$requestData['avatar_blob']);
Storage::disk('local')->put($dest_image, file_get_contents($requestData['avatar_blob']));
ImageOptimizer::optimize( storage_path().'/app/'.$dest_image, null );
} // if ( !empty($page_content_image) ) {
As result, I have an image uploaded, but it is not readable.
The source file has 5 Kib, the resulting file has 5.8 Kib and in the browser's console I see the blobs path as
avatar_blob: "blob:http://local-hostels2.com/91a18493-36a7-4023-8ced-f5ea4a3c58af"
Have do I convert my blob to save it correctly?
MODIFIED :
a bit more detailed :
In vue file I send request using axios :
let customerRegisterArray =
{
username: this.previewCustomerRegister.username,
email: this.previewCustomerRegister.email,
first_name: this.previewCustomerRegister.first_name,
last_name: this.previewCustomerRegister.last_name,
account_type: this.previewCustomerRegister.account_type,
phone: this.previewCustomerRegister.phone,
website: this.previewCustomerRegister.website,
notes: this.previewCustomerRegister.notes,
avatar_filename: this.previewCustomerRegister.avatarFile.name,
avatar_blob: this.previewCustomerRegister.avatarFile.blob,
};
console.log("customerRegisterArray::")
console.log(customerRegisterArray)
axios({
method: ('post'),
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
}).then((response) => {
this.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
alert( "SAVED!!::"+var_dump() )
}).catch((error) => {
});
and this.previewCustomerRegister.avatarFile.blob has value: "blob:http://local-hostels2.com/91a18493-36a7-4023-8ced-f5ea4a3c58af"
where http://local-hostels2.com is my hosting...
I set this value to preview image defined as :
<img
class="img-preview-wrapper"
:src="previewCustomerRegister.avatarFile.blob"
alt="Your avatar"
v-show="previewCustomerRegister.avatarFile.blob"
width="256"
height="auto"
id="preview_avatar_file"
>
and when previewCustomerRegister.avatarFile.blob is assigned with uploaded file I see it in preview image.
I show control with saving function in first topic but when I tried to opened my generated file with kate, I found that it
has content of my container file resources/views/index.blade.php...
What I did wrong and which is the valid way ?
MODIFIED BLOCK #2 :
I added 'Content-Type' in request
axios({
method: ('post'),
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
headers: {
'Content-Type': 'multipart/form-data'
}
but with it I got validation errors in my control, as I define control action with request:
public function store(CustomerRegisterRequest $request)
{
and in app/Http/Requests/CustomerRegisterRequest.php :
<?php
namespace App\Http\Requests;
use App\Http\Traits\funcsTrait;
use Illuminate\Foundation\Http\FormRequest;
use App\Customer;
class CustomerRegisterRequest extends FormRequest
{
use funcsTrait;
public function authorize()
{
return true;
}
public function rules()
{
$request= Request();
$requestData= $request->all();
$this->debToFile(print_r( $requestData,true),' getCustomerValidationRulesArray $requestData::');
/* My debugging method to write data to text file
and with Content-Type defined above I see that $requestData is always empty
and I got validations errors
*/
// Validations rules
$customerValidationRulesArray= Customer::getCustomerValidationRulesArray( $request->get('id'), ['status'] );
return $customerValidationRulesArray;
}
}
In routes/api.php defined :
Route::post('customer_register_store', 'CustomerRegisterController#store');
In the console of my bhrowser I see : https://imgur.com/a/0vsPIsa, https://imgur.com/a/wJEbBnP
I suppose that something is wrong in axios header ? without 'Content-Type' defined my validation rules work ok...
MODIFIED BLOCK #3
I managed to make fetch of blob with metod like :
var self = this;
fetch(this.previewCustomerRegister.avatarFile.blob) .then(function(response) {
console.log("fetch response::")
console.log( response )
if (response.ok) {
return response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
// myImage.src = objectURL;
console.log("objectURL::")
console.log( objectURL )
console.log("self::")
console.log( self )
let customerRegisterArray =
{
username: self.previewCustomerRegister.username,
email: self.previewCustomerRegister.email,
first_name: self.previewCustomerRegister.first_name,
last_name: self.previewCustomerRegister.last_name,
account_type: self.previewCustomerRegister.account_type,
phone: self.previewCustomerRegister.phone,
website: self.previewCustomerRegister.website,
notes: self.previewCustomerRegister.notes,
avatar_filename: self.previewCustomerRegister.avatarFile.name,
avatar: objectURL,
};
console.log("customerRegisterArray::")
console.log(customerRegisterArray)
axios({
method: 'POST',
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
// headers: {
// 'Content-Type': 'multipart/form-data' // multipart/form-data - as we need to upload with image
// }
}).then((response) => {
self.is_page_updating = false
self.message = ''
self.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
alert( "SAVED!!::")
}).catch((error) => {
self.$setLaravelValidationErrorsFromResponse(error.response.data);
self.is_page_updating = false
self.showRunTimeError(error, this);
self.showPopupMessage("Customer Register", 'Error adding customer ! Check Details fields !', 'warn');
// window.grecaptcha.reset()
self.is_recaptcha_verified = false;
self.$refs.customer_register_wizard.changeTab(3,0)
});
});
} else {
return response.json().then(function(jsonError) {
// ...
});
}
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
In objectURL and self I see proper values : https://imgur.com/a/4YvhbFz
1) But checking data on server in laravel's control I see the same values I had at start of my attemps to upload image:
[avatar_filename] => patlongred.jpg
[avatar] => blob:http://local-hostels2.com/d9bf4b66-42b9-4990-9325-a72dc8c3a392
Have To manipulate with fetched bnlob in some other way ?
2) If I set :
headers: {
'Content-Type': 'multipart/form-data'
}
I got validation errors that my data were not correctly requested...
?
You're using request type as application/json hence you won't be able to save the image this way, for a file upload a request type should be multipart/form-data in this case you'll need to send request as
let customerRegisterArray = new FormData();
customerRegisterArray.put('username', this.previewCustomerRegister.username);
customerRegisterArray.put('email', this.previewCustomerRegister.email);
....
customerRegisterArray.put('avatar', this.previewCustomerRegister.avatarFile);
console.log("customerRegisterArray::")
console.log(customerRegisterArray)
axios({
method: ('post'),
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((response) => {
this.showPopupMessage("Customer Register", 'Customer added successfully !Check entered email for activation link !', 'success');
alert( "SAVED!!::"+var_dump() )
}).catch((error) => {});
Thank you for your help!
Valid decision was :
var self = this;
fetch(this.previewCustomerRegister.avatarFile.blob) .then(function(response) {
if (response.ok) {
return response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
let data = new FormData()
data.append('username', self.previewCustomerRegister.username)
data.append('email', self.previewCustomerRegister.email)
data.append('first_name', self.previewCustomerRegister.first_name)
data.append('last_name', self.previewCustomerRegister.last_name)
data.append('account_type', self.previewCustomerRegister.account_type)
data.append('phone', self.previewCustomerRegister.phone)
data.append('website', self.previewCustomerRegister.website)
data.append('notes', self.previewCustomerRegister.notes)
data.append('avatar_filename', self.previewCustomerRegister.avatarFile.name)
data.append('avatar', myBlob)
axios({
method: 'POST',
url: window.API_VERSION_LINK + '/customer_register_store',
data: data,
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data' // multipart/form-data - as we need to upload with image
}
}).then((response) => {
self.is_page_updating = false
self.message = ''
self.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
alert( "SAVED!!::123")
// self.$router.push({path: '/'});
}).catch((error) => {
self.$setLaravelValidationErrorsFromResponse(error.response.data);
self.is_page_updating = false
self.showRunTimeError(error, this);
self.showPopupMessage("Customer Register", 'Error adding customer ! Check Details fields !', 'warn');
window.grecaptcha.reset()
self.is_recaptcha_verified = false;
self.$refs.customer_register_wizard.changeTab(3,0)
});
});
} else {
return response.json().then(function(jsonError) {
// ...
});
}
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
and common laravel's file uploading functionality :
$customerAvatarUploadedFile = $request->file('avatar');
...

Test dynamic url in protractor

I have written a protractor test code that will pull the url of a blog. Each time a new blog post, the last url will be updated and will be shown on the website. I want to check whether the url is returning 404 or 200. if 404 comes, the test will be failed. Below is my code
describe('Writing to wiki how', function() {
browser.waitForAngularEnabled(false);
browser.sleep(1000);
it('test commmunity', function () {
browser.get('https://www.debtconsolidationcare.com/');
browser.sleep(5000);
var knowhowimg = element(by.id('knowhowimg')).getAttribute("src").then(function (value) {
console.log(value); //want to test if this returns 200
browser.sleep(5000);
});
var knowhowimghref = element(by.id('knowhowimghref')).getAttribute("href").then(function (value) {
console.log(value); //want to test if this returns 200
browser.sleep(5000);
});
var knowhowheadhref = element(by.id('knowhowheadhref')).getAttribute("href").then(function (value) {
console.log(value); //want to test if this returns 200
browser.sleep(5000);
Those 3 console.log returns proper URL. I want to test those 3 urls that comes in console.log
The Request package is what you are looking for.
Example Usage:
var request = require('request');
describe('Writing to wiki how', function() {
browser.waitForAngularEnabled(false);
browser.sleep(1000);
it('Tests Community', function() {
element(by.id('knowhowimg')).getAttribute("src").then(function (value) {
request(value,function(error, response, body){
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
expect(response.statusCode).toBe(200);
});
});
});
Without using the Request package (will likely take longer due to having to fully load the page)
describe('Writing to wiki how', function() {
browser.waitForAngularEnabled(false);
browser.sleep(1000);
it('Tests Community', function() {
element(by.id('knowhowimg')).getAttribute("src").then(function (value) {
browser.get(value);
expect(element(by.css('div.ElementOnNewPage')).isPresent()).toBeTruthy(); //define an element that exists ONLY on the new page here
});
});
The main difference is that you are checking for an element that is on the next page to appear, thus proving that the page loaded.

CasperJs Google login

I having been working on some code to access my google CSE
For that I need to sign in with my google account.
I have the following code:
var casper = require('casper').create({
verbose: true,
logLevel: 'debug',
waitTimeout: 5000,
clientScripts: ["libs/jquery.min.js"],
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)
AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
});
const google_email = "MY_EMAIL";
const google_passwd = "MY_PASSWORD";
const loginUrl = 'https://accounts.google.com';
casper.start(loginUrl, function() {
this.waitForSelector('#view_container > form');
});
casper.then(function() {
this.fillSelectors('#view_container > form', {
'input[name="identifier"]': google_email
}, false);
});
casper.then(function() {
this.click('#identifierNext');
});
casper.wait(500, function() { //Wait for next page to load
this.capture('images/step01.png');
});
casper.then(function() {
this.evaluate(function () {
var identifierNext = $('#identifierNext');
identifierNext.click();
});
});
casper.then(function() {
this.capture('images/step02.png');
});
casper.run(function() {
this.echo("Done");
});
The part of entering the email seems to work.
But the click part isn't working.
I found this but it seems outdated.
Thanks
I haven't fixed the issue related to the new form, but we found a way to access the old form, so the "old" scripts should still work, and that solution is disabling JS. For that, change the loginUrl to
https://accounts.google.com/ServiceLogin?passive=1209600&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount&followup=https%3A%2F%2Faccounts.google.com%2FManageAccount&flowName=GlifWebSignIn&flowEntry=ServiceLogin&nojavascript=1#identifier
Important thing: nojavascript=1
We are using the script posted in Casperjs Google Login Not working
Just changing the login URL.
Try this - a lot more delays are needed to wait for the dynamically loaded pages.
casper.options.verbose = true; // verbose reporting
casper.options.logLevel = 'debug'; // full log reporting
casper.options.exitOnError = false; // Keep going on error
const google_email = "EMAIL";
const google_passwd = "PASSWORD";
const loginUrl = 'https://accounts.google.com';
// Load the login page
casper.start(loginUrl, function() {
this.waitForSelector('#view_container'); // '> form' doesn't seem to work
});
// Fill in the 'username' form
casper.then(function() {
this.fill('form', {
identifier: google_email,
});
this.sendKeys('#view_container', casper.page.event.key.Enter , {keepFocus: true});
});
// First 'Enter' is too quick for Google, send another one after a pause
casper.wait(2500, function() {
this.sendKeys('#identifierId', casper.page.event.key.Enter , {keepFocus: true});
});
// Wait for the 'password' form
casper.waitForSelector("#passwordNext", function() {
this.echo("password form is apparently available");
});
// Password form seems to load slowly, even if the selector is found/visible, this delay ensures next form fill works
casper.wait(2500, function() {
this.echo("password form is really available");
});
// Fill in the 'password' form
casper.then(function() {
this.fill('form', {
password: google_passwd,
});
this.sendKeys('#view_container', casper.page.event.key.Enter , {keepFocus: true});
});
// First 'Enter' is too quick for Google, send another one after a pause
casper.wait(500, function() {
this.sendKeys('input.whsOnd.zHQkBf', casper.page.event.key.Enter , {keepFocus: true});
});
// Extend timeout to allow for slow dynamic page rendering
casper.options.waitTimeout = 25000;
casper.waitForSelector("#gb", function() {
this.echo("login complete");
});
casper.thenOpen('https://(google app you want)', function() {
// Check it opened okay
});

getjson does not work on production server but works on development machine

I have following javascript that is using a selection changed to fill in a select list.
$(function () {
$("#bedrijvenauto").each(function () {
var target = $(this);
var dest = target.attr("data-autocomplete-destination");
target.autocomplete({
source: target.attr("data-autocomplete-source"),
select: function (event, ui) {
alert('selected bedrijf');
event.preventDefault();
target.val(ui.item.label);
$(dest).val(ui.item.value);
$("#projectenauto").val("");
alert('selected bedrijf');
alert($('#BEDRIJF_ID').val());
$.getJSON("/Project/GetListViaJson", { bedrijf: $('#BEDRIJF_ID').val() }, function (data) {
alert('selected bedrijf');
alert(data);
$("#PROJECT_ID").empty();
$("#PROJECT_ID").append(new Option("Maak een selectie", 0));
for (var i = 0; i < data.length; ++i) {
alert(data[i].value + ' ' + data[i].label);
$("#PROJECT_ID").append(new Option(data[i].label, data[i].value));
}
});
},
focus: function (event, ui) {
event.preventDefault();
target.val(ui.item.label);
}
});
target.val($("#BEDRIJF_NAAM").val());
});
It works like a charm on my development pc. The alert are all coming out even the data is returning results. That is the difference with the development pc that does not give any results after the call to getJSON
I have the feeling I am missing a detail here.
I am not used to debugging on a webserver because I usually create GUI applications in WPF, and this is a student's work for his vacation and I now got to get it working without him being around anymore. Vacation is done :-(
But not for me.
The 404 error indicated in your comments means the url your creating is incorrect. Always make use of the #Url.Action() method to ensure they are correctly generated. In your script
var url = '#Url.Action("GetListViaJson", "Project")';
$.getJSON(url, { bedrijf: $('#BEDRIJF_ID').val() }, function (data) {
....
}
or if this is an external script, then add the var url = '#Url.Action(...)'; in the main view (razor code is not evaluated in external script files), or add it as a data- attribute to the element your handling
data-url = "#Url.Action(...)"
and get it again using var url = $(someElement).data('url');

ajax post , but I'm unable to receive data on the server

I have a form in jade , I'm posting form ajax way , there is not problem in ajax method but I'm unable to receive data on the server. Please help me solve this.Previously I have never come across this.
jade
form(accept-charset="UTF-8", action="/booking/get/trips", name="gettrips", method="post", enctype='multipart/form-data', id="gettrips")
p
label(for='from') From
select#from(name="fromCity", required="required")
each fromcity in cities
option(value="#{fromcity.cityId}") #{fromcity.cityName}
p.destination
label(for='to') To
select#to(name="toCity", required="required")
option select
p
label(for='datetimepicker') Depart
input#datetimepicker(type='text', name="departDate", value='2014-03-15')
p.mr-0
label(for='datetimepicker1')
input#chk(type='checkbox', name="returnDate", value='', checked='checked')
| Return
input#datetimepicker1(type='text', value='2014-03-15')
p
button(type="submit", value="find") look
booking.js
getTrips: function getTrips(req, res, next){
var options = {
fromCity :req.body.fromCity,
toCity : req.body.toCity,
departDate : req.body.departDate
};
console.log('date ' + req.body.departDate); // undefined
if (req.body.returndate) {
options.returnDate = req.body.returnDate;
}
console.log('got form info ' + JSON.stringify(options)); //gives null
},
js
function getTrips() {
var lookup = $('#gettrips');
lookup.submit(function (ev) {
$.ajax({
type: lookup.attr('method'),
url: lookup.attr('action'),
data: lookup.serialize(),
success: function (data) {
//ok send response
}
});
ev.preventDefault();
});
}
route
var booking = require('./booking');
module.exports = function (app) {
app.post('/booking/get/trips', booking.collectTripsInfo, booking.validateTripInfo, };

Resources